context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System.Collections.Generic;
using Android.Content;
using Android.Widget;
using Android.Graphics;
using Android.Util;
using System.Collections;
namespace PrintBot.Droid
{
class BordEditor_Bord : RelativeLayout
{
public BordEditor_Bord(Context context) : base(context, null, 0)
{
Init(context);
}
public BordEditor_Bord(Context context, IAttributeSet attrs) : base(context, attrs)
{
Init(context);
}
public BordEditor_Bord(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
{ //Init(context);
}
private List<BordEditor_DigitalPin> digitalPins = new List<BordEditor_DigitalPin>();
private List<BordEditor_AnalogPin> _analogPins = new List<BordEditor_AnalogPin>();
private BordEditor_Pin5V _pin5V;
private BordEditor_Pin3V _pin3V;
private BordEditor_PinVin _pinVin;
public List<BordEditor_AnalogPin> AnalogPins
{
get
{
return _analogPins;
}
set
{
_analogPins = value;
}
}
public BordEditor_Pin5V Pin5V
{
get
{
return _pin5V;
}
set
{
_pin5V = value;
}
}
public BordEditor_Pin3V Pin3V
{
get
{
return _pin3V;
}
set
{
_pin3V = value;
}
}
public BordEditor_PinVin PinVin
{
get
{
return _pinVin;
}
set
{
_pinVin = value;
}
}
public List<BordEditor_DigitalPin> DigitalPins
{
get
{
return digitalPins;
}
set
{
digitalPins = value;
}
}
public void Init(Context context)
{
this.SetBackgroundColor(Color.Aqua);
var scale = (int)PrintBot.Droid.Activities.BordEditor_MainActivity._scaleFactor;
var w = 100 * scale;
var h = 390 * scale;
var pinW = 25 * scale;
var pinH = 25 * scale;
var pinTransX = w - pinW;
var OffsetDec = 30 * scale;
var textX = w - 2 * pinW;
this.LayoutParameters = new LayoutParams(w, h);
float tmp = PrintBot.Droid.Activities.BordEditor_MainActivity._screenWidth / 2;
this.TranslationX = tmp - w / 2;
// digital
int yOffset = h - pinH;
for (int i = 0; i <= 13; i++)
{
BordEditor_DigitalPin pin = new BordEditor_DigitalPin(context);
pin.LayoutParameters = new LayoutParams(pinW, pinH);
pin.TranslationX = pinTransX;
pin.TranslationY = yOffset;
pin.parent = this;
pin.Nr = i;
this.AddView(pin);
DigitalPins.Add(pin);
pin.Text = i + "";
//AddText(textX, yOffset, i + "", context);
yOffset -= OffsetDec;
}
//Analog
yOffset = h - pinH;
for (int i = 0; i < 7; i++)
{
BordEditor_AnalogPin pin = new BordEditor_AnalogPin(context);
pin.LayoutParameters = new LayoutParams(pinW, pinH);
pin.TranslationX = 0;
pin.TranslationY = yOffset;
pin.parent = this;
pin.Nr = i;
this.AddView(pin);
AnalogPins.Add(pin);
pin.Text = $"A{i}";
//AddText(75, yOffset, $"A{i}", context);
yOffset -= OffsetDec;
}
// GND
yOffset -= 2*OffsetDec;
//5V
var pinV5 = new BordEditor_Pin5V(context);
pinV5.LayoutParameters = new LayoutParams(pinW, pinH);
pinV5.TranslationX = 0;
pinV5.TranslationY = yOffset;
pinV5.parent = this;
this.AddView(pinV5);
this._pin5V = pinV5;
pinV5.Text = "5V";
yOffset -= OffsetDec;
// 3V
var pinV3 = new BordEditor_Pin3V(context);
pinV3.LayoutParameters = new LayoutParams(pinW, pinH);
pinV3.TranslationX = 0;
pinV3.TranslationY = yOffset;
pinV3.parent = this;
this.AddView(pinV3);
this._pin3V = pinV3;
pinV3.Text = "3V";
yOffset -= OffsetDec;
// Vin
var pinVin = new BordEditor_PinVin(context);
pinVin.LayoutParameters = new LayoutParams(pinW, pinH);
pinVin.TranslationX = 0;
pinVin.TranslationY = yOffset;
pinVin.parent = this;
this.AddView(pinVin);
this._pinVin = pinVin;
pinVin.Text = "Vin";
}
private void AddText(float x, float y, string text, Context context)
{
TextView nr = new TextView(context);
nr.LayoutParameters = new LayoutParams(25, 25);
nr.SetTextSize(ComplexUnitType.Dip, 10f);
nr.SetTextColor(Color.Black);
nr.Text = text;
nr.TranslationX = x;
nr.TranslationY = y;
this.AddView(nr);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Caps=OpenSim.Framework.Capabilities.Caps;
using OSDArray=OpenMetaverse.StructuredData.OSDArray;
using OSDMap=OpenMetaverse.StructuredData.OSDMap;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
public class WorldMapModule : INonSharedRegionModule, IWorldMapModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string DEFAULT_WORLD_MAP_EXPORT_PATH = "exportmap.jpg";
private static readonly UUID STOP_UUID = UUID.Random();
private static readonly string m_mapLayerPath = "0001/";
private OpenSim.Framework.BlockingQueue<MapRequestState> requests = new OpenSim.Framework.BlockingQueue<MapRequestState>();
//private IConfig m_config;
protected Scene m_scene;
private List<MapBlockData> cachedMapBlocks = new List<MapBlockData>();
private int cachedTime = 0;
private byte[] myMapImageJPEG;
protected volatile bool m_Enabled = false;
private Dictionary<UUID, MapRequestState> m_openRequests = new Dictionary<UUID, MapRequestState>();
private Dictionary<string, int> m_blacklistedurls = new Dictionary<string, int>();
private Dictionary<ulong, int> m_blacklistedregions = new Dictionary<ulong, int>();
private Dictionary<ulong, string> m_cachedRegionMapItemsAddress = new Dictionary<ulong, string>();
private List<UUID> m_rootAgents = new List<UUID>();
private volatile bool threadrunning = false;
//private int CacheRegionsDistance = 256;
#region INonSharedRegionModule Members
public virtual void Initialise (IConfigSource config)
{
IConfig startupConfig = config.Configs["Startup"];
if (startupConfig.GetString("WorldMapModule", "WorldMap") == "WorldMap")
m_Enabled = true;
}
public virtual void AddRegion (Scene scene)
{
if (!m_Enabled)
return;
lock (scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IWorldMapModule>(this);
m_scene.AddCommand(
this, "export-map",
"export-map [<path>]",
"Save an image of the world map", HandleExportWorldMapConsoleCommand);
AddHandlers();
}
}
public virtual void RemoveRegion (Scene scene)
{
if (!m_Enabled)
return;
lock (m_scene)
{
m_Enabled = false;
RemoveHandlers();
m_scene = null;
}
}
public virtual void RegionLoaded (Scene scene)
{
}
public virtual void Close()
{
}
public Type ReplaceableInterface
{
get { return null; }
}
public virtual string Name
{
get { return "WorldMapModule"; }
}
#endregion
// this has to be called with a lock on m_scene
protected virtual void AddHandlers()
{
myMapImageJPEG = new byte[0];
string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString();
regionimage = regionimage.Replace("-", "");
m_log.Info("[WORLD MAP]: JPEG Map location: http://" + m_scene.RegionInfo.ExternalEndPoint.Address.ToString() + ":" + m_scene.RegionInfo.HttpPort.ToString() + "/index.php?method=" + regionimage);
MainServer.Instance.AddHTTPHandler(regionimage, OnHTTPGetMapImage);
MainServer.Instance.AddLLSDHandler(
"/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(), HandleRemoteMapItemRequest);
m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
m_scene.EventManager.OnNewClient += OnNewClient;
m_scene.EventManager.OnClientClosed += ClientLoggedOut;
m_scene.EventManager.OnMakeChildAgent += MakeChildAgent;
m_scene.EventManager.OnMakeRootAgent += MakeRootAgent;
}
// this has to be called with a lock on m_scene
protected virtual void RemoveHandlers()
{
m_scene.EventManager.OnMakeRootAgent -= MakeRootAgent;
m_scene.EventManager.OnMakeChildAgent -= MakeChildAgent;
m_scene.EventManager.OnClientClosed -= ClientLoggedOut;
m_scene.EventManager.OnNewClient -= OnNewClient;
m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
string regionimage = "regionImage" + m_scene.RegionInfo.RegionID.ToString();
regionimage = regionimage.Replace("-", "");
MainServer.Instance.RemoveLLSDHandler("/MAP/MapItems/" + m_scene.RegionInfo.RegionHandle.ToString(),
HandleRemoteMapItemRequest);
MainServer.Instance.RemoveHTTPHandler("", regionimage);
}
public void OnRegisterCaps(UUID agentID, Caps caps)
{
//m_log.DebugFormat("[WORLD MAP]: OnRegisterCaps: agentID {0} caps {1}", agentID, caps);
string capsBase = "/CAPS/" + caps.CapsObjectPath;
caps.RegisterHandler("MapLayer",
new RestStreamHandler("POST", capsBase + m_mapLayerPath,
delegate(string request, string path, string param,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
return MapLayerRequest(request, path, param,
agentID, caps);
}));
}
/// <summary>
/// Callback for a map layer request
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="agentID"></param>
/// <param name="caps"></param>
/// <returns></returns>
public string MapLayerRequest(string request, string path, string param,
UUID agentID, Caps caps)
{
//try
//{
//m_log.DebugFormat("[MAPLAYER]: request: {0}, path: {1}, param: {2}, agent:{3}",
//request, path, param,agentID.ToString());
// this is here because CAPS map requests work even beyond the 10,000 limit.
ScenePresence avatarPresence = null;
m_scene.TryGetAvatar(agentID, out avatarPresence);
if (avatarPresence != null)
{
bool lookup = false;
lock (cachedMapBlocks)
{
if (cachedMapBlocks.Count > 0 && ((cachedTime + 1800) > Util.UnixTimeSinceEpoch()))
{
List<MapBlockData> mapBlocks;
mapBlocks = cachedMapBlocks;
avatarPresence.ControllingClient.SendMapBlock(mapBlocks, 0);
}
else
{
lookup = true;
}
}
if (lookup)
{
List<MapBlockData> mapBlocks = new List<MapBlockData>(); ;
List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID,
(int)(m_scene.RegionInfo.RegionLocX - 8) * (int)Constants.RegionSize,
(int)(m_scene.RegionInfo.RegionLocX + 8) * (int)Constants.RegionSize,
(int)(m_scene.RegionInfo.RegionLocY - 8) * (int)Constants.RegionSize,
(int)(m_scene.RegionInfo.RegionLocY + 8) * (int)Constants.RegionSize);
foreach (GridRegion r in regions)
{
MapBlockData block = new MapBlockData();
MapBlockFromGridRegion(block, r);
mapBlocks.Add(block);
}
avatarPresence.ControllingClient.SendMapBlock(mapBlocks, 0);
lock (cachedMapBlocks)
cachedMapBlocks = mapBlocks;
cachedTime = Util.UnixTimeSinceEpoch();
}
}
LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
return mapResponse.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="mapReq"></param>
/// <returns></returns>
public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq)
{
m_log.Debug("[WORLD MAP]: MapLayer Request in region: " + m_scene.RegionInfo.RegionName);
LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
return mapResponse;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected static OSDMapLayer GetOSDMapLayerResponse()
{
OSDMapLayer mapLayer = new OSDMapLayer();
mapLayer.Right = 5000;
mapLayer.Top = 5000;
mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006");
return mapLayer;
}
#region EventHandlers
/// <summary>
/// Registered for event
/// </summary>
/// <param name="client"></param>
private void OnNewClient(IClientAPI client)
{
client.OnRequestMapBlocks += RequestMapBlocks;
client.OnMapItemRequest += HandleMapItemRequest;
}
/// <summary>
/// Client logged out, check to see if there are any more root agents in the simulator
/// If not, stop the mapItemRequest Thread
/// Event handler
/// </summary>
/// <param name="AgentId">AgentID that logged out</param>
private void ClientLoggedOut(UUID AgentId, Scene scene)
{
List<ScenePresence> presences = m_scene.GetAvatars();
int rootcount = 0;
for (int i=0;i<presences.Count;i++)
{
if (presences[i] != null)
{
if (!presences[i].IsChildAgent)
rootcount++;
}
}
if (rootcount <= 1)
StopThread();
lock (m_rootAgents)
{
if (m_rootAgents.Contains(AgentId))
{
m_rootAgents.Remove(AgentId);
}
}
}
#endregion
/// <summary>
/// Starts the MapItemRequest Thread
/// Note that this only gets started when there are actually agents in the region
/// Additionally, it gets stopped when there are none.
/// </summary>
/// <param name="o"></param>
private void StartThread(object o)
{
if (threadrunning) return;
threadrunning = true;
m_log.Debug("[WORLD MAP]: Starting remote MapItem request thread");
Watchdog.StartThread(process, "MapItemRequestThread", ThreadPriority.BelowNormal, true);
}
/// <summary>
/// Enqueues a 'stop thread' MapRequestState. Causes the MapItemRequest thread to end
/// </summary>
private void StopThread()
{
MapRequestState st = new MapRequestState();
st.agentID=STOP_UUID;
st.EstateID=0;
st.flags=0;
st.godlike=false;
st.itemtype=0;
st.regionhandle=0;
requests.Enqueue(st);
}
public virtual void HandleMapItemRequest(IClientAPI remoteClient, uint flags,
uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
{
lock (m_rootAgents)
{
if (!m_rootAgents.Contains(remoteClient.AgentId))
return;
}
uint xstart = 0;
uint ystart = 0;
Utils.LongToUInts(m_scene.RegionInfo.RegionHandle, out xstart, out ystart);
if (itemtype == 6) // we only sevice 6 right now (avatar green dots)
{
if (regionhandle == 0 || regionhandle == m_scene.RegionInfo.RegionHandle)
{
// Local Map Item Request
List<ScenePresence> avatars = m_scene.GetAvatars();
int tc = Environment.TickCount;
List<mapItemReply> mapitems = new List<mapItemReply>();
mapItemReply mapitem = new mapItemReply();
if (avatars.Count == 0 || avatars.Count == 1)
{
mapitem = new mapItemReply();
mapitem.x = (uint)(xstart + 1);
mapitem.y = (uint)(ystart + 1);
mapitem.id = UUID.Zero;
mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString());
mapitem.Extra = 0;
mapitem.Extra2 = 0;
mapitems.Add(mapitem);
}
else
{
foreach (ScenePresence av in avatars)
{
// Don't send a green dot for yourself
if (av.UUID != remoteClient.AgentId)
{
mapitem = new mapItemReply();
mapitem.x = (uint)(xstart + av.AbsolutePosition.X);
mapitem.y = (uint)(ystart + av.AbsolutePosition.Y);
mapitem.id = UUID.Zero;
mapitem.name = Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString());
mapitem.Extra = 1;
mapitem.Extra2 = 0;
mapitems.Add(mapitem);
}
}
}
remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags);
}
else
{
// Remote Map Item Request
// ensures that the blockingqueue doesn't get borked if the GetAgents() timing changes.
// Note that we only start up a remote mapItem Request thread if there's users who could
// be making requests
if (!threadrunning)
{
m_log.Warn("[WORLD MAP]: Starting new remote request thread manually. This means that AvatarEnteringParcel never fired! This needs to be fixed! Don't Mantis this, as the developers can see it in this message");
StartThread(new object());
}
RequestMapItems("",remoteClient.AgentId,flags,EstateID,godlike,itemtype,regionhandle);
}
}
}
/// <summary>
/// Processing thread main() loop for doing remote mapitem requests
/// </summary>
public void process()
{
try
{
while (true)
{
MapRequestState st = requests.Dequeue(1000);
// end gracefully
if (st.agentID == STOP_UUID)
break;
if (st.agentID != UUID.Zero)
{
bool dorequest = true;
lock (m_rootAgents)
{
if (!m_rootAgents.Contains(st.agentID))
dorequest = false;
}
if (dorequest)
{
OSDMap response = RequestMapItemsAsync("", st.agentID, st.flags, st.EstateID, st.godlike, st.itemtype, st.regionhandle);
RequestMapItemsCompleted(response);
}
}
Watchdog.UpdateThread();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[WORLD MAP]: Map item request thread terminated abnormally with exception {0}", e);
}
threadrunning = false;
Watchdog.RemoveThread();
}
/// <summary>
/// Enqueues the map item request into the processing thread
/// </summary>
/// <param name="state"></param>
public void EnqueueMapItemRequest(MapRequestState state)
{
requests.Enqueue(state);
}
/// <summary>
/// Sends the mapitem response to the IClientAPI
/// </summary>
/// <param name="response">The OSDMap Response for the mapitem</param>
private void RequestMapItemsCompleted(OSDMap response)
{
UUID requestID = response["requestID"].AsUUID();
if (requestID != UUID.Zero)
{
MapRequestState mrs = new MapRequestState();
mrs.agentID = UUID.Zero;
lock (m_openRequests)
{
if (m_openRequests.ContainsKey(requestID))
{
mrs = m_openRequests[requestID];
m_openRequests.Remove(requestID);
}
}
if (mrs.agentID != UUID.Zero)
{
ScenePresence av = null;
m_scene.TryGetAvatar(mrs.agentID, out av);
if (av != null)
{
if (response.ContainsKey(mrs.itemtype.ToString()))
{
List<mapItemReply> returnitems = new List<mapItemReply>();
OSDArray itemarray = (OSDArray)response[mrs.itemtype.ToString()];
for (int i = 0; i < itemarray.Count; i++)
{
OSDMap mapitem = (OSDMap)itemarray[i];
mapItemReply mi = new mapItemReply();
mi.x = (uint)mapitem["X"].AsInteger();
mi.y = (uint)mapitem["Y"].AsInteger();
mi.id = mapitem["ID"].AsUUID();
mi.Extra = mapitem["Extra"].AsInteger();
mi.Extra2 = mapitem["Extra2"].AsInteger();
mi.name = mapitem["Name"].AsString();
returnitems.Add(mi);
}
av.ControllingClient.SendMapItemReply(returnitems.ToArray(), mrs.itemtype, mrs.flags);
}
}
}
}
}
/// <summary>
/// Enqueue the MapItem request for remote processing
/// </summary>
/// <param name="httpserver">blank string, we discover this in the process</param>
/// <param name="id">Agent ID that we are making this request on behalf</param>
/// <param name="flags">passed in from packet</param>
/// <param name="EstateID">passed in from packet</param>
/// <param name="godlike">passed in from packet</param>
/// <param name="itemtype">passed in from packet</param>
/// <param name="regionhandle">Region we're looking up</param>
public void RequestMapItems(string httpserver, UUID id, uint flags,
uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
{
MapRequestState st = new MapRequestState();
st.agentID = id;
st.flags = flags;
st.EstateID = EstateID;
st.godlike = godlike;
st.itemtype = itemtype;
st.regionhandle = regionhandle;
EnqueueMapItemRequest(st);
}
/// <summary>
/// Does the actual remote mapitem request
/// This should be called from an asynchronous thread
/// Request failures get blacklisted until region restart so we don't
/// continue to spend resources trying to contact regions that are down.
/// </summary>
/// <param name="httpserver">blank string, we discover this in the process</param>
/// <param name="id">Agent ID that we are making this request on behalf</param>
/// <param name="flags">passed in from packet</param>
/// <param name="EstateID">passed in from packet</param>
/// <param name="godlike">passed in from packet</param>
/// <param name="itemtype">passed in from packet</param>
/// <param name="regionhandle">Region we're looking up</param>
/// <returns></returns>
private OSDMap RequestMapItemsAsync(string httpserver, UUID id, uint flags,
uint EstateID, bool godlike, uint itemtype, ulong regionhandle)
{
bool blacklisted = false;
lock (m_blacklistedregions)
{
if (m_blacklistedregions.ContainsKey(regionhandle))
blacklisted = true;
}
if (blacklisted)
return new OSDMap();
UUID requestID = UUID.Random();
lock (m_cachedRegionMapItemsAddress)
{
if (m_cachedRegionMapItemsAddress.ContainsKey(regionhandle))
httpserver = m_cachedRegionMapItemsAddress[regionhandle];
}
if (httpserver.Length == 0)
{
uint x = 0, y = 0;
Utils.LongToUInts(regionhandle, out x, out y);
GridRegion mreg = m_scene.GridService.GetRegionByPosition(m_scene.RegionInfo.ScopeID, (int)x, (int)y);
if (mreg != null)
{
httpserver = "http://" + mreg.ExternalEndPoint.Address.ToString() + ":" + mreg.HttpPort + "/MAP/MapItems/" + regionhandle.ToString();
lock (m_cachedRegionMapItemsAddress)
{
if (!m_cachedRegionMapItemsAddress.ContainsKey(regionhandle))
m_cachedRegionMapItemsAddress.Add(regionhandle, httpserver);
}
}
else
{
lock (m_blacklistedregions)
{
if (!m_blacklistedregions.ContainsKey(regionhandle))
m_blacklistedregions.Add(regionhandle, Environment.TickCount);
}
m_log.InfoFormat("[WORLD MAP]: Blacklisted region {0}", regionhandle.ToString());
}
}
blacklisted = false;
lock (m_blacklistedurls)
{
if (m_blacklistedurls.ContainsKey(httpserver))
blacklisted = true;
}
// Can't find the http server
if (httpserver.Length == 0 || blacklisted)
return new OSDMap();
MapRequestState mrs = new MapRequestState();
mrs.agentID = id;
mrs.EstateID = EstateID;
mrs.flags = flags;
mrs.godlike = godlike;
mrs.itemtype=itemtype;
mrs.regionhandle = regionhandle;
lock (m_openRequests)
m_openRequests.Add(requestID, mrs);
WebRequest mapitemsrequest = WebRequest.Create(httpserver);
mapitemsrequest.Method = "POST";
mapitemsrequest.ContentType = "application/xml+llsd";
OSDMap RAMap = new OSDMap();
// string RAMapString = RAMap.ToString();
OSD LLSDofRAMap = RAMap; // RENAME if this works
byte[] buffer = OSDParser.SerializeLLSDXmlBytes(LLSDofRAMap);
OSDMap responseMap = new OSDMap();
responseMap["requestID"] = OSD.FromUUID(requestID);
Stream os = null;
try
{ // send the Post
mapitemsrequest.ContentLength = buffer.Length; //Count bytes to send
os = mapitemsrequest.GetRequestStream();
os.Write(buffer, 0, buffer.Length); //Send it
os.Close();
//m_log.DebugFormat("[WORLD MAP]: Getting MapItems from Sim {0}", httpserver);
}
catch (WebException ex)
{
m_log.WarnFormat("[WORLD MAP]: Bad send on GetMapItems {0}", ex.Message);
responseMap["connect"] = OSD.FromBoolean(false);
lock (m_blacklistedurls)
{
if (!m_blacklistedurls.ContainsKey(httpserver))
m_blacklistedurls.Add(httpserver, Environment.TickCount);
}
m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver);
return responseMap;
}
string response_mapItems_reply = null;
{ // get the response
try
{
WebResponse webResponse = mapitemsrequest.GetResponse();
if (webResponse != null)
{
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
response_mapItems_reply = sr.ReadToEnd().Trim();
}
else
{
return new OSDMap();
}
}
catch (WebException)
{
responseMap["connect"] = OSD.FromBoolean(false);
lock (m_blacklistedurls)
{
if (!m_blacklistedurls.ContainsKey(httpserver))
m_blacklistedurls.Add(httpserver, Environment.TickCount);
}
m_log.WarnFormat("[WORLD MAP]: Blacklisted {0}", httpserver);
return responseMap;
}
OSD rezResponse = null;
try
{
rezResponse = OSDParser.DeserializeLLSDXml(response_mapItems_reply);
responseMap = (OSDMap)rezResponse;
responseMap["requestID"] = OSD.FromUUID(requestID);
}
catch (Exception)
{
//m_log.InfoFormat("[OGP]: exception on parse of rez reply {0}", ex.Message);
responseMap["connect"] = OSD.FromBoolean(false);
return responseMap;
}
}
return responseMap;
}
/// <summary>
/// Requests map blocks in area of minX, maxX, minY, MaxY in world cordinates
/// </summary>
/// <param name="minX"></param>
/// <param name="minY"></param>
/// <param name="maxX"></param>
/// <param name="maxY"></param>
public virtual void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag)
{
if ((flag & 0x10000) != 0) // user clicked on the map a tile that isn't visible
{
List<MapBlockData> response = new List<MapBlockData>();
// this should return one mapblock at most.
// (diva note: why?? in that case we should GetRegionByPosition)
// But make sure: Look whether the one we requested is in there
List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID,
minX * (int)Constants.RegionSize,
maxX * (int)Constants.RegionSize,
minY * (int)Constants.RegionSize,
maxY * (int)Constants.RegionSize);
if (regions != null)
{
foreach (GridRegion r in regions)
{
if ((r.RegionLocX == minX * (int)Constants.RegionSize) &&
(r.RegionLocY == minY * (int)Constants.RegionSize))
{
// found it => add it to response
MapBlockData block = new MapBlockData();
MapBlockFromGridRegion(block, r);
response.Add(block);
break;
}
}
}
if (response.Count == 0)
{
// response still empty => couldn't find the map-tile the user clicked on => tell the client
MapBlockData block = new MapBlockData();
block.X = (ushort)minX;
block.Y = (ushort)minY;
block.Access = 254; // == not there
response.Add(block);
}
remoteClient.SendMapBlock(response, 0);
}
else
{
// normal mapblock request. Use the provided values
GetAndSendBlocks(remoteClient, minX, minY, maxX, maxY, flag);
}
}
protected virtual void GetAndSendBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY, uint flag)
{
List<MapBlockData> mapBlocks = new List<MapBlockData>();
List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID,
(minX - 4) * (int)Constants.RegionSize,
(maxX + 4) * (int)Constants.RegionSize,
(minY - 4) * (int)Constants.RegionSize,
(maxY + 4) * (int)Constants.RegionSize);
foreach (GridRegion r in regions)
{
MapBlockData block = new MapBlockData();
MapBlockFromGridRegion(block, r);
mapBlocks.Add(block);
}
remoteClient.SendMapBlock(mapBlocks, flag);
}
protected void MapBlockFromGridRegion(MapBlockData block, GridRegion r)
{
block.Access = r.Access;
block.MapImageId = r.TerrainImage;
block.Name = r.RegionName;
block.X = (ushort)(r.RegionLocX / Constants.RegionSize);
block.Y = (ushort)(r.RegionLocY / Constants.RegionSize);
}
public Hashtable OnHTTPGetMapImage(Hashtable keysvals)
{
m_log.Debug("[WORLD MAP]: Sending map image jpeg");
Hashtable reply = new Hashtable();
int statuscode = 200;
byte[] jpeg = new byte[0];
if (myMapImageJPEG.Length == 0)
{
MemoryStream imgstream = new MemoryStream();
Bitmap mapTexture = new Bitmap(1,1);
ManagedImage managedImage;
Image image = (Image)mapTexture;
try
{
// Taking our jpeg2000 data, decoding it, then saving it to a byte array with regular jpeg data
imgstream = new MemoryStream();
// non-async because we know we have the asset immediately.
AssetBase mapasset = m_scene.AssetService.Get(m_scene.RegionInfo.lastMapUUID.ToString());
// Decode image to System.Drawing.Image
if (OpenJPEG.DecodeToImage(mapasset.Data, out managedImage, out image))
{
// Save to bitmap
mapTexture = new Bitmap(image);
EncoderParameters myEncoderParameters = new EncoderParameters();
myEncoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
// Save bitmap to stream
mapTexture.Save(imgstream, GetEncoderInfo("image/jpeg"), myEncoderParameters);
// Write the stream to a byte array for output
jpeg = imgstream.ToArray();
myMapImageJPEG = jpeg;
}
}
catch (Exception)
{
// Dummy!
m_log.Warn("[WORLD MAP]: Unable to generate Map image");
}
finally
{
// Reclaim memory, these are unmanaged resources
// If we encountered an exception, one or more of these will be null
if (mapTexture != null)
mapTexture.Dispose();
if (image != null)
image.Dispose();
if (imgstream != null)
{
imgstream.Close();
imgstream.Dispose();
}
}
}
else
{
// Use cached version so we don't have to loose our mind
jpeg = myMapImageJPEG;
}
reply["str_response_string"] = Convert.ToBase64String(jpeg);
reply["int_response_code"] = statuscode;
reply["content_type"] = "image/jpeg";
return reply;
}
// From msdn
private static ImageCodecInfo GetEncoderInfo(String mimeType)
{
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
/// <summary>
/// Export the world map
/// </summary>
/// <param name="fileName"></param>
public void HandleExportWorldMapConsoleCommand(string module, string[] cmdparams)
{
if (m_scene.ConsoleScene() == null)
{
// FIXME: If console region is root then this will be printed by every module. Currently, there is no
// way to prevent this, short of making the entire module shared (which is complete overkill).
// One possibility is to return a bool to signal whether the module has completely handled the command
m_log.InfoFormat("[WORLD MAP]: Please change to a specific region in order to export its world map");
return;
}
if (m_scene.ConsoleScene() != m_scene)
return;
string exportPath;
if (cmdparams.Length > 1)
exportPath = cmdparams[1];
else
exportPath = DEFAULT_WORLD_MAP_EXPORT_PATH;
m_log.InfoFormat(
"[WORLD MAP]: Exporting world map for {0} to {1}", m_scene.RegionInfo.RegionName, exportPath);
List<MapBlockData> mapBlocks = new List<MapBlockData>();
List<GridRegion> regions = m_scene.GridService.GetRegionRange(m_scene.RegionInfo.ScopeID,
(int)(m_scene.RegionInfo.RegionLocX - 9) * (int)Constants.RegionSize,
(int)(m_scene.RegionInfo.RegionLocX + 9) * (int)Constants.RegionSize,
(int)(m_scene.RegionInfo.RegionLocY - 9) * (int)Constants.RegionSize,
(int)(m_scene.RegionInfo.RegionLocY + 9) * (int)Constants.RegionSize);
List<AssetBase> textures = new List<AssetBase>();
List<Image> bitImages = new List<Image>();
foreach (GridRegion r in regions)
{
MapBlockData mapBlock = new MapBlockData();
MapBlockFromGridRegion(mapBlock, r);
AssetBase texAsset = m_scene.AssetService.Get(mapBlock.MapImageId.ToString());
if (texAsset != null)
{
textures.Add(texAsset);
}
//else
//{
// // WHAT?!? This doesn't seem right. Commenting (diva)
// texAsset = m_scene.AssetService.Get(mapBlock.MapImageId.ToString());
// if (texAsset != null)
// {
// textures.Add(texAsset);
// }
//}
}
foreach (AssetBase asset in textures)
{
ManagedImage managedImage;
Image image;
if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
bitImages.Add(image);
}
Bitmap mapTexture = new Bitmap(2560, 2560);
Graphics g = Graphics.FromImage(mapTexture);
SolidBrush sea = new SolidBrush(Color.DarkBlue);
g.FillRectangle(sea, 0, 0, 2560, 2560);
for (int i = 0; i < mapBlocks.Count; i++)
{
ushort x = (ushort)((mapBlocks[i].X - m_scene.RegionInfo.RegionLocX) + 10);
ushort y = (ushort)((mapBlocks[i].Y - m_scene.RegionInfo.RegionLocY) + 10);
g.DrawImage(bitImages[i], (x * 128), 2560 - (y * 128), 128, 128); // y origin is top
}
mapTexture.Save(exportPath, ImageFormat.Jpeg);
m_log.InfoFormat(
"[WORLD MAP]: Successfully exported world map for {0} to {1}",
m_scene.RegionInfo.RegionName, exportPath);
}
public OSD HandleRemoteMapItemRequest(string path, OSD request, string endpoint)
{
uint xstart = 0;
uint ystart = 0;
Utils.LongToUInts(m_scene.RegionInfo.RegionHandle,out xstart,out ystart);
OSDMap responsemap = new OSDMap();
List<ScenePresence> avatars = m_scene.GetAvatars();
OSDArray responsearr = new OSDArray(avatars.Count);
OSDMap responsemapdata = new OSDMap();
int tc = Environment.TickCount;
/*
foreach (ScenePresence av in avatars)
{
responsemapdata = new OSDMap();
responsemapdata["X"] = OSD.FromInteger((int)(xstart + av.AbsolutePosition.X));
responsemapdata["Y"] = OSD.FromInteger((int)(ystart + av.AbsolutePosition.Y));
responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
responsemapdata["Name"] = OSD.FromString("TH");
responsemapdata["Extra"] = OSD.FromInteger(0);
responsemapdata["Extra2"] = OSD.FromInteger(0);
responsearr.Add(responsemapdata);
}
responsemap["1"] = responsearr;
*/
if (avatars.Count == 0)
{
responsemapdata = new OSDMap();
responsemapdata["X"] = OSD.FromInteger((int)(xstart + 1));
responsemapdata["Y"] = OSD.FromInteger((int)(ystart + 1));
responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()));
responsemapdata["Extra"] = OSD.FromInteger(0);
responsemapdata["Extra2"] = OSD.FromInteger(0);
responsearr.Add(responsemapdata);
responsemap["6"] = responsearr;
}
else
{
responsearr = new OSDArray(avatars.Count);
foreach (ScenePresence av in avatars)
{
responsemapdata = new OSDMap();
responsemapdata["X"] = OSD.FromInteger((int)(xstart + av.AbsolutePosition.X));
responsemapdata["Y"] = OSD.FromInteger((int)(ystart + av.AbsolutePosition.Y));
responsemapdata["ID"] = OSD.FromUUID(UUID.Zero);
responsemapdata["Name"] = OSD.FromString(Util.Md5Hash(m_scene.RegionInfo.RegionName + tc.ToString()));
responsemapdata["Extra"] = OSD.FromInteger(1);
responsemapdata["Extra2"] = OSD.FromInteger(0);
responsearr.Add(responsemapdata);
}
responsemap["6"] = responsearr;
}
return responsemap;
}
public void LazySaveGeneratedMaptile(byte[] data, bool temporary)
{
// Overwrites the local Asset cache with new maptile data
// Assets are single write, this causes the asset server to ignore this update,
// but the local asset cache does not
// this is on purpose! The net result of this is the region always has the most up to date
// map tile while protecting the (grid) asset database from bloat caused by a new asset each
// time a mapimage is generated!
UUID lastMapRegionUUID = m_scene.RegionInfo.lastMapUUID;
int lastMapRefresh = 0;
int twoDays = 172800;
int RefreshSeconds = twoDays;
try
{
lastMapRefresh = Convert.ToInt32(m_scene.RegionInfo.lastMapRefresh);
}
catch (ArgumentException)
{
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
UUID TerrainImageUUID = UUID.Random();
if (lastMapRegionUUID == UUID.Zero || (lastMapRefresh + RefreshSeconds) < Util.UnixTimeSinceEpoch())
{
m_scene.RegionInfo.SaveLastMapUUID(TerrainImageUUID);
m_log.Debug("[MAPTILE]: STORING MAPTILE IMAGE");
}
else
{
TerrainImageUUID = lastMapRegionUUID;
m_log.Debug("[MAPTILE]: REUSING OLD MAPTILE IMAGE ID");
}
m_scene.RegionInfo.RegionSettings.TerrainImageID = TerrainImageUUID;
AssetBase asset = new AssetBase();
asset.FullID = m_scene.RegionInfo.RegionSettings.TerrainImageID;
asset.Data = data;
asset.Name
= "terrainImage_" + m_scene.RegionInfo.RegionID.ToString() + "_" + lastMapRefresh.ToString();
asset.Description = m_scene.RegionInfo.RegionName;
asset.Type = 0;
asset.Temporary = temporary;
m_scene.AssetService.Store(asset);
}
private void MakeRootAgent(ScenePresence avatar)
{
// You may ask, why this is in a threadpool to start with..
// The reason is so we don't cause the thread to freeze waiting
// for the 1 second it costs to start a thread manually.
if (!threadrunning)
Util.FireAndForget(this.StartThread);
lock (m_rootAgents)
{
if (!m_rootAgents.Contains(avatar.UUID))
{
m_rootAgents.Add(avatar.UUID);
}
}
}
private void MakeChildAgent(ScenePresence avatar)
{
List<ScenePresence> presences = m_scene.GetAvatars();
int rootcount = 0;
for (int i = 0; i < presences.Count; i++)
{
if (presences[i] != null)
{
if (!presences[i].IsChildAgent)
rootcount++;
}
}
if (rootcount <= 1)
StopThread();
lock (m_rootAgents)
{
if (m_rootAgents.Contains(avatar.UUID))
{
m_rootAgents.Remove(avatar.UUID);
}
}
}
}
public struct MapRequestState
{
public UUID agentID;
public uint flags;
public uint EstateID;
public bool godlike;
public uint itemtype;
public ulong regionhandle;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.ObjectPool;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNetCore.ResponseCaching
{
internal class ResponseCachingKeyProvider : IResponseCachingKeyProvider
{
// Use the record separator for delimiting components of the cache key to avoid possible collisions
private const char KeyDelimiter = '\x1e';
// Use the unit separator for delimiting subcomponents of the cache key to avoid possible collisions
private const char KeySubDelimiter = '\x1f';
private readonly ObjectPool<StringBuilder> _builderPool;
private readonly ResponseCachingOptions _options;
internal ResponseCachingKeyProvider(ObjectPoolProvider poolProvider, IOptions<ResponseCachingOptions> options)
{
if (poolProvider == null)
{
throw new ArgumentNullException(nameof(poolProvider));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_builderPool = poolProvider.CreateStringBuilderPool();
_options = options.Value;
}
public IEnumerable<string> CreateLookupVaryByKeys(ResponseCachingContext context)
{
return new string[] { CreateStorageVaryByKey(context) };
}
// GET<delimiter>SCHEME<delimiter>HOST:PORT/PATHBASE/PATH
public string CreateBaseKey(ResponseCachingContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var request = context.HttpContext.Request;
var builder = _builderPool.Get();
try
{
builder
.AppendUpperInvariant(request.Method)
.Append(KeyDelimiter)
.AppendUpperInvariant(request.Scheme)
.Append(KeyDelimiter)
.AppendUpperInvariant(request.Host.Value);
if (_options.UseCaseSensitivePaths)
{
builder
.Append(request.PathBase.Value)
.Append(request.Path.Value);
}
else
{
builder
.AppendUpperInvariant(request.PathBase.Value)
.AppendUpperInvariant(request.Path.Value);
}
return builder.ToString();
}
finally
{
_builderPool.Return(builder);
}
}
// BaseKey<delimiter>H<delimiter>HeaderName=HeaderValue<delimiter>Q<delimiter>QueryName=QueryValue1<subdelimiter>QueryValue2
public string CreateStorageVaryByKey(ResponseCachingContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var varyByRules = context.CachedVaryByRules;
if (varyByRules == null)
{
throw new InvalidOperationException($"{nameof(CachedVaryByRules)} must not be null on the {nameof(ResponseCachingContext)}");
}
if (StringValues.IsNullOrEmpty(varyByRules.Headers) && StringValues.IsNullOrEmpty(varyByRules.QueryKeys))
{
return varyByRules.VaryByKeyPrefix;
}
var request = context.HttpContext.Request;
var builder = _builderPool.Get();
try
{
// Prepend with the Guid of the CachedVaryByRules
builder.Append(varyByRules.VaryByKeyPrefix);
// Vary by headers
var headersCount = varyByRules?.Headers.Count ?? 0;
if (headersCount > 0)
{
// Append a group separator for the header segment of the cache key
builder.Append(KeyDelimiter)
.Append('H');
var requestHeaders = context.HttpContext.Request.Headers;
for (var i = 0; i < headersCount; i++)
{
var header = varyByRules!.Headers[i] ?? string.Empty;
var headerValues = requestHeaders[header];
builder.Append(KeyDelimiter)
.Append(header)
.Append('=');
var headerValuesArray = headerValues.ToArray();
Array.Sort(headerValuesArray, StringComparer.Ordinal);
for (var j = 0; j < headerValuesArray.Length; j++)
{
builder.Append(headerValuesArray[j]);
}
}
}
// Vary by query keys
if (varyByRules?.QueryKeys.Count > 0)
{
// Append a group separator for the query key segment of the cache key
builder.Append(KeyDelimiter)
.Append('Q');
if (varyByRules.QueryKeys.Count == 1 && string.Equals(varyByRules.QueryKeys[0], "*", StringComparison.Ordinal))
{
// Vary by all available query keys
var queryArray = context.HttpContext.Request.Query.ToArray();
// Query keys are aggregated case-insensitively whereas the query values are compared ordinally.
Array.Sort(queryArray, QueryKeyComparer.OrdinalIgnoreCase);
for (var i = 0; i < queryArray.Length; i++)
{
builder.Append(KeyDelimiter)
.AppendUpperInvariant(queryArray[i].Key)
.Append('=');
var queryValueArray = queryArray[i].Value.ToArray();
Array.Sort(queryValueArray, StringComparer.Ordinal);
for (var j = 0; j < queryValueArray.Length; j++)
{
if (j > 0)
{
builder.Append(KeySubDelimiter);
}
builder.Append(queryValueArray[j]);
}
}
}
else
{
for (var i = 0; i < varyByRules.QueryKeys.Count; i++)
{
var queryKey = varyByRules.QueryKeys[i] ?? string.Empty;
var queryKeyValues = context.HttpContext.Request.Query[queryKey];
builder.Append(KeyDelimiter)
.Append(queryKey)
.Append('=');
var queryValueArray = queryKeyValues.ToArray();
Array.Sort(queryValueArray, StringComparer.Ordinal);
for (var j = 0; j < queryValueArray.Length; j++)
{
if (j > 0)
{
builder.Append(KeySubDelimiter);
}
builder.Append(queryValueArray[j]);
}
}
}
}
return builder.ToString();
}
finally
{
_builderPool.Return(builder);
}
}
private class QueryKeyComparer : IComparer<KeyValuePair<string, StringValues>>
{
private readonly StringComparer _stringComparer;
public static QueryKeyComparer OrdinalIgnoreCase { get; } = new QueryKeyComparer(StringComparer.OrdinalIgnoreCase);
public QueryKeyComparer(StringComparer stringComparer)
{
_stringComparer = stringComparer;
}
public int Compare(KeyValuePair<string, StringValues> x, KeyValuePair<string, StringValues> y) => _stringComparer.Compare(x.Key, y.Key);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Sql.LegacySdk;
using Microsoft.Azure.Management.Sql.LegacySdk.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Sql.LegacySdk
{
/// <summary>
/// Represents all the operations to manage Azure SQL Database and Database
/// Server Audit policy. Contains operations to: Create, Retrieve and
/// Update audit policy.
/// </summary>
internal partial class AuditingPolicyOperations : IServiceOperations<SqlManagementClient>, IAuditingPolicyOperations
{
/// <summary>
/// Initializes a new instance of the AuditingPolicyOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal AuditingPolicyOperations(SqlManagementClient client)
{
this._client = client;
}
private SqlManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Sql.LegacySdk.SqlManagementClient.
/// </summary>
public SqlManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Creates or updates an Azure SQL Database auditing policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the auditing
/// policy applies.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a Azure
/// SQL Database auditing policy.
/// </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> CreateOrUpdateDatabasePolicyAsync(string resourceGroupName, string serverName, string databaseName, DatabaseAuditingPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
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("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateDatabasePolicyAsync", 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/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/auditingPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
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
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject databaseAuditingPolicyCreateOrUpdateParametersValue = new JObject();
requestDoc = databaseAuditingPolicyCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
databaseAuditingPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.UseServerDefault != null)
{
propertiesValue["useServerDefault"] = parameters.Properties.UseServerDefault;
}
if (parameters.Properties.AuditingState != null)
{
propertiesValue["auditingState"] = parameters.Properties.AuditingState;
}
if (parameters.Properties.EventTypesToAudit != null)
{
propertiesValue["eventTypesToAudit"] = parameters.Properties.EventTypesToAudit;
}
if (parameters.Properties.StorageAccountName != null)
{
propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName;
}
if (parameters.Properties.StorageAccountKey != null)
{
propertiesValue["storageAccountKey"] = parameters.Properties.StorageAccountKey;
}
if (parameters.Properties.StorageAccountSecondaryKey != null)
{
propertiesValue["storageAccountSecondaryKey"] = parameters.Properties.StorageAccountSecondaryKey;
}
if (parameters.Properties.StorageTableEndpoint != null)
{
propertiesValue["storageTableEndpoint"] = parameters.Properties.StorageTableEndpoint;
}
if (parameters.Properties.StorageAccountResourceGroupName != null)
{
propertiesValue["storageAccountResourceGroupName"] = parameters.Properties.StorageAccountResourceGroupName;
}
if (parameters.Properties.StorageAccountSubscriptionId != null)
{
propertiesValue["storageAccountSubscriptionId"] = parameters.Properties.StorageAccountSubscriptionId;
}
if (parameters.Properties.RetentionDays != null)
{
propertiesValue["retentionDays"] = parameters.Properties.RetentionDays;
}
if (parameters.Properties.AuditLogsTableName != null)
{
propertiesValue["auditLogsTableName"] = parameters.Properties.AuditLogsTableName;
}
if (parameters.Properties.FullAuditLogsTableName != null)
{
propertiesValue["fullAuditLogsTableName"] = parameters.Properties.FullAuditLogsTableName;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// 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
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>
/// Creates or updates an Azure SQL Database Server auditing policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='parameters'>
/// Required. The required parameters for createing or updating a Azure
/// SQL Database Server auditing policy.
/// </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> CreateOrUpdateServerPolicyAsync(string resourceGroupName, string serverName, ServerAuditingPolicyCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
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("serverName", serverName);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateServerPolicyAsync", 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/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/auditingPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
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
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject serverAuditingPolicyCreateOrUpdateParametersValue = new JObject();
requestDoc = serverAuditingPolicyCreateOrUpdateParametersValue;
JObject propertiesValue = new JObject();
serverAuditingPolicyCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.AuditingState != null)
{
propertiesValue["auditingState"] = parameters.Properties.AuditingState;
}
if (parameters.Properties.EventTypesToAudit != null)
{
propertiesValue["eventTypesToAudit"] = parameters.Properties.EventTypesToAudit;
}
if (parameters.Properties.StorageAccountName != null)
{
propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName;
}
if (parameters.Properties.StorageAccountKey != null)
{
propertiesValue["storageAccountKey"] = parameters.Properties.StorageAccountKey;
}
if (parameters.Properties.StorageAccountSecondaryKey != null)
{
propertiesValue["storageAccountSecondaryKey"] = parameters.Properties.StorageAccountSecondaryKey;
}
if (parameters.Properties.StorageTableEndpoint != null)
{
propertiesValue["storageTableEndpoint"] = parameters.Properties.StorageTableEndpoint;
}
if (parameters.Properties.StorageAccountResourceGroupName != null)
{
propertiesValue["storageAccountResourceGroupName"] = parameters.Properties.StorageAccountResourceGroupName;
}
if (parameters.Properties.StorageAccountSubscriptionId != null)
{
propertiesValue["storageAccountSubscriptionId"] = parameters.Properties.StorageAccountSubscriptionId;
}
if (parameters.Properties.RetentionDays != null)
{
propertiesValue["retentionDays"] = parameters.Properties.RetentionDays;
}
if (parameters.Properties.AuditLogsTableName != null)
{
propertiesValue["auditLogsTableName"] = parameters.Properties.AuditLogsTableName;
}
if (parameters.Properties.FullAuditLogsTableName != null)
{
propertiesValue["fullAuditLogsTableName"] = parameters.Properties.FullAuditLogsTableName;
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// 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
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>
/// Returns an Azure SQL Database auditing policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='databaseName'>
/// Required. The name of the Azure SQL Database for which the auditing
/// policy applies.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a get database auditing policy request.
/// </returns>
public async Task<DatabaseAuditingPolicyGetResponse> GetDatabasePolicyAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
if (databaseName == null)
{
throw new ArgumentNullException("databaseName");
}
// 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("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
TracingAdapter.Enter(invocationId, this, "GetDatabasePolicyAsync", 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/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/databases/";
url = url + Uri.EscapeDataString(databaseName);
url = url + "/auditingPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
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
// 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
DatabaseAuditingPolicyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DatabaseAuditingPolicyGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DatabaseAuditingPolicy auditingPolicyInstance = new DatabaseAuditingPolicy();
result.AuditingPolicy = auditingPolicyInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
DatabaseAuditingPolicyProperties propertiesInstance = new DatabaseAuditingPolicyProperties();
auditingPolicyInstance.Properties = propertiesInstance;
JToken useServerDefaultValue = propertiesValue["useServerDefault"];
if (useServerDefaultValue != null && useServerDefaultValue.Type != JTokenType.Null)
{
string useServerDefaultInstance = ((string)useServerDefaultValue);
propertiesInstance.UseServerDefault = useServerDefaultInstance;
}
JToken auditingStateValue = propertiesValue["auditingState"];
if (auditingStateValue != null && auditingStateValue.Type != JTokenType.Null)
{
string auditingStateInstance = ((string)auditingStateValue);
propertiesInstance.AuditingState = auditingStateInstance;
}
JToken eventTypesToAuditValue = propertiesValue["eventTypesToAudit"];
if (eventTypesToAuditValue != null && eventTypesToAuditValue.Type != JTokenType.Null)
{
string eventTypesToAuditInstance = ((string)eventTypesToAuditValue);
propertiesInstance.EventTypesToAudit = eventTypesToAuditInstance;
}
JToken storageAccountNameValue = propertiesValue["storageAccountName"];
if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null)
{
string storageAccountNameInstance = ((string)storageAccountNameValue);
propertiesInstance.StorageAccountName = storageAccountNameInstance;
}
JToken storageAccountKeyValue = propertiesValue["storageAccountKey"];
if (storageAccountKeyValue != null && storageAccountKeyValue.Type != JTokenType.Null)
{
string storageAccountKeyInstance = ((string)storageAccountKeyValue);
propertiesInstance.StorageAccountKey = storageAccountKeyInstance;
}
JToken storageAccountSecondaryKeyValue = propertiesValue["storageAccountSecondaryKey"];
if (storageAccountSecondaryKeyValue != null && storageAccountSecondaryKeyValue.Type != JTokenType.Null)
{
string storageAccountSecondaryKeyInstance = ((string)storageAccountSecondaryKeyValue);
propertiesInstance.StorageAccountSecondaryKey = storageAccountSecondaryKeyInstance;
}
JToken storageTableEndpointValue = propertiesValue["storageTableEndpoint"];
if (storageTableEndpointValue != null && storageTableEndpointValue.Type != JTokenType.Null)
{
string storageTableEndpointInstance = ((string)storageTableEndpointValue);
propertiesInstance.StorageTableEndpoint = storageTableEndpointInstance;
}
JToken storageAccountResourceGroupNameValue = propertiesValue["storageAccountResourceGroupName"];
if (storageAccountResourceGroupNameValue != null && storageAccountResourceGroupNameValue.Type != JTokenType.Null)
{
string storageAccountResourceGroupNameInstance = ((string)storageAccountResourceGroupNameValue);
propertiesInstance.StorageAccountResourceGroupName = storageAccountResourceGroupNameInstance;
}
JToken storageAccountSubscriptionIdValue = propertiesValue["storageAccountSubscriptionId"];
if (storageAccountSubscriptionIdValue != null && storageAccountSubscriptionIdValue.Type != JTokenType.Null)
{
string storageAccountSubscriptionIdInstance = ((string)storageAccountSubscriptionIdValue);
propertiesInstance.StorageAccountSubscriptionId = storageAccountSubscriptionIdInstance;
}
JToken retentionDaysValue = propertiesValue["retentionDays"];
if (retentionDaysValue != null && retentionDaysValue.Type != JTokenType.Null)
{
string retentionDaysInstance = ((string)retentionDaysValue);
propertiesInstance.RetentionDays = retentionDaysInstance;
}
JToken auditLogsTableNameValue = propertiesValue["auditLogsTableName"];
if (auditLogsTableNameValue != null && auditLogsTableNameValue.Type != JTokenType.Null)
{
string auditLogsTableNameInstance = ((string)auditLogsTableNameValue);
propertiesInstance.AuditLogsTableName = auditLogsTableNameInstance;
}
JToken fullAuditLogsTableNameValue = propertiesValue["fullAuditLogsTableName"];
if (fullAuditLogsTableNameValue != null && fullAuditLogsTableNameValue.Type != JTokenType.Null)
{
string fullAuditLogsTableNameInstance = ((string)fullAuditLogsTableNameValue);
propertiesInstance.FullAuditLogsTableName = fullAuditLogsTableNameInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
auditingPolicyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
auditingPolicyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
auditingPolicyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
auditingPolicyInstance.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);
auditingPolicyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
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>
/// Returns an Azure SQL Database server auditing policy.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the Resource Group to which the server
/// belongs.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server on which the
/// database is hosted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Represents the response to a get database auditing policy request.
/// </returns>
public async Task<ServerAuditingPolicyGetResponse> GetServerPolicyAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serverName == null)
{
throw new ArgumentNullException("serverName");
}
// 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("serverName", serverName);
TracingAdapter.Enter(invocationId, this, "GetServerPolicyAsync", 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/";
url = url + "Microsoft.Sql";
url = url + "/servers/";
url = url + Uri.EscapeDataString(serverName);
url = url + "/auditingPolicies/Default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01");
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
// 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
ServerAuditingPolicyGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ServerAuditingPolicyGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
ServerAuditingPolicy auditingPolicyInstance = new ServerAuditingPolicy();
result.AuditingPolicy = auditingPolicyInstance;
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ServerAuditingPolicyProperties propertiesInstance = new ServerAuditingPolicyProperties();
auditingPolicyInstance.Properties = propertiesInstance;
JToken auditingStateValue = propertiesValue["auditingState"];
if (auditingStateValue != null && auditingStateValue.Type != JTokenType.Null)
{
string auditingStateInstance = ((string)auditingStateValue);
propertiesInstance.AuditingState = auditingStateInstance;
}
JToken eventTypesToAuditValue = propertiesValue["eventTypesToAudit"];
if (eventTypesToAuditValue != null && eventTypesToAuditValue.Type != JTokenType.Null)
{
string eventTypesToAuditInstance = ((string)eventTypesToAuditValue);
propertiesInstance.EventTypesToAudit = eventTypesToAuditInstance;
}
JToken storageAccountNameValue = propertiesValue["storageAccountName"];
if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null)
{
string storageAccountNameInstance = ((string)storageAccountNameValue);
propertiesInstance.StorageAccountName = storageAccountNameInstance;
}
JToken storageAccountKeyValue = propertiesValue["storageAccountKey"];
if (storageAccountKeyValue != null && storageAccountKeyValue.Type != JTokenType.Null)
{
string storageAccountKeyInstance = ((string)storageAccountKeyValue);
propertiesInstance.StorageAccountKey = storageAccountKeyInstance;
}
JToken storageAccountSecondaryKeyValue = propertiesValue["storageAccountSecondaryKey"];
if (storageAccountSecondaryKeyValue != null && storageAccountSecondaryKeyValue.Type != JTokenType.Null)
{
string storageAccountSecondaryKeyInstance = ((string)storageAccountSecondaryKeyValue);
propertiesInstance.StorageAccountSecondaryKey = storageAccountSecondaryKeyInstance;
}
JToken storageTableEndpointValue = propertiesValue["storageTableEndpoint"];
if (storageTableEndpointValue != null && storageTableEndpointValue.Type != JTokenType.Null)
{
string storageTableEndpointInstance = ((string)storageTableEndpointValue);
propertiesInstance.StorageTableEndpoint = storageTableEndpointInstance;
}
JToken storageAccountResourceGroupNameValue = propertiesValue["storageAccountResourceGroupName"];
if (storageAccountResourceGroupNameValue != null && storageAccountResourceGroupNameValue.Type != JTokenType.Null)
{
string storageAccountResourceGroupNameInstance = ((string)storageAccountResourceGroupNameValue);
propertiesInstance.StorageAccountResourceGroupName = storageAccountResourceGroupNameInstance;
}
JToken storageAccountSubscriptionIdValue = propertiesValue["storageAccountSubscriptionId"];
if (storageAccountSubscriptionIdValue != null && storageAccountSubscriptionIdValue.Type != JTokenType.Null)
{
string storageAccountSubscriptionIdInstance = ((string)storageAccountSubscriptionIdValue);
propertiesInstance.StorageAccountSubscriptionId = storageAccountSubscriptionIdInstance;
}
JToken retentionDaysValue = propertiesValue["retentionDays"];
if (retentionDaysValue != null && retentionDaysValue.Type != JTokenType.Null)
{
string retentionDaysInstance = ((string)retentionDaysValue);
propertiesInstance.RetentionDays = retentionDaysInstance;
}
JToken auditLogsTableNameValue = propertiesValue["auditLogsTableName"];
if (auditLogsTableNameValue != null && auditLogsTableNameValue.Type != JTokenType.Null)
{
string auditLogsTableNameInstance = ((string)auditLogsTableNameValue);
propertiesInstance.AuditLogsTableName = auditLogsTableNameInstance;
}
JToken fullAuditLogsTableNameValue = propertiesValue["fullAuditLogsTableName"];
if (fullAuditLogsTableNameValue != null && fullAuditLogsTableNameValue.Type != JTokenType.Null)
{
string fullAuditLogsTableNameInstance = ((string)fullAuditLogsTableNameValue);
propertiesInstance.FullAuditLogsTableName = fullAuditLogsTableNameInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
auditingPolicyInstance.Id = idInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
auditingPolicyInstance.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
auditingPolicyInstance.Type = typeInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
auditingPolicyInstance.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);
auditingPolicyInstance.Tags.Add(tagsKey, tagsValue);
}
}
}
}
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();
}
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
#if DEBUG
#define TRACK_BASICBLOCK_IDENTITY
#else
//#define TRACK_BASICBLOCK_IDENTITY
#endif
namespace Microsoft.Zelig.CodeGeneration.IR
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
public abstract class BasicBlock
{
public static readonly BasicBlock[] SharedEmptyArray = new BasicBlock[0];
public enum Qualifier
{
Entry ,
PrologueStart ,
PrologueEnd ,
EntryInjectionStart,
EntryInjectionEnd ,
Normal ,
Exception ,
ExitInjectionStart ,
ExitInjectionEnd ,
EpilogueStart ,
EpilogueEnd ,
Exit ,
}
//
// State
//
#if TRACK_BASICBLOCK_IDENTITY
protected static int s_identity;
#endif
public int m_identity;
//--//
protected ControlFlowGraphState m_owner;
protected int m_index;
protected Operator[] m_operators;
protected ExceptionHandlerBasicBlock[] m_protectedBy;
protected Qualifier m_qualifier;
//
// Created through ResetFlowInformation/UpdateFlowInformation
//
protected BasicBlockEdge[] m_predecessors;
protected BasicBlockEdge[] m_successors;
//
// Constructor Methods
//
protected BasicBlock() // Default constructor required by TypeSystemSerializer.
{
#if TRACK_BASICBLOCK_IDENTITY
m_identity = s_identity++;
#endif
m_index = -1;
}
protected BasicBlock( ControlFlowGraphState owner ) : this()
{
m_owner = owner;
m_operators = Operator .SharedEmptyArray;
m_protectedBy = ExceptionHandlerBasicBlock.SharedEmptyArray;
m_qualifier = Qualifier.Normal;
m_predecessors = BasicBlockEdge .SharedEmptyArray;
m_successors = BasicBlockEdge .SharedEmptyArray;
owner.Register( this );
}
//--//
//
// Helper Methods
//
public abstract BasicBlock Clone( CloningContext context );
public BasicBlock RegisterAndCloneState( CloningContext context ,
BasicBlock clone )
{
context.Register( this, clone );
CloneState( context, clone );
return clone;
}
public virtual void CloneState( CloningContext context ,
BasicBlock clone )
{
clone.m_qualifier = m_qualifier;
clone.m_operators = context.Clone( m_operators );
clone.m_protectedBy = context.Clone( m_protectedBy );
}
//--//
internal void BumpVersion()
{
m_owner.BumpVersion();
}
internal void ResetFlowInformation()
{
m_predecessors = BasicBlockEdge.SharedEmptyArray;
m_successors = BasicBlockEdge.SharedEmptyArray;
}
internal void UpdateFlowInformation()
{
//
// NOTICE!
//
// It's important that we link first the normal edges and then the exception ones.
// This way, when we build the spanning tree, it's guaranteed that the tree edges go
// through the normal execution path and not through the exceptional one.
//
ControlOperator ctrl = this.FlowControl;
if(ctrl != null)
{
ctrl.UpdateSuccessorInformationInner();
}
foreach(BasicBlock protectedBy in m_protectedBy)
{
this.LinkToExceptionBasicBlock( protectedBy );
}
}
//--//--//
public void LinkToNormalBasicBlock( BasicBlock successor )
{
CHECKS.ASSERT( successor is ExceptionHandlerBasicBlock == false, "Cannot link from flow control to an exception basic block: {0} => {1}", this, successor );
LinkToInner( successor );
}
public void LinkToExceptionBasicBlock( BasicBlock successor )
{
CHECKS.ASSERT( successor is ExceptionHandlerBasicBlock == true, "Cannot use a normal basic block for exception handling: {0} => {1}", this, successor );
LinkToInner( successor );
}
private void LinkToInner( BasicBlock successor )
{
foreach(BasicBlockEdge edge in this.m_successors)
{
CHECKS.ASSERT( edge.Predecessor == this, "Found inconsistency in basic block linkage" );
if(edge.Successor == successor)
{
CHECKS.ASSERT( ArrayUtility.FindReferenceInNotNullArray( successor.m_predecessors, edge ) >= 0, "Found inconsistency in basic block linkage" );
return;
}
}
BasicBlockEdge newEdge = new BasicBlockEdge( this, successor );
successor.m_predecessors = ArrayUtility.AppendToNotNullArray( successor.m_predecessors, newEdge );
this .m_successors = ArrayUtility.AppendToNotNullArray( this .m_successors , newEdge );
}
public void Delete()
{
m_owner.Deregister( this );
m_owner = null;
}
public BasicBlock InsertNewSuccessor( BasicBlock oldBB )
{
return InsertNewSuccessor( oldBB, new NormalBasicBlock( m_owner ) );
}
public BasicBlock InsertNewSuccessor( BasicBlock oldBB ,
BasicBlock newBB )
{
this.FlowControl.SubstituteTarget( oldBB, newBB );
newBB.AddOperator( UnconditionalControlOperator.New( null, oldBB ) );
newBB.NotifyNewPredecessor( this );
return newBB;
}
public BasicBlock InsertNewPredecessor()
{
return InsertNewPredecessor( new NormalBasicBlock( m_owner ) );
}
public BasicBlock InsertNewPredecessor( BasicBlock newBB )
{
BasicBlockEdge[] edges = this.Predecessors;
newBB.AddOperator( UnconditionalControlOperator.New( null, this ) );
foreach(BasicBlockEdge edge in edges)
{
edge.Predecessor.FlowControl.SubstituteTarget( this, newBB );
}
newBB.NotifyNewPredecessor( this );
return newBB;
}
//--//
private void NotifyMerge( BasicBlock entryBB )
{
foreach(BasicBlockEdge edge in this.Successors)
{
BasicBlock succ = edge.Successor;
foreach(Operator op in succ.Operators)
{
op.NotifyMerge( entryBB, this );
}
}
}
private void NotifyNewPredecessor( BasicBlock oldBB )
{
foreach(BasicBlockEdge edge in this.Successors)
{
BasicBlock succ = edge.Successor;
foreach(Operator op in succ.Operators)
{
op.NotifyNewPredecessor( oldBB, this );
}
}
}
//--//
public BasicBlockEdge FindForwardEdge( BasicBlock successor )
{
foreach(BasicBlockEdge edge in m_successors)
{
if(edge.Successor == successor)
{
return edge;
}
}
return null;
}
public BasicBlockEdge FindBackwardEdge( BasicBlock predecessor )
{
foreach(BasicBlockEdge edge in m_predecessors)
{
if(edge.Predecessor == predecessor)
{
return edge;
}
}
return null;
}
public bool IsProtectedBy( BasicBlock handler )
{
foreach(BasicBlock bb in m_protectedBy)
{
if(bb == handler)
{
return true;
}
}
return false;
}
public bool ShouldIncludeInScheduling( BasicBlock bbNext )
{
var ctrl = this.FlowControl;
return ctrl != null ? ctrl.ShouldIncludeInScheduling( bbNext ) : false;
}
//--//
public void SetProtectedBy( ExceptionHandlerBasicBlock bb )
{
BumpVersion();
m_protectedBy = ArrayUtility.AddUniqueToNotNullArray( m_protectedBy, bb );
}
public bool SubstituteProtectedBy( ExceptionHandlerBasicBlock oldBB ,
ExceptionHandlerBasicBlock newBB )
{
int pos = ArrayUtility.FindInNotNullArray( m_protectedBy, oldBB );
if(pos >= 0)
{
m_protectedBy = ArrayUtility.ReplaceAtPositionOfNotNullArray( m_protectedBy, pos, newBB );
BumpVersion();
return true;
}
return false;
}
//--//
public bool IsDominatedBy( BasicBlock bbTarget ,
BitVector[] dominance )
{
return dominance[this.SpanningTreeIndex][bbTarget.SpanningTreeIndex];
}
public Operator GetOperator( Type target )
{
foreach(Operator op in m_operators)
{
if(target.IsInstanceOfType( op ))
{
return op;
}
}
return null;
}
public Operator GetFirstDifferentOperator( Type target )
{
foreach(Operator op in m_operators)
{
if(target.IsInstanceOfType( op ) == false)
{
return op;
}
}
return null;
}
public void AddOperator( Operator oper )
{
CHECKS.ASSERT( !(oper is ControlOperator) || this.FlowControl == null, "Cannot add two control operators to a basic block" );
CHECKS.ASSERT( oper.BasicBlock == null , "Adding operator already part of another code sequence" );
CHECKS.ASSERT( oper.GetBasicBlockIndex() < 0 , "Adding operator already present in code sequence" );
BumpVersion();
oper.BasicBlock = this;
int pos = m_operators.Length;
if(oper is ControlOperator)
{
//
// Make sure the ControlOperator is always the last one in the basic block.
//
}
else if(pos > 0)
{
Operator ctrl = m_operators[pos-1];
if(ctrl is ControlOperator)
{
//
// Insert before the control operator.
//
pos -= 1;
}
}
m_operators = ArrayUtility.InsertAtPositionOfNotNullArray( m_operators, pos, oper );
}
internal void AddAsFirstOperator( Operator oper )
{
AddOperatorBefore( oper, m_operators[0] );
}
internal void AddOperatorBefore( Operator oper ,
Operator operTarget )
{
CHECKS.ASSERT( oper != null , "Missing source operator" );
CHECKS.ASSERT( operTarget != null , "Missing target operator" );
CHECKS.ASSERT( oper is ControlOperator == false , "Control operator can only be added at the end of a basic block" );
CHECKS.ASSERT( oper .BasicBlock == null , "Adding operator already part of another code sequence" );
CHECKS.ASSERT( operTarget.BasicBlock == this , "Target operator does not belong to this basic block" );
CHECKS.ASSERT( operTarget.GetBasicBlockIndex() >= 0, "Target operator does not belong to this basic block" );
CHECKS.ASSERT( oper .GetBasicBlockIndex() < 0, "Adding operator already present in code sequence" );
BumpVersion();
oper.BasicBlock = this;
int pos = operTarget.GetBasicBlockIndex();
m_operators = ArrayUtility.InsertAtPositionOfNotNullArray( m_operators, pos, oper );
}
internal void AddOperatorAfter( Operator operTarget ,
Operator oper )
{
CHECKS.ASSERT( operTarget != null , "Missing target operator" );
CHECKS.ASSERT( operTarget is ControlOperator == false, "Target operator cannot be a control operator" );
AddOperatorBefore( oper, operTarget.GetNextOperator() );
}
internal void RemoveOperator( Operator oper )
{
CHECKS.ASSERT( oper.BasicBlock == this , "Removing operator part of another code sequence" );
CHECKS.ASSERT( oper.GetBasicBlockIndex() >= 0, "Removing operator not part of current basic block" );
BumpVersion();
int pos = oper.GetBasicBlockIndex();
m_operators = ArrayUtility.RemoveAtPositionFromNotNullArray( m_operators, pos );
oper.BasicBlock = null;
}
internal void SubstituteOperator( Operator opOld ,
Operator opNew ,
Operator.SubstitutionFlags flags )
{
CHECKS.ASSERT( opOld.BasicBlock == this , "Target operator does not belong to this basic block" );
CHECKS.ASSERT( opNew.BasicBlock == null , "Substituting operator already part of another code sequence" );
CHECKS.ASSERT( (opOld is ControlOperator) == (opNew is ControlOperator), "Change substitute between incompatible operators ({0} <=> {1})", opOld, opNew );
BumpVersion();
if((flags & Operator.SubstitutionFlags.CopyAnnotations) != 0)
{
opNew.CopyAnnotations( opOld );
}
int pos = opOld.GetBasicBlockIndex();
m_operators = ArrayUtility.ReplaceAtPositionOfNotNullArray( m_operators, pos, opNew );
opOld.BasicBlock = null;
opNew.BasicBlock = this;
}
public void Merge( BasicBlock bbNext )
{
CHECKS.ASSERT( this.Owner == bbNext.Owner, "Cannot merge basic blocks from different flow graphs!" );
ControlOperator ctrl = this.FlowControl;
CHECKS.ASSERT( ctrl is UnconditionalControlOperator &&
((UnconditionalControlOperator)ctrl).TargetBranch == bbNext &&
bbNext.Predecessors.Length == 1 , "Cannot merge two non-consecutive basic blocks" );
bbNext.NotifyMerge( this );
ctrl.Delete();
m_operators = ArrayUtility.AppendNotNullArrayToNotNullArray( m_operators, bbNext.Operators );
foreach(Operator op in bbNext.Operators)
{
op.BasicBlock = this;
}
this.NotifyNewPredecessor( bbNext );
}
public NormalBasicBlock SplitAtOperator( Operator oper ,
bool fRemoveOperator ,
bool fAddFlowControl )
{
CHECKS.ASSERT( this is NormalBasicBlock , "Cannot split non-normal basic block" );
CHECKS.ASSERT( !(oper is ControlOperator), "Cannot split on control operator" );
CHECKS.ASSERT( oper.BasicBlock == this , "Target operator does not belong to this basic block" );
BumpVersion();
//
// Create new basic block, copying the exception handler sets.
//
NormalBasicBlock bb = NormalBasicBlock.CreateWithSameProtection( this );
switch(this.Annotation)
{
case Qualifier.EntryInjectionEnd:
this.Annotation = BasicBlock.Qualifier.Normal;
bb .Annotation = BasicBlock.Qualifier.EntryInjectionEnd;
break;
case Qualifier.ExitInjectionEnd:
this.Annotation = BasicBlock.Qualifier.Normal;
bb .Annotation = BasicBlock.Qualifier.ExitInjectionEnd;
break;
}
//
// Redistribute operators, redirect post ones to the new basic block, add branch from pre ones.
//
int pos = oper.GetBasicBlockIndex();
int pos2;
if(fRemoveOperator)
{
Operator next = oper.GetNextOperator();
if(next != null)
{
pos2 = next.GetBasicBlockIndex();
}
else
{
pos2 = m_operators.Length;
}
}
else
{
pos2 = pos;
}
Operator[] preOps = ArrayUtility.ExtractSliceFromNotNullArray( m_operators, 0 , pos );
Operator[] postOps = ArrayUtility.ExtractSliceFromNotNullArray( m_operators, pos2, m_operators.Length - pos2 );
this.m_operators = preOps;
bb .m_operators = postOps;
foreach(Operator op in postOps)
{
op.Retarget( bb );
}
if(fAddFlowControl)
{
AddOperator( UnconditionalControlOperator.New( null, bb ) );
}
if(fRemoveOperator)
{
oper.ClearState();
}
bb.NotifyNewPredecessor( this );
return bb;
}
//--//
//
// Example:
//
// bb.PerformActionOnValues( delegate( Expression ex )
// {
// TemporaryVariableExpression var = ex as TemporaryVariableExpression;
//
// if(var != null)
// {
// SetTemporary( var );
// }
// } );
//
public void PerformActionOnValues( Action< Expression > action )
{
foreach(var op in m_operators)
{
foreach(var ex in op.Results)
{
if(ex != null)
{
action( ex );
}
}
foreach(var ex in op.Arguments)
{
if(ex != null)
{
action( ex );
}
}
}
}
//--//
public virtual void ApplyTransformation( TransformationContextForIR context )
{
context.Push( this );
context.Transform( ref m_owner );
context.Transform( ref m_index );
context.Transform( ref m_operators );
context.Transform( ref m_protectedBy );
context.Transform( ref m_qualifier );
context.Pop();
}
//--//
//
// Access Methods
//
public ControlFlowGraphState Owner
{
get
{
return m_owner;
}
}
public int SpanningTreeIndex
{
get
{
return m_index;
}
set
{
m_index = value;
}
}
public Operator[] Operators
{
get
{
return m_operators;
}
}
[System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )]
public BasicBlockEdge[] Predecessors
{
get
{
m_owner.UpdateFlowInformation();
return m_predecessors;
}
}
[System.Diagnostics.DebuggerBrowsable( System.Diagnostics.DebuggerBrowsableState.Never )]
public BasicBlockEdge[] Successors
{
get
{
m_owner.UpdateFlowInformation();
return m_successors;
}
}
public ExceptionHandlerBasicBlock[] ProtectedBy
{
get
{
return m_protectedBy;
}
}
public Qualifier Annotation
{
get
{
return m_qualifier;
}
set
{
m_qualifier = value;
}
}
public ControlOperator FlowControl
{
get
{
int len = m_operators.Length;
if(len > 0)
{
Operator op = m_operators[len-1];
if(op is ControlOperator)
{
return (ControlOperator)op;
}
}
return null;
}
set
{
BumpVersion();
value.BasicBlock = this;
int len = m_operators.Length;
if(len > 0)
{
Operator op = m_operators[len-1];
if(op is ControlOperator)
{
//
// Update existing control operator.
//
m_operators[len-1] = value;
return;
}
}
m_operators = ArrayUtility.AppendToNotNullArray( m_operators, (Operator)value );
}
}
public BasicBlock FirstPredecessor
{
get
{
return this.Predecessors[0].Predecessor;
}
}
public BasicBlock FirstSuccessor
{
get
{
return this.Successors[0].Successor;
}
}
public Operator FirstOperator
{
get
{
return m_operators[0];
}
}
public Operator LastOperator
{
get
{
return m_operators[m_operators.Length - 1];
}
}
//--//
//
// Debug Methods
//
public override string ToString()
{
string fmt = (m_owner == null) ? "{0}" : "{0} of {1}";
return string.Format( fmt, this.ToShortString(), m_owner );
}
public abstract string ToShortString();
//--//
protected string ToShortStringInner( string prefix )
{
return string.Format( "{0}({1})", prefix, m_index );
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
internal sealed class ApplyClassExtensions : Transformations.ScanTypeSystem
{
//
// State
//
private Transformations.ReverseIndexTypeSystem m_reverseIndex;
private List< Transformations.PerformClassExtension.Duplicate > m_duplicates;
private bool m_fChanged;
//
// Constructor Methods
//
internal ApplyClassExtensions( TypeSystemForCodeTransformation typeSystem ) : base( typeSystem, typeof(ApplyClassExtensions) )
{
m_fChanged = false;
}
//
// Helper Methods
//
internal static bool Hack_MirrorGenericInstantiations( TypeSystemForCodeTransformation typeSystem )
{
bool fChanged = false;
typeSystem.BuildGenericInstantiationTables();
foreach(TypeRepresentation td in typeSystem.Types.ToArray())
{
CustomAttributeRepresentation ca = td.FindCustomAttribute( typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_ExtendClassAttribute );
if(ca != null)
{
object objTarget = ca.FixedArgsValues[0];
TypeRepresentation tdTarget = objTarget as TypeRepresentation;
if(tdTarget == null)
{
tdTarget = typeSystem.GetWellKnownTypeNoThrow( objTarget as string );
}
if(tdTarget == null)
{
throw TypeConsistencyErrorException.Create( "Missing target class to extend: {0}", objTarget );
}
if(td.IsOpenType == false && tdTarget.IsOpenType)
{
tdTarget = typeSystem.CreateInstantiationOfGenericTemplate( tdTarget, td.GenericParameters );
}
if(tdTarget.IsOpenType)
{
List< TypeRepresentation > lstTdTarget;
if(typeSystem.GenericTypeInstantiations.TryGetValue( tdTarget, out lstTdTarget ))
{
List< TypeRepresentation > lstTd;
typeSystem.GenericTypeInstantiations.TryGetValue( td, out lstTd );
foreach(var td2 in lstTdTarget)
{
var tdNew = typeSystem.CreateInstantiationOfGenericTemplate( td, td2.GenericParameters );
if(td != tdNew && (lstTd == null || lstTd.Contains( tdNew ) == false))
{
fChanged = true;
}
}
}
}
else
{
fChanged |= Hack_ProcessType( typeSystem, td, tdTarget );
}
}
}
return fChanged;
}
private static bool Hack_ProcessType( TypeSystemForCodeTransformation typeSystem ,
TypeRepresentation td ,
TypeRepresentation tdTarget )
{
bool fChanged = false;
var ht = IR.Transformations.PerformClassExtension.Hack_GetSubstitutionTable( typeSystem, td, tdTarget );
foreach(var mdOverriding in ht.Keys)
{
if(mdOverriding.IsOpenMethod)
{
var mdOverridden = ht[mdOverriding];
List< MethodRepresentation > lstMdOverridden;
if(typeSystem.GenericMethodInstantiations.TryGetValue( mdOverridden, out lstMdOverridden ))
{
List< MethodRepresentation > lstMdOverriding;
typeSystem.GenericMethodInstantiations.TryGetValue( mdOverriding, out lstMdOverriding );
foreach(var md in lstMdOverridden)
{
if(md.IsOpenMethod == false)
{
var mdNew = typeSystem.CreateInstantiationOfGenericTemplate( mdOverriding, md.GenericParameters );
if(lstMdOverriding == null || lstMdOverriding.Contains( mdNew ) == false)
{
fChanged = true;
}
}
}
}
}
}
return fChanged;
}
//--//
internal void Run()
{
m_reverseIndex = new Transformations.ReverseIndexTypeSystem( m_typeSystem );
m_duplicates = new List< Transformations.PerformClassExtension.Duplicate >();
//
// We need to deal with Generic Types and Methods.
//
// For generic types, we need to ensure we have as many specialization of the overridding type as those of the overridden one.
//
// For generic methods, we need to ensure that the overriding generic method is instantiated as many times as the overridden one.
//
//
// To speed up the processing of mapping from the overridding entities to the overridden ones,
// we build a reverse index of the whole type system.
//
using(new Transformations.ExecutionTiming( "ReverseIndexTypeSystem" ))
{
m_reverseIndex.ProcessTypeSystem();
}
foreach(TypeRepresentation td in m_typeSystem.Types.ToArray())
{
ProcessType( td );
}
if(m_fChanged)
{
if(m_duplicates.Count > 0)
{
Transformations.PerformClassExtension pfe = new Transformations.PerformClassExtension( m_typeSystem, m_reverseIndex, m_duplicates );
pfe.ProcessDuplicates();
}
//
// We need to rebuild all the hash tables.
//
TypeSystemForCodeTransformation typeSystem = m_typeSystem;
Transform( ref typeSystem );
typeSystem.RefreshHashCodesAfterTypeSystemRemapping();
}
}
//--//
protected override bool ShouldRefreshHashCodes()
{
return true;
}
//--//
private void ProcessType( TypeRepresentation td )
{
if(m_typeSystem.ReachabilitySet.IsProhibited( td ) == false)
{
CustomAttributeRepresentation ca = td.FindCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_ExtendClassAttribute );
if(ca != null)
{
object objTarget = ca.FixedArgsValues[0];
TypeRepresentation tdTarget = objTarget as TypeRepresentation;
bool fNoConstructors = false;
object obj;
if(tdTarget == null)
{
tdTarget = m_typeSystem.GetWellKnownTypeNoThrow( objTarget as string );
}
if(tdTarget == null)
{
throw TypeConsistencyErrorException.Create( "Missing target class to extend: {0}", objTarget );
}
if(td.IsOpenType == false && tdTarget.IsOpenType)
{
List< TypeRepresentation > lstTdTarget;
if(m_typeSystem.GenericTypeInstantiations.TryGetValue( tdTarget, out lstTdTarget ) == false)
{
throw TypeConsistencyErrorException.Create( "Found mismatch between instantiation of class extension and target class: {0} not compatible with {1}", td, tdTarget );
}
tdTarget = null;
foreach(var tdTarget2 in lstTdTarget)
{
if(tdTarget2.IsOpenType == false && ArrayUtility.ArrayEqualsNotNull( td.GenericParameters, tdTarget2.GenericParameters, 0 ))
{
tdTarget = tdTarget2;
}
}
if(tdTarget == null)
{
throw TypeConsistencyErrorException.Create( "Missing target class to extend: {0}", objTarget );
}
}
obj = ca.GetNamedArg( "NoConstructors" );
if(obj != null)
{
fNoConstructors = (bool)obj;
}
obj = ca.GetNamedArg( "ProcessAfter" );
if(obj != null)
{
TypeRepresentation tdPre = (TypeRepresentation)obj;
if(tdPre.HasCustomAttribute( m_typeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_ExtendClassAttribute ))
{
ProcessType( tdPre );
}
}
TypeRepresentation tdExtends = td.Extends;
if(tdExtends != null)
{
ProcessType( tdExtends );
}
//
// HACK: Generic type extension is handled at the end of meta data import.
//
if(td.IsOpenType || tdTarget.IsOpenType)
{
return;
}
using(new Transformations.ExecutionTiming( "PerformClassExtension from {0} to {1}", td, tdTarget ))
{
var pfe = new Transformations.PerformClassExtension( m_typeSystem, m_reverseIndex, m_duplicates, td, tdTarget, fNoConstructors );
pfe.Execute();
}
m_fChanged = true;
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="LinkArea.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System;
using System.Reflection;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Collections;
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[
TypeConverterAttribute(typeof(LinkArea.LinkAreaConverter)),
Serializable
]
public struct LinkArea {
int start;
int length;
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.LinkArea"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public LinkArea(int start, int length) {
this.start = start;
this.length = length;
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.Start"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Start {
get {
return start;
}
set {
start = value;
}
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.Length"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int Length {
get {
return length;
}
set {
length = value;
}
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.IsEmpty"]/*' />
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsEmpty {
get {
return length == start && start == 0;
}
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.Equals"]/*' />
public override bool Equals(object o) {
if (!(o is LinkArea)) {
return false;
}
LinkArea a = (LinkArea)o;
return this == a;
}
public override string ToString() {
return "{Start=" + Start.ToString(CultureInfo.CurrentCulture) + ", Length=" + Length.ToString(CultureInfo.CurrentCulture) + "}";
}
public static bool operator == (LinkArea linkArea1, LinkArea linkArea2){
return (linkArea1.start == linkArea2.start) && (linkArea1.length == linkArea2.length);
}
public static bool operator != (LinkArea linkArea1, LinkArea linkArea2) {
return !(linkArea1 == linkArea2);
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.GetHashCode"]/*' />
public override int GetHashCode() {
return start << 4 | length;
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.LinkAreaConverter"]/*' />
/// <devdoc>
/// LinkAreaConverter is a class that can be used to convert
/// LinkArea from one data type to another. Access this
/// class through the TypeDescriptor.
/// </devdoc>
public class LinkAreaConverter : TypeConverter {
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.LinkAreaConverter.CanConvertFrom"]/*' />
/// <devdoc>
/// Determines if this converter can convert an object in the given source
/// type to the native type of the converter.
/// </devdoc>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string)) {
return true;
}
return base.CanConvertFrom(context, sourceType);
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.LinkAreaConverter.CanConvertTo"]/*' />
/// <devdoc>
/// <para>Gets a value indicating whether this converter can
/// convert an object to the given destination type using the context.</para>
/// </devdoc>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (destinationType == typeof(InstanceDescriptor)) {
return true;
}
return base.CanConvertTo(context, destinationType);
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.LinkAreaConverter.ConvertFrom"]/*' />
/// <devdoc>
/// Converts the given object to the converter's native type.
/// </devdoc>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
if (value is string) {
string text = ((string)value).Trim();
if (text.Length == 0) {
return null;
}
else {
// Parse 2 integer values.
//
if (culture == null) {
culture = CultureInfo.CurrentCulture;
}
char sep = culture.TextInfo.ListSeparator[0];
string[] tokens = text.Split(new char[] {sep});
int[] values = new int[tokens.Length];
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
for (int i = 0; i < values.Length; i++) {
values[i] = (int)intConverter.ConvertFromString(context, culture, tokens[i]);
}
if (values.Length == 2) {
return new LinkArea(values[0], values[1]);
}
else {
throw new ArgumentException(SR.GetString(SR.TextParseFailedFormat,
text,
"start, length"));
}
}
}
return base.ConvertFrom(context, culture, value);
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.LinkAreaConverter.ConvertTo"]/*' />
/// <devdoc>
/// Converts the given object to another type. The most common types to convert
/// are to and from a string object. The default implementation will make a call
/// to ToString on the object if the object is valid and if the destination
/// type is string. If this cannot convert to the desitnation type, this will
/// throw a NotSupportedException.
/// </devdoc>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
if (destinationType == null) {
throw new ArgumentNullException("destinationType");
}
if (destinationType == typeof(string) && value is LinkArea) {
LinkArea pt = (LinkArea)value;
if (culture == null) {
culture = CultureInfo.CurrentCulture;
}
string sep = culture.TextInfo.ListSeparator + " ";
TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
string[] args = new string[2];
int nArg = 0;
args[nArg++] = intConverter.ConvertToString(context, culture, pt.Start);
args[nArg++] = intConverter.ConvertToString(context, culture, pt.Length);
return string.Join(sep, args);
}
if (destinationType == typeof(InstanceDescriptor) && value is LinkArea) {
LinkArea pt = (LinkArea)value;
ConstructorInfo ctor = typeof(LinkArea).GetConstructor(new Type[] {typeof(int), typeof(int)});
if (ctor != null) {
return new InstanceDescriptor(ctor, new object[] {pt.Start, pt.Length});
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.LinkAreaConverter.CreateInstance"]/*' />
/// <devdoc>
/// Creates an instance of this type given a set of property values
/// for the object. This is useful for objects that are immutable, but still
/// want to provide changable properties.
/// </devdoc>
public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues) {
return new LinkArea((int)propertyValues["Start"],
(int)propertyValues["Length"]);
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.LinkAreaConverter.GetCreateInstanceSupported"]/*' />
/// <devdoc>
/// Determines if changing a value on this object should require a call to
/// CreateInstance to create a new value.
/// </devdoc>
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) {
return true;
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.LinkAreaConverter.GetProperties"]/*' />
/// <devdoc>
/// Retrieves the set of properties for this type. By default, a type has
/// does not return any properties. An easy implementation of this method
/// can just call TypeDescriptor.GetProperties for the correct data type.
/// </devdoc>
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) {
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(LinkArea), attributes);
return props.Sort(new string[] {"Start", "Length"});
}
/// <include file='doc\LinkArea.uex' path='docs/doc[@for="LinkArea.LinkAreaConverter.GetPropertiesSupported"]/*' />
/// <devdoc>
/// Determines if this object supports properties. By default, this
/// is false.
/// </devdoc>
public override bool GetPropertiesSupported(ITypeDescriptorContext context) {
return true;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 CompareGreaterThanSByte()
{
var test = new SimpleBinaryOpTest__CompareGreaterThanSByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareGreaterThanSByte
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(SByte);
private static SByte[] _data1 = new SByte[ElementCount];
private static SByte[] _data2 = new SByte[ElementCount];
private static Vector256<SByte> _clsVar1;
private static Vector256<SByte> _clsVar2;
private Vector256<SByte> _fld1;
private Vector256<SByte> _fld2;
private SimpleBinaryOpTest__DataTable<SByte> _dataTable;
static SimpleBinaryOpTest__CompareGreaterThanSByte()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareGreaterThanSByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<SByte>(_data1, _data2, new SByte[ElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.CompareGreaterThan(
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.CompareGreaterThan(
Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.CompareGreaterThan(
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareGreaterThan), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareGreaterThan), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) })
.Invoke(null, new object[] {
Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareGreaterThan), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.CompareGreaterThan(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr);
var result = Avx2.CompareGreaterThan(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr));
var result = Avx2.CompareGreaterThan(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr));
var result = Avx2.CompareGreaterThan(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareGreaterThanSByte();
var result = Avx2.CompareGreaterThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.CompareGreaterThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<SByte> left, Vector256<SByte> right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[ElementCount];
SByte[] inArray2 = new SByte[ElementCount];
SByte[] outArray = new SByte[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[ElementCount];
SByte[] inArray2 = new SByte[ElementCount];
SByte[] outArray = new SByte[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
if (result[0] != ((left[0] > right[0]) ? unchecked((sbyte)(-1)) : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (result[i] != ((left[i] > right[i]) ? unchecked((sbyte)(-1)) : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.CompareGreaterThan)}<SByte>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
#region Copyright Information
// Sentience Lab Unity Framework
// (C) Sentience Lab ([email protected]), Auckland University of Technology, Auckland, New Zealand
#endregion Copyright Information
using System.Collections.Generic;
using UnityEngine;
using UnityOSC;
namespace SentienceLab.OSC
{
public interface IOSCVariableContainer
{
List<OSC_Variable> GetOSC_Variables();
}
public abstract class OSC_Variable
{
public string Name;
/// <summary>
/// Class for delegates that are notified when an OSC variable has received new data.
/// </summary>
/// <param name="var">the variable that has received data</param>
///
public delegate void DataReceived(OSC_Variable var);
public event DataReceived OnDataReceived;
public OSC_Variable(string _name = "")
{
Name = _name;
m_manager = null;
}
public void SetManager(OSC_Manager _manager)
{
m_manager = _manager;
}
public bool CanAccept(OSCPacket _packet)
{
return _packet.Address.CompareTo(Name) == 0;
}
public void Accept(OSCPacket _packet)
{
Unpack(_packet);
m_packetReceived = true;
}
public abstract void Unpack(OSCPacket _packet);
public void SendUpdate()
{
if (m_manager != null)
{
OSCPacket packet = new OSCMessage(Name);
Pack(packet);
m_manager.SendPacket(packet);
}
}
public abstract void Pack(OSCPacket _packet);
public void Update()
{
// notify listener within the main Unity update loop
if (m_packetReceived)
{
if (OnDataReceived != null) OnDataReceived.Invoke(this);
m_packetReceived = false;
}
}
private OSC_Manager m_manager;
private bool m_packetReceived;
}
public class OSC_BoolVariable : OSC_Variable
{
public bool Value;
public OSC_BoolVariable(string _name = "") : base(_name)
{
Value = false;
}
public override void Unpack(OSCPacket _packet)
{
object obj = _packet.Data[0];
System.Type type = obj.GetType();
if (type == typeof(byte) ) { Value = ((byte)obj) > 0; }
else if (type == typeof(int) ) { Value = ((int)obj) > 0; }
else if (type == typeof(long) ) { Value = ((long)obj) > 0; }
else if (type == typeof(float) ) { Value = ((float)obj) > 0; }
else if (type == typeof(double)) { Value = ((double)obj) > 0; }
}
public override void Pack(OSCPacket _packet)
{
_packet.Append<int>(Value ? 1 : 0);
}
}
public class OSC_IntVariable : OSC_Variable
{
public int Value;
public int Min, Max;
public OSC_IntVariable(string _name = "", int _min = int.MinValue, int _max = int.MaxValue) : base(_name)
{
Value = 0;
Min = _min;
Max = _max;
}
public override void Unpack(OSCPacket _packet)
{
object obj = _packet.Data[0];
System.Type type = obj.GetType();
if (type == typeof(byte) ) { Value = (byte)obj; }
else if (type == typeof(int) ) { Value = (int)obj; }
else if (type == typeof(long) ) { Value = (int)((long)obj); }
else if (type == typeof(float) ) { Value = (int)((float)obj); }
else if (type == typeof(double)) { Value = (int)((double)obj); }
if (Value > Max) { Value = Max; }
if (Value < Min) { Value = Min; }
}
public override void Pack(OSCPacket _packet)
{
_packet.Append<int>(Value);
}
}
public class OSC_FloatVariable : OSC_Variable
{
public float Value;
public float Min, Max;
public OSC_FloatVariable(string _name = "", float _min = 0, float _max = 1) : base(_name)
{
Value = 0;
Min = _min;
Max = _max;
}
public override void Unpack(OSCPacket _packet)
{
object obj = _packet.Data[0];
System.Type type = obj.GetType();
if (type == typeof(byte) ) { Value = ((byte)obj); }
else if (type == typeof(int) ) { Value = ((int)obj); }
else if (type == typeof(long) ) { Value = ((long)obj); }
else if (type == typeof(float) ) { Value = (float)obj; }
else if (type == typeof(double)) { Value = (float)((double)obj); }
if (Value > Max) { Value = Max; }
if (Value < Min) { Value = Min; }
}
public override void Pack(OSCPacket _packet)
{
_packet.Append<float>(Value);
}
}
public class OSC_Vector2Variable : OSC_Variable
{
public Vector2 Value;
public OSC_Vector2Variable(string _name = "") : base(_name)
{
Value = Vector2.zero;
}
public override void Unpack(OSCPacket _packet)
{
for (int idx = 0; idx < _packet.Data.Count; idx++)
{
object obj = _packet.Data[idx];
System.Type type = obj.GetType();
float value = 0;
if (type == typeof(byte) ) { value = ((byte)obj); }
else if (type == typeof(int) ) { value = ((int)obj); }
else if (type == typeof(long) ) { value = ((long)obj); }
else if (type == typeof(float) ) { value = (float)obj; }
else if (type == typeof(double)) { value = (float)((double)obj); }
switch (idx)
{
case 0: Value.x = value; break;
case 1: Value.y = value; break;
default: break;
}
}
}
public override void Pack(OSCPacket _packet)
{
_packet.Append<float>(Value.x);
_packet.Append<float>(Value.y);
}
}
public class OSC_Vector3Variable : OSC_Variable
{
public Vector3 Value;
public OSC_Vector3Variable(string _name = "") : base(_name)
{
Value = Vector3.zero;
}
public override void Unpack(OSCPacket _packet)
{
for (int idx = 0; idx < _packet.Data.Count; idx++)
{
object obj = _packet.Data[idx];
System.Type type = obj.GetType();
float value = 0;
if (type == typeof(byte) ) { value = ((byte)obj); }
else if (type == typeof(int) ) { value = ((int)obj); }
else if (type == typeof(long) ) { value = ((long)obj); }
else if (type == typeof(float) ) { value = (float)obj; }
else if (type == typeof(double)) { value = (float)((double)obj); }
switch (idx)
{
case 0: Value.x = value; break;
case 1: Value.y = value; break;
case 2: Value.z = value; break;
default: break;
}
}
}
public override void Pack(OSCPacket _packet)
{
_packet.Append<float>(Value.x);
_packet.Append<float>(Value.y);
_packet.Append<float>(Value.z);
}
}
public class OSC_StringVariable : OSC_Variable
{
public string Value;
public OSC_StringVariable(string _name = "") : base(_name)
{
Value = "";
}
public override void Unpack(OSCPacket _packet)
{
object obj = _packet.Data[0];
System.Type type = obj.GetType();
if (type == typeof(string)) { Value = (string)obj; }
/*
else if (type == typeof(byte) ) { value = (byte)obj; }
else if (type == typeof(int) ) { value = (int)obj; }
else if (type == typeof(long) ) { value = (int) ((long)obj); }
else if (type == typeof(float) ) { value = (int) ((float)obj); }
else if (type == typeof(double)) { value = (int) ((double)obj); }
*/
}
public override void Pack(OSCPacket _packet)
{
_packet.Append<string>(Value);
}
}
}
| |
/*
* Copyright (c) 2007-2008, Second Life Reverse Engineering Team
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the Second Life Reverse Engineering Team nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using libsecondlife.StructuredData;
using libsecondlife.Capabilities;
using libsecondlife.Packets;
namespace libsecondlife
{
#region Enums
/// <summary>
///
/// </summary>
public enum LoginStatus
{
/// <summary></summary>
Failed = -1,
/// <summary></summary>
None = 0,
/// <summary></summary>
ConnectingToLogin,
/// <summary></summary>
ReadingResponse,
/// <summary></summary>
ConnectingToSim,
/// <summary></summary>
Redirecting,
/// <summary></summary>
Success
}
#endregion Enums
#region Structs
/// <summary>
///
/// </summary>
public struct LoginParams
{
/// <summary></summary>
public string URI;
/// <summary></summary>
public int Timeout;
/// <summary></summary>
public string MethodName;
/// <summary></summary>
public string FirstName;
/// <summary></summary>
public string LastName;
/// <summary></summary>
public string Password;
/// <summary></summary>
public string Start;
/// <summary></summary>
public string Channel;
/// <summary></summary>
public string Version;
/// <summary></summary>
public string Platform;
/// <summary></summary>
public string MAC;
/// <summary></summary>
public string ViewerDigest;
/// <summary></summary>
public List<string> Options;
/// <summary></summary>
public string id0;
}
public struct LoginResponseData
{
public LLUUID AgentID;
public LLUUID SessionID;
public LLUUID SecureSessionID;
public string FirstName;
public string LastName;
public string StartLocation;
public string AgentAccess;
public LLVector3 LookAt;
public ulong HomeRegion;
public LLVector3 HomePosition;
public LLVector3 HomeLookAt;
public uint CircuitCode;
public uint RegionX;
public uint RegionY;
public ushort SimPort;
public IPAddress SimIP;
public string SeedCapability;
public FriendInfo[] BuddyList;
public DateTime SecondsSinceEpoch;
public LLUUID InventoryRoot;
public LLUUID LibraryRoot;
public InventoryFolder[] InventorySkeleton;
public InventoryFolder[] LibrarySkeleton;
public LLUUID LibraryOwner;
public void Parse(LLSDMap reply)
{
try
{
AgentID = ParseUUID("agent_id", reply);
SessionID = ParseUUID("session_id", reply);
SecureSessionID = ParseUUID("secure_session_id", reply);
FirstName = ParseString("first_name", reply).Trim('"');
LastName = ParseString("last_name", reply).Trim('"');
StartLocation = ParseString("start_location", reply);
AgentAccess = ParseString("agent_access", reply);
LookAt = ParseLLVector3("look_at", reply);
}
catch (LLSDException e)
{
// FIXME: sometimes look_at comes back with invalid values e.g: 'look_at':'[r1,r2.0193899999999998204e-06,r0]'
// need to handle that somehow
Logger.DebugLog("login server returned (some) invalid data: " + e.Message);
}
// Home
LLSDMap home = null;
LLSD llsdHome = LLSDParser.DeserializeNotation(reply["home"].AsString());
if (llsdHome.Type == LLSDType.Map)
{
home = (LLSDMap)llsdHome;
LLSD homeRegion;
if (home.TryGetValue("region_handle", out homeRegion) && homeRegion.Type == LLSDType.Array)
{
LLSDArray homeArray = (LLSDArray)homeRegion;
if (homeArray.Count == 2)
HomeRegion = Helpers.UIntsToLong((uint)homeArray[0].AsInteger(), (uint)homeArray[1].AsInteger());
else
HomeRegion = 0;
}
HomePosition = ParseLLVector3("position", home);
HomeLookAt = ParseLLVector3("look_at", home);
}
else
{
HomeRegion = 0;
HomePosition = LLVector3.Zero;
HomeLookAt = LLVector3.Zero;
}
CircuitCode = ParseUInt("circuit_code", reply);
RegionX = ParseUInt("region_x", reply);
RegionY = ParseUInt("region_y", reply);
SimPort = (ushort)ParseUInt("sim_port", reply);
string simIP = ParseString("sim_ip", reply);
IPAddress.TryParse(simIP, out SimIP);
SeedCapability = ParseString("seed_capability", reply);
// Buddy list
LLSD buddyLLSD;
if (reply.TryGetValue("buddy-list", out buddyLLSD) && buddyLLSD.Type == LLSDType.Array)
{
LLSDArray buddyArray = (LLSDArray)buddyLLSD;
BuddyList = new FriendInfo[buddyArray.Count];
for (int i = 0; i < buddyArray.Count; i++)
{
if (buddyArray[i].Type == LLSDType.Map)
{
LLSDMap buddy = (LLSDMap)buddyArray[i];
BuddyList[i] = new FriendInfo(
ParseUUID("buddy_id", buddy),
(FriendRights)ParseUInt("buddy_rights_given", buddy),
(FriendRights)ParseUInt("buddy_rights_has", buddy));
}
}
}
SecondsSinceEpoch = Helpers.UnixTimeToDateTime(ParseUInt("seconds_since_epoch", reply));
InventoryRoot = ParseMappedUUID("inventory-root", "folder_id", reply);
InventorySkeleton = ParseInventoryFolders("inventory-skeleton", AgentID, reply);
LibraryRoot = ParseMappedUUID("inventory-lib-root", "folder_id", reply);
LibraryOwner = ParseMappedUUID("inventory-lib-owner", "agent_id", reply);
LibrarySkeleton = ParseInventoryFolders("inventory-skel-lib", LibraryOwner, reply);
}
#region Parsing Helpers
public static uint ParseUInt(string key, LLSDMap reply)
{
LLSD llsd;
if (reply.TryGetValue(key, out llsd))
return (uint)llsd.AsInteger();
else
return 0;
}
public static LLUUID ParseUUID(string key, LLSDMap reply)
{
LLSD llsd;
if (reply.TryGetValue(key, out llsd))
return llsd.AsUUID();
else
return LLUUID.Zero;
}
public static string ParseString(string key, LLSDMap reply)
{
LLSD llsd;
if (reply.TryGetValue(key, out llsd))
return llsd.AsString();
else
return String.Empty;
}
public static LLVector3 ParseLLVector3(string key, LLSDMap reply)
{
LLSD llsd;
if (reply.TryGetValue(key, out llsd))
{
if (llsd.Type == LLSDType.Array)
{
LLVector3 vec = new LLVector3();
vec.FromLLSD(llsd);
return vec;
}
else if (llsd.Type == LLSDType.String)
{
LLSDArray array = (LLSDArray)LLSDParser.DeserializeNotation(llsd.AsString());
LLVector3 vec = new LLVector3();
vec.FromLLSD(array);
return vec;
}
}
return LLVector3.Zero;
}
public static LLUUID ParseMappedUUID(string key, string key2, LLSDMap reply)
{
LLSD folderLLSD;
if (reply.TryGetValue(key, out folderLLSD) && folderLLSD.Type == LLSDType.Array)
{
LLSDArray array = (LLSDArray)folderLLSD;
if (array.Count == 1 && array[0].Type == LLSDType.Map)
{
LLSDMap map = (LLSDMap)array[0];
LLSD folder;
if (map.TryGetValue(key2, out folder))
return folder.AsUUID();
}
}
return LLUUID.Zero;
}
public static InventoryFolder[] ParseInventoryFolders(string key, LLUUID owner, LLSDMap reply)
{
List<InventoryFolder> folders = new List<InventoryFolder>();
LLSD skeleton;
if (reply.TryGetValue(key, out skeleton) && skeleton.Type == LLSDType.Array)
{
LLSDArray array = (LLSDArray)skeleton;
for (int i = 0; i < array.Count; i++)
{
if (array[i].Type == LLSDType.Map)
{
LLSDMap map = (LLSDMap)array[i];
InventoryFolder folder = new InventoryFolder(map["folder_id"].AsUUID());
folder.PreferredType = (AssetType)map["type_default"].AsInteger();
folder.Version = map["version"].AsInteger();
folder.OwnerID = owner;
folder.ParentUUID = map["parent_id"].AsUUID();
folder.Name = map["name"].AsString();
folders.Add(folder);
}
}
return folders.ToArray();
}
return new InventoryFolder[0];
}
#endregion Parsing Helpers
}
#endregion Structs
// TODO: Remove me when MONO can handle ServerCertificateValidationCallback
internal class AcceptAllCertificatePolicy : ICertificatePolicy
{
public AcceptAllCertificatePolicy()
{
}
public bool CheckValidationResult(ServicePoint sPoint,
System.Security.Cryptography.X509Certificates.X509Certificate cert,
WebRequest wRequest, int certProb)
{
// Always accept
return true;
}
}
public partial class NetworkManager
{
#region Delegates
/// <summary>
///
/// </summary>
/// <param name="login"></param>
/// <param name="message"></param>
public delegate void LoginCallback(LoginStatus login, string message);
/// <summary>
///
/// </summary>
/// <param name="loginSuccess"></param>
/// <param name="redirect"></param>
/// <param name="replyData"></param>
public delegate void LoginResponseCallback(bool loginSuccess, bool redirect, string message, string reason, LoginResponseData replyData);
#endregion Delegates
#region Events
/// <summary>Called any time the login status changes, will eventually
/// return LoginStatus.Success or LoginStatus.Failure</summary>
public event LoginCallback OnLogin;
/// <summary>Called when a reply is received from the login server, the
/// login sequence will block until this event returns</summary>
private event LoginResponseCallback OnLoginResponse;
#endregion Events
/// <summary>Seed CAPS URL returned from the login server</summary>
public string LoginSeedCapability = String.Empty;
/// <summary>Current state of logging in</summary>
public LoginStatus LoginStatusCode { get { return InternalStatusCode; } }
/// <summary>Upon login failure, contains a short string key for the
/// type of login error that occurred</summary>
public string LoginErrorKey { get { return InternalErrorKey; } }
/// <summary>The raw XML-RPC reply from the login server, exactly as it
/// was received (minus the HTTP header)</summary>
public string RawLoginReply { get { return InternalRawLoginReply; } }
/// <summary>During login this contains a descriptive version of
/// LoginStatusCode. After a successful login this will contain the
/// message of the day, and after a failed login a descriptive error
/// message will be returned</summary>
public string LoginMessage { get { return InternalLoginMessage; } }
private LoginParams? CurrentContext = null;
private AutoResetEvent LoginEvent = new AutoResetEvent(false);
private LoginStatus InternalStatusCode = LoginStatus.None;
private string InternalErrorKey = String.Empty;
private string InternalLoginMessage = String.Empty;
private string InternalRawLoginReply = String.Empty;
private Dictionary<LoginResponseCallback, string[]> CallbackOptions = new Dictionary<LoginResponseCallback, string[]>();
/// <summary>
///
/// </summary>
/// <param name="firstName">Account first name</param>
/// <param name="lastName">Account last name</param>
/// <param name="password">Account password</param>
/// <param name="userAgent">Client application name</param>
/// <param name="userVersion">Client application version</param>
/// <returns></returns>
public LoginParams DefaultLoginParams(string firstName, string lastName, string password,
string userAgent, string userVersion)
{
List<string> options = new List<string>();
//options.Add("gestures");
//options.Add("event_categories");
//options.Add("event_notifications");
//options.Add("classified_categories");
//options.Add("ui-config");
//options.Add("login-flags");
//options.Add("global-textures");
//options.Add("initial-outfit");
LoginParams loginParams = new LoginParams();
loginParams.URI = Client.Settings.LOGIN_SERVER;
loginParams.Timeout = Client.Settings.LOGIN_TIMEOUT;
loginParams.MethodName = "login_to_simulator";
loginParams.FirstName = firstName;
loginParams.LastName = lastName;
loginParams.Password = password;
loginParams.Start = "last";
loginParams.Channel = userAgent + " (libsecondlife)";
loginParams.Version = userVersion;
loginParams.Platform = GetPlatform();
loginParams.MAC = GetMAC();
loginParams.ViewerDigest = String.Empty;
loginParams.Options = options;
// workaround for bots being caught up in a global ban
// This *should* be the hash of the first hard drive,
// but any unique identifier works.
loginParams.id0 = GetMAC();
return loginParams;
}
/// <summary>
/// Simplified login that takes the most common and required fields
/// </summary>
/// <param name="firstName">Account first name</param>
/// <param name="lastName">Account last name</param>
/// <param name="password">Account password</param>
/// <param name="userAgent">Client application name</param>
/// <param name="userVersion">Client application version</param>
/// <returns>Whether the login was successful or not. On failure the
/// LoginErrorKey string will contain the error code and LoginMessage
/// will contain a description of the error</returns>
public bool Login(string firstName, string lastName, string password, string userAgent, string userVersion)
{
return Login(firstName, lastName, password, userAgent, "last", userVersion);
}
/// <summary>
/// Simplified login that takes the most common fields along with a
/// starting location URI, and can accept an MD5 string instead of a
/// plaintext password
/// </summary>
/// <param name="firstName">Account first name</param>
/// <param name="lastName">Account last name</param>
/// <param name="password">Account password or MD5 hash of the password
/// such as $1$1682a1e45e9f957dcdf0bb56eb43319c</param>
/// <param name="userAgent">Client application name</param>
/// <param name="start">Starting location URI that can be built with
/// StartLocation()</param>
/// <param name="userVersion">Client application version</param>
/// <returns>Whether the login was successful or not. On failure the
/// LoginErrorKey string will contain the error code and LoginMessage
/// will contain a description of the error</returns>
public bool Login(string firstName, string lastName, string password, string userAgent, string start,
string userVersion)
{
LoginParams loginParams = DefaultLoginParams(firstName, lastName, password, userAgent, userVersion);
loginParams.Start = start;
return Login(loginParams);
}
/// <summary>
/// Login that takes a struct of all the values that will be passed to
/// the login server
/// </summary>
/// <param name="loginParams">The values that will be passed to the login
/// server, all fields must be set even if they are String.Empty</param>
/// <returns>Whether the login was successful or not. On failure the
/// LoginErrorKey string will contain the error code and LoginMessage
/// will contain a description of the error</returns>
public bool Login(LoginParams loginParams)
{
BeginLogin(loginParams);
LoginEvent.WaitOne(loginParams.Timeout, false);
if (CurrentContext != null)
{
CurrentContext = null; // Will force any pending callbacks to bail out early
InternalStatusCode = LoginStatus.Failed;
InternalLoginMessage = "Timed out";
return false;
}
return (InternalStatusCode == LoginStatus.Success);
}
public void BeginLogin(LoginParams loginParams)
{
// FIXME: Now that we're using CAPS we could cancel the current login and start a new one
if (CurrentContext != null)
throw new Exception("Login already in progress");
LoginEvent.Reset();
CurrentContext = loginParams;
BeginLogin();
}
public void RegisterLoginResponseCallback(LoginResponseCallback callback)
{
RegisterLoginResponseCallback(callback, null);
}
public void RegisterLoginResponseCallback(LoginResponseCallback callback, string[] options)
{
CallbackOptions.Add(callback, options);
OnLoginResponse += callback;
}
public void UnregisterLoginResponseCallback(LoginResponseCallback callback)
{
CallbackOptions.Remove(callback);
OnLoginResponse -= callback;
}
/// <summary>
/// Build a start location URI for passing to the Login function
/// </summary>
/// <param name="sim">Name of the simulator to start in</param>
/// <param name="x">X coordinate to start at</param>
/// <param name="y">Y coordinate to start at</param>
/// <param name="z">Z coordinate to start at</param>
/// <returns>String with a URI that can be used to login to a specified
/// location</returns>
public static string StartLocation(string sim, int x, int y, int z)
{
return String.Format("uri:{0}&{1}&{2}&{3}", sim.ToLower(), x, y, z);
}
private void BeginLogin()
{
LoginParams loginParams = CurrentContext.Value;
// Sanity check
if (loginParams.Options == null)
loginParams.Options = new List<string>();
// Convert the password to MD5 if it isn't already
if (loginParams.Password.Length != 35 && !loginParams.Password.StartsWith("$1$"))
loginParams.Password = Helpers.MD5(loginParams.Password);
// Override SSL authentication mechanisms. DO NOT convert this to the
// .NET 2.0 preferred method, the equivalent function in Mono has a
// different name and it will break compatibility!
ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();
// TODO: At some point, maybe we should check the cert?
// Create the CAPS login structure
LLSDMap loginLLSD = new LLSDMap();
loginLLSD["first"] = LLSD.FromString(loginParams.FirstName);
loginLLSD["last"] = LLSD.FromString(loginParams.LastName);
loginLLSD["passwd"] = LLSD.FromString(loginParams.Password);
loginLLSD["start"] = LLSD.FromString(loginParams.Start);
loginLLSD["channel"] = LLSD.FromString(loginParams.Channel);
loginLLSD["version"] = LLSD.FromString(loginParams.Version);
loginLLSD["platform"] = LLSD.FromString(loginParams.Platform);
loginLLSD["mac"] = LLSD.FromString(loginParams.MAC);
loginLLSD["agree_to_tos"] = LLSD.FromBoolean(true);
loginLLSD["read_critical"] = LLSD.FromBoolean(true);
loginLLSD["viewer_digest"] = LLSD.FromString(loginParams.ViewerDigest);
loginLLSD["id0"] = LLSD.FromString(loginParams.id0);
// Create the options LLSD array
LLSDArray optionsLLSD = new LLSDArray();
for (int i = 0; i < loginParams.Options.Count; i++)
optionsLLSD.Add(LLSD.FromString(loginParams.Options[i]));
foreach (string[] callbackOpts in CallbackOptions.Values)
{
if (callbackOpts != null)
{
for (int i = 0; i < callbackOpts.Length; i++)
{
if (!optionsLLSD.Contains(callbackOpts[i]))
optionsLLSD.Add(callbackOpts[i]);
}
}
}
loginLLSD["options"] = optionsLLSD;
// Make the CAPS POST for login
Uri loginUri;
try
{
loginUri = new Uri(loginParams.URI);
}
catch (Exception ex)
{
Logger.Log(String.Format("Failed to parse login URI {0}, {1}", loginParams.URI, ex.Message),
Helpers.LogLevel.Error, Client);
return;
}
CapsClient loginRequest = new CapsClient(new Uri(loginParams.URI));
loginRequest.OnComplete += new CapsClient.CompleteCallback(LoginReplyHandler);
loginRequest.UserData = CurrentContext;
loginRequest.StartRequest(LLSDParser.SerializeXmlBytes(loginLLSD), "application/xml+llsd");
}
private void UpdateLoginStatus(LoginStatus status, string message)
{
InternalStatusCode = status;
InternalLoginMessage = message;
Logger.DebugLog("Login status: " + status.ToString() + ": " + message, Client);
// If we reached a login resolution trigger the event
if (status == LoginStatus.Success || status == LoginStatus.Failed)
{
CurrentContext = null;
LoginEvent.Set();
}
// Fire the login status callback
if (OnLogin != null)
{
try { OnLogin(status, message); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
private void LoginReplyHandler(CapsClient client, LLSD result, Exception error)
{
if (error == null)
{
if (result != null && result.Type == LLSDType.Map)
{
LLSDMap map = (LLSDMap)result;
LLSD llsd;
string reason, message;
if (map.TryGetValue("reason", out llsd))
reason = llsd.AsString();
else
reason = String.Empty;
if (map.TryGetValue("message", out llsd))
message = llsd.AsString();
else
message = String.Empty;
if (map.TryGetValue("login", out llsd))
{
bool loginSuccess = llsd.AsBoolean();
bool redirect = (llsd.AsString() == "indeterminate");
LoginResponseData data = new LoginResponseData();
// Parse successful login replies in to LoginResponseData structs
if (loginSuccess)
data.Parse(map);
if (OnLoginResponse != null)
{
try { OnLoginResponse(loginSuccess, redirect, message, reason, data); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); }
}
if (loginSuccess && !redirect)
{
// Login succeeded
// These parameters are stored in NetworkManager, so instead of registering
// another callback for them we just set the values here
CircuitCode = data.CircuitCode;
LoginSeedCapability = data.SeedCapability;
UpdateLoginStatus(LoginStatus.ConnectingToSim, "Connecting to simulator...");
ulong handle = Helpers.UIntsToLong(data.RegionX, data.RegionY);
if (data.SimIP != null && data.SimPort != 0)
{
// Connect to the sim given in the login reply
if (Connect(data.SimIP, data.SimPort, handle, true, LoginSeedCapability) != null)
{
// Request the economy data right after login
SendPacket(new EconomyDataRequestPacket());
// Update the login message with the MOTD returned from the server
UpdateLoginStatus(LoginStatus.Success, message);
// Fire an event for connecting to the grid
if (OnConnected != null)
{
try { OnConnected(this.Client); }
catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); }
}
}
else
{
UpdateLoginStatus(LoginStatus.Failed,
"Unable to establish a UDP connection to the simulator");
}
}
else
{
UpdateLoginStatus(LoginStatus.Failed,
"Login server did not return a simulator address");
}
}
else if (redirect)
{
// Login redirected
// Make the next login URL jump
UpdateLoginStatus(LoginStatus.Redirecting, "Redirecting login...");
LoginParams loginParams = CurrentContext.Value;
loginParams.URI = LoginResponseData.ParseString("next_url", map);
//CurrentContext.Params.MethodName = LoginResponseData.ParseString("next_method", map);
// Sleep for some amount of time while the servers work
int seconds = (int)LoginResponseData.ParseUInt("next_duration", map);
Logger.Log("Sleeping for " + seconds + " seconds during a login redirect",
Helpers.LogLevel.Info);
Thread.Sleep(seconds * 1000);
// Ignore next_options for now
CurrentContext = loginParams;
BeginLogin();
}
else
{
// Login failed
// Make sure a usable error key is set
if (reason != String.Empty)
InternalErrorKey = reason;
else
InternalErrorKey = "unknown";
UpdateLoginStatus(LoginStatus.Failed, message);
}
}
else
{
// Got an LLSD map but no login value
UpdateLoginStatus(LoginStatus.Failed, "login parameter missing in the response");
}
}
else
{
// No LLSD response
InternalErrorKey = "bad response";
UpdateLoginStatus(LoginStatus.Failed, "Empty or unparseable login response");
}
}
else
{
// Connection error
InternalErrorKey = "no connection";
UpdateLoginStatus(LoginStatus.Failed, error.Message);
}
}
/// <summary>
/// Get current OS
/// </summary>
/// <returns>Either "Win" or "Linux"</returns>
private static string GetPlatform()
{
switch (Environment.OSVersion.Platform)
{
case PlatformID.Unix:
return "Linux";
default:
return "Win";
}
}
/// <summary>
/// Get clients default Mac Address
/// </summary>
/// <returns>A string containing the first found Mac Address</returns>
private static string GetMAC()
{
string mac = "";
System.Net.NetworkInformation.NetworkInterface[] nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
if (nics.Length > 0)
{
mac = nics[0].GetPhysicalAddress().ToString().ToUpper();
}
if (mac.Length < 12)
{
mac = mac.PadRight(12, '0');
}
return String.Format("{0}:{1}:{2}:{3}:{4}:{5}",
mac.Substring(0, 2),
mac.Substring(2, 2),
mac.Substring(4, 2),
mac.Substring(6, 2),
mac.Substring(8, 2),
mac.Substring(10, 2));
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SessionApi.cs" company="Google">
//
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCoreInternal
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using GoogleARCore;
using UnityEngine;
#if UNITY_IOS && !UNITY_EDITOR
using AndroidImport = GoogleARCoreInternal.DllImportNoop;
using IOSImport = System.Runtime.InteropServices.DllImportAttribute;
#else
using AndroidImport = System.Runtime.InteropServices.DllImportAttribute;
using IOSImport = GoogleARCoreInternal.DllImportNoop;
#endif
internal class SessionApi
{
private NativeSession m_NativeSession;
public SessionApi(NativeSession nativeSession)
{
m_NativeSession = nativeSession;
}
public void ReportEngineType()
{
ExternApi.ArSession_reportEngineType(m_NativeSession.SessionHandle, "Unity", Application.unityVersion);
}
public bool SetConfiguration(ARCoreSessionConfig sessionConfig)
{
IntPtr configHandle = m_NativeSession.SessionConfigApi.Create();
m_NativeSession.SessionConfigApi.UpdateApiConfigWithArCoreSessionConfig(configHandle, sessionConfig);
bool ret = ExternApi.ArSession_configure(m_NativeSession.SessionHandle, configHandle) == 0;
m_NativeSession.SessionConfigApi.Destroy(configHandle);
return ret;
}
public void GetSupportedCameraConfigurations(IntPtr cameraConfigListHandle,
List<IntPtr> supportedCameraConfigHandles, List<CameraConfig> supportedCameraConfigs)
{
ExternApi.ArSession_getSupportedCameraConfigs(
m_NativeSession.SessionHandle, cameraConfigListHandle);
supportedCameraConfigHandles.Clear();
supportedCameraConfigs.Clear();
int listSize = m_NativeSession.CameraConfigListApi.GetSize(cameraConfigListHandle);
Debug.LogFormat("Found {0} camera configs.", listSize);
for (int i = 0; i < listSize; i++)
{
IntPtr cameraConfigHandle = m_NativeSession.CameraConfigApi.Create();
m_NativeSession.CameraConfigListApi.GetItemAt(cameraConfigListHandle, i, cameraConfigHandle);
Debug.LogFormat("Config {0} with handle {1}", i, cameraConfigHandle);
supportedCameraConfigHandles.Add(cameraConfigHandle);
supportedCameraConfigs.Add(_CreateCameraConfig(cameraConfigHandle));
}
}
public ApiArStatus SetCameraConfig(IntPtr cameraConfigHandle)
{
return ExternApi.ArSession_setCameraConfig(m_NativeSession.SessionHandle, cameraConfigHandle);
}
public CameraConfig GetCameraConfig()
{
IntPtr cameraConfigHandle = m_NativeSession.CameraConfigApi.Create();
ExternApi.ArSession_getCameraConfig(m_NativeSession.SessionHandle, cameraConfigHandle);
CameraConfig currentCameraConfig = _CreateCameraConfig(cameraConfigHandle);
m_NativeSession.CameraConfigApi.Destroy(cameraConfigHandle);
return currentCameraConfig;
}
public void GetAllTrackables(List<Trackable> trackables)
{
IntPtr listHandle = m_NativeSession.TrackableListApi.Create();
ExternApi.ArSession_getAllTrackables(m_NativeSession.SessionHandle, ApiTrackableType.BaseTrackable, listHandle);
trackables.Clear();
int count = m_NativeSession.TrackableListApi.GetCount(listHandle);
for (int i = 0; i < count; i++)
{
IntPtr trackableHandle = m_NativeSession.TrackableListApi.AcquireItem(listHandle, i);
Trackable trackable = m_NativeSession.TrackableFactory(trackableHandle);
if (trackable != null)
{
trackables.Add(trackable);
}
else
{
m_NativeSession.TrackableApi.Release(trackableHandle);
}
}
m_NativeSession.TrackableListApi.Destroy(listHandle);
}
public void SetDisplayGeometry(ScreenOrientation orientation, int width, int height)
{
const int androidRotation0 = 0;
const int androidRotation90 = 1;
const int androidRotation180 = 2;
const int androidRotation270 = 3;
int androidOrientation = 0;
switch (orientation)
{
case ScreenOrientation.LandscapeLeft:
androidOrientation = androidRotation90;
break;
case ScreenOrientation.LandscapeRight:
androidOrientation = androidRotation270;
break;
case ScreenOrientation.Portrait:
androidOrientation = androidRotation0;
break;
case ScreenOrientation.PortraitUpsideDown:
androidOrientation = androidRotation180;
break;
}
ExternApi.ArSession_setDisplayGeometry(m_NativeSession.SessionHandle, androidOrientation, width, height);
}
public Anchor CreateAnchor(Pose pose)
{
IntPtr poseHandle = m_NativeSession.PoseApi.Create(pose);
IntPtr anchorHandle = IntPtr.Zero;
ExternApi.ArSession_acquireNewAnchor(m_NativeSession.SessionHandle, poseHandle, ref anchorHandle);
var anchorResult = Anchor.Factory(m_NativeSession, anchorHandle);
m_NativeSession.PoseApi.Destroy(poseHandle);
return anchorResult;
}
public ApiArStatus CreateCloudAnchor(IntPtr platformAnchorHandle, out IntPtr cloudAnchorHandle)
{
cloudAnchorHandle = IntPtr.Zero;
var result = ExternApi.ArSession_hostAndAcquireNewCloudAnchor(m_NativeSession.SessionHandle,
platformAnchorHandle, ref cloudAnchorHandle);
return result;
}
public ApiArStatus ResolveCloudAnchor(String cloudAnchorId, out IntPtr cloudAnchorHandle)
{
cloudAnchorHandle = IntPtr.Zero;
return ExternApi.ArSession_resolveAndAcquireNewCloudAnchor(m_NativeSession.SessionHandle,
cloudAnchorId, ref cloudAnchorHandle);
}
private CameraConfig _CreateCameraConfig(IntPtr cameraConfigHandle)
{
int imageWidth = 0;
int imageHeight = 0;
int textureWidth = 0;
int textureHeight = 0;
m_NativeSession.CameraConfigApi.GetImageDimensions(cameraConfigHandle,
out imageWidth, out imageHeight);
m_NativeSession.CameraConfigApi.GetTextureDimensions(cameraConfigHandle,
out textureWidth, out textureHeight);
return new CameraConfig(new Vector2(imageWidth, imageHeight),
new Vector2(textureWidth, textureHeight));
}
private struct ExternApi
{
#pragma warning disable 626
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern int ArSession_configure(IntPtr sessionHandle, IntPtr config);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArSession_getSupportedCameraConfigs(IntPtr sessionHandle,
IntPtr cameraConfigListHandle);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern ApiArStatus ArSession_setCameraConfig(IntPtr sessionHandle, IntPtr cameraConfigHandle);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArSession_getCameraConfig(IntPtr sessionHandle, IntPtr cameraConfigHandle);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArSession_getAllTrackables(IntPtr sessionHandle, ApiTrackableType filterType,
IntPtr trackableList);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArSession_setDisplayGeometry(IntPtr sessionHandle, int rotation, int width,
int height);
[AndroidImport(ApiConstants.ARCoreNativeApi)]
public static extern int ArSession_acquireNewAnchor(IntPtr sessionHandle, IntPtr poseHandle,
ref IntPtr anchorHandle);
#pragma warning restore 626
[DllImport(ApiConstants.ARCoreNativeApi)]
public static extern void ArSession_reportEngineType(IntPtr sessionHandle, string engineType,
string engineVersion);
[DllImport(ApiConstants.ARCoreNativeApi)]
public static extern ApiArStatus ArSession_hostAndAcquireNewCloudAnchor(IntPtr sessionHandle,
IntPtr anchorHandle, ref IntPtr cloudAnchorHandle);
[DllImport(ApiConstants.ARCoreNativeApi)]
public static extern ApiArStatus ArSession_resolveAndAcquireNewCloudAnchor(
IntPtr sessionHandle, String cloudAnchorId, ref IntPtr cloudAnchorHandle);
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace EvoXP
{
/// <summary>
/// Summary description for TransactionEditor.
/// </summary>
public class TransactionEditor : System.Windows.Forms.Form
{
private GameClient _GC = null;
private LocalWaypoint _LW = null;
private EconomyClient _EC = null;
private bool bNew = false;
private bool bEdit = false;
private int _LWi = 0;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button buttonNew;
private System.Windows.Forms.Button buttonEdit;
private System.Windows.Forms.Button buttonDel;
private System.Windows.Forms.ListBox listBoxSells;
private System.Windows.Forms.ListBox listBoxBuys;
private System.Windows.Forms.ComboBox comboBoxCommodity;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.RadioButton radioButtonBUY;
private System.Windows.Forms.Button buttonSave;
private System.Windows.Forms.Button buttonTCancel;
private System.Windows.Forms.Button buttonQuit;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.RadioButton radioButtonLimit;
private System.Windows.Forms.TextBox textBoxQuatity;
private System.Windows.Forms.GroupBox groupBoxQuatity;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.RadioButton radioButtonAbs;
private System.Windows.Forms.RadioButton radioButtonPerc;
private System.Windows.Forms.GroupBox groupBox6;
private System.Windows.Forms.RadioButton radioButtonAllorNone;
private System.Windows.Forms.RadioButton radioButtonPartial;
private System.Windows.Forms.RadioButton radioButtonMarket;
private System.Windows.Forms.TextBox textBoxLimit;
private System.Windows.Forms.GroupBox groupBoxET;
private System.Windows.Forms.GroupBox groupBoxL;
private System.Timers.Timer timerUpdate;
private System.Windows.Forms.RadioButton radioButtonSELL;
public TransactionEditor(EconomyClient EC, LocalWaypoint LW, int lwi)
{
_LWi = lwi;
_GC = EC._gameclient;
_LW = LW;
_EC = EC;
_LW.bUpdate = true;
InitializeComponent();
Text = LW.route + ":" + LW.desc + "'s Transactions";
MakeInvalid();
UpdateLists();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.listBoxSells = new System.Windows.Forms.ListBox();
this.listBoxBuys = new System.Windows.Forms.ListBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.buttonNew = new System.Windows.Forms.Button();
this.buttonEdit = new System.Windows.Forms.Button();
this.buttonDel = new System.Windows.Forms.Button();
this.comboBoxCommodity = new System.Windows.Forms.ComboBox();
this.groupBoxET = new System.Windows.Forms.GroupBox();
this.groupBoxL = new System.Windows.Forms.GroupBox();
this.textBoxLimit = new System.Windows.Forms.TextBox();
this.groupBox6 = new System.Windows.Forms.GroupBox();
this.radioButtonPartial = new System.Windows.Forms.RadioButton();
this.radioButtonAllorNone = new System.Windows.Forms.RadioButton();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.radioButtonPerc = new System.Windows.Forms.RadioButton();
this.radioButtonAbs = new System.Windows.Forms.RadioButton();
this.groupBoxQuatity = new System.Windows.Forms.GroupBox();
this.textBoxQuatity = new System.Windows.Forms.TextBox();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.radioButtonLimit = new System.Windows.Forms.RadioButton();
this.radioButtonMarket = new System.Windows.Forms.RadioButton();
this.buttonTCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.radioButtonSELL = new System.Windows.Forms.RadioButton();
this.radioButtonBUY = new System.Windows.Forms.RadioButton();
this.buttonQuit = new System.Windows.Forms.Button();
this.timerUpdate = new System.Timers.Timer();
this.groupBoxET.SuspendLayout();
this.groupBoxL.SuspendLayout();
this.groupBox6.SuspendLayout();
this.groupBox5.SuspendLayout();
this.groupBoxQuatity.SuspendLayout();
this.groupBox4.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.timerUpdate)).BeginInit();
this.SuspendLayout();
//
// listBoxSells
//
this.listBoxSells.Location = new System.Drawing.Point(8, 24);
this.listBoxSells.Name = "listBoxSells";
this.listBoxSells.Size = new System.Drawing.Size(192, 134);
this.listBoxSells.TabIndex = 0;
this.listBoxSells.SelectedIndexChanged += new System.EventHandler(this.listBoxSells_SelectedIndexChanged);
//
// listBoxBuys
//
this.listBoxBuys.Location = new System.Drawing.Point(208, 24);
this.listBoxBuys.Name = "listBoxBuys";
this.listBoxBuys.Size = new System.Drawing.Size(192, 134);
this.listBoxBuys.TabIndex = 1;
this.listBoxBuys.SelectedIndexChanged += new System.EventHandler(this.listBoxBuys_SelectedIndexChanged);
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(112, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Sells";
//
// label2
//
this.label2.Location = new System.Drawing.Point(208, 8);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(112, 16);
this.label2.TabIndex = 3;
this.label2.Text = "Buys";
//
// buttonNew
//
this.buttonNew.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.buttonNew.Location = new System.Drawing.Point(152, 168);
this.buttonNew.Name = "buttonNew";
this.buttonNew.Size = new System.Drawing.Size(56, 24);
this.buttonNew.TabIndex = 4;
this.buttonNew.Text = "New";
this.buttonNew.Click += new System.EventHandler(this.buttonNew_Click);
//
// buttonEdit
//
this.buttonEdit.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.buttonEdit.Location = new System.Drawing.Point(216, 168);
this.buttonEdit.Name = "buttonEdit";
this.buttonEdit.Size = new System.Drawing.Size(56, 24);
this.buttonEdit.TabIndex = 6;
this.buttonEdit.Text = "Edit";
this.buttonEdit.Click += new System.EventHandler(this.buttonEdit_Click);
//
// buttonDel
//
this.buttonDel.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.buttonDel.Location = new System.Drawing.Point(280, 168);
this.buttonDel.Name = "buttonDel";
this.buttonDel.Size = new System.Drawing.Size(56, 24);
this.buttonDel.TabIndex = 7;
this.buttonDel.Text = "Del";
this.buttonDel.Click += new System.EventHandler(this.buttonDel_Click);
//
// comboBoxCommodity
//
this.comboBoxCommodity.Location = new System.Drawing.Point(8, 16);
this.comboBoxCommodity.Name = "comboBoxCommodity";
this.comboBoxCommodity.Size = new System.Drawing.Size(112, 21);
this.comboBoxCommodity.TabIndex = 8;
//
// groupBoxET
//
this.groupBoxET.Controls.AddRange(new System.Windows.Forms.Control[] {
this.groupBoxL,
this.groupBox6,
this.groupBox5,
this.groupBoxQuatity,
this.groupBox4,
this.buttonTCancel,
this.buttonSave,
this.groupBox3,
this.groupBox2});
this.groupBoxET.Location = new System.Drawing.Point(8, 200);
this.groupBoxET.Name = "groupBoxET";
this.groupBoxET.Size = new System.Drawing.Size(392, 144);
this.groupBoxET.TabIndex = 9;
this.groupBoxET.TabStop = false;
this.groupBoxET.Text = "ET";
//
// groupBoxL
//
this.groupBoxL.Controls.AddRange(new System.Windows.Forms.Control[] {
this.textBoxLimit});
this.groupBoxL.Location = new System.Drawing.Point(248, 16);
this.groupBoxL.Name = "groupBoxL";
this.groupBoxL.Size = new System.Drawing.Size(80, 48);
this.groupBoxL.TabIndex = 18;
this.groupBoxL.TabStop = false;
this.groupBoxL.Text = "Limit";
//
// textBoxLimit
//
this.textBoxLimit.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBoxLimit.Location = new System.Drawing.Point(8, 16);
this.textBoxLimit.Name = "textBoxLimit";
this.textBoxLimit.Size = new System.Drawing.Size(64, 20);
this.textBoxLimit.TabIndex = 0;
this.textBoxLimit.Text = "0";
this.textBoxLimit.TextChanged += new System.EventHandler(this.textBoxLimit_TextChanged);
//
// groupBox6
//
this.groupBox6.Controls.AddRange(new System.Windows.Forms.Control[] {
this.radioButtonPartial,
this.radioButtonAllorNone});
this.groupBox6.Location = new System.Drawing.Point(280, 72);
this.groupBox6.Name = "groupBox6";
this.groupBox6.Size = new System.Drawing.Size(104, 64);
this.groupBox6.TabIndex = 17;
this.groupBox6.TabStop = false;
this.groupBox6.Text = "Sell Style";
//
// radioButtonPartial
//
this.radioButtonPartial.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.radioButtonPartial.Location = new System.Drawing.Point(8, 40);
this.radioButtonPartial.Name = "radioButtonPartial";
this.radioButtonPartial.Size = new System.Drawing.Size(88, 16);
this.radioButtonPartial.TabIndex = 1;
this.radioButtonPartial.Text = "Partial";
//
// radioButtonAllorNone
//
this.radioButtonAllorNone.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.radioButtonAllorNone.Location = new System.Drawing.Point(8, 16);
this.radioButtonAllorNone.Name = "radioButtonAllorNone";
this.radioButtonAllorNone.Size = new System.Drawing.Size(88, 16);
this.radioButtonAllorNone.TabIndex = 0;
this.radioButtonAllorNone.Text = "All or None";
//
// groupBox5
//
this.groupBox5.Controls.AddRange(new System.Windows.Forms.Control[] {
this.radioButtonPerc,
this.radioButtonAbs});
this.groupBox5.Location = new System.Drawing.Point(176, 72);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(96, 64);
this.groupBox5.TabIndex = 16;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Cargo Style";
//
// radioButtonPerc
//
this.radioButtonPerc.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.radioButtonPerc.Location = new System.Drawing.Point(8, 40);
this.radioButtonPerc.Name = "radioButtonPerc";
this.radioButtonPerc.Size = new System.Drawing.Size(80, 16);
this.radioButtonPerc.TabIndex = 1;
this.radioButtonPerc.Text = "Percentage";
this.radioButtonPerc.CheckedChanged += new System.EventHandler(this.radioButtonPerc_CheckedChanged);
//
// radioButtonAbs
//
this.radioButtonAbs.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.radioButtonAbs.Location = new System.Drawing.Point(8, 16);
this.radioButtonAbs.Name = "radioButtonAbs";
this.radioButtonAbs.Size = new System.Drawing.Size(80, 16);
this.radioButtonAbs.TabIndex = 0;
this.radioButtonAbs.Text = "Absolute";
this.radioButtonAbs.CheckedChanged += new System.EventHandler(this.radioButtonAbs_CheckedChanged);
//
// groupBoxQuatity
//
this.groupBoxQuatity.Controls.AddRange(new System.Windows.Forms.Control[] {
this.textBoxQuatity});
this.groupBoxQuatity.Location = new System.Drawing.Point(144, 16);
this.groupBoxQuatity.Name = "groupBoxQuatity";
this.groupBoxQuatity.Size = new System.Drawing.Size(96, 48);
this.groupBoxQuatity.TabIndex = 15;
this.groupBoxQuatity.TabStop = false;
this.groupBoxQuatity.Text = "Quatity";
//
// textBoxQuatity
//
this.textBoxQuatity.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBoxQuatity.Location = new System.Drawing.Point(8, 16);
this.textBoxQuatity.Name = "textBoxQuatity";
this.textBoxQuatity.Size = new System.Drawing.Size(80, 20);
this.textBoxQuatity.TabIndex = 14;
this.textBoxQuatity.Text = "0";
this.textBoxQuatity.TextChanged += new System.EventHandler(this.textBoxQuatity_TextChanged);
//
// groupBox4
//
this.groupBox4.Controls.AddRange(new System.Windows.Forms.Control[] {
this.radioButtonLimit,
this.radioButtonMarket});
this.groupBox4.Location = new System.Drawing.Point(80, 72);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(88, 64);
this.groupBox4.TabIndex = 13;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "Behavior";
//
// radioButtonLimit
//
this.radioButtonLimit.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.radioButtonLimit.Location = new System.Drawing.Point(16, 40);
this.radioButtonLimit.Name = "radioButtonLimit";
this.radioButtonLimit.Size = new System.Drawing.Size(56, 16);
this.radioButtonLimit.TabIndex = 1;
this.radioButtonLimit.Text = "Limit";
this.radioButtonLimit.CheckedChanged += new System.EventHandler(this.radioButtonLimit_CheckedChanged);
//
// radioButtonMarket
//
this.radioButtonMarket.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.radioButtonMarket.Location = new System.Drawing.Point(16, 16);
this.radioButtonMarket.Name = "radioButtonMarket";
this.radioButtonMarket.Size = new System.Drawing.Size(64, 16);
this.radioButtonMarket.TabIndex = 0;
this.radioButtonMarket.Text = "Market";
this.radioButtonMarket.CheckedChanged += new System.EventHandler(this.radioButtonMarket_CheckedChanged);
//
// buttonTCancel
//
this.buttonTCancel.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.buttonTCancel.Location = new System.Drawing.Point(336, 48);
this.buttonTCancel.Name = "buttonTCancel";
this.buttonTCancel.Size = new System.Drawing.Size(48, 24);
this.buttonTCancel.TabIndex = 12;
this.buttonTCancel.Text = "Cancel";
this.buttonTCancel.Click += new System.EventHandler(this.buttonTCancel_Click);
//
// buttonSave
//
this.buttonSave.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.buttonSave.Location = new System.Drawing.Point(336, 16);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(48, 24);
this.buttonSave.TabIndex = 11;
this.buttonSave.Text = "Save";
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// groupBox3
//
this.groupBox3.Controls.AddRange(new System.Windows.Forms.Control[] {
this.comboBoxCommodity});
this.groupBox3.Location = new System.Drawing.Point(8, 16);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(128, 48);
this.groupBox3.TabIndex = 10;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Commodities";
//
// groupBox2
//
this.groupBox2.Controls.AddRange(new System.Windows.Forms.Control[] {
this.radioButtonSELL,
this.radioButtonBUY});
this.groupBox2.Location = new System.Drawing.Point(8, 72);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(64, 64);
this.groupBox2.TabIndex = 9;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Type";
//
// radioButtonSELL
//
this.radioButtonSELL.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.radioButtonSELL.Location = new System.Drawing.Point(8, 40);
this.radioButtonSELL.Name = "radioButtonSELL";
this.radioButtonSELL.Size = new System.Drawing.Size(48, 16);
this.radioButtonSELL.TabIndex = 1;
this.radioButtonSELL.Text = "Sell";
this.radioButtonSELL.CheckedChanged += new System.EventHandler(this.radioButtonSELL_CheckedChanged);
//
// radioButtonBUY
//
this.radioButtonBUY.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.radioButtonBUY.Location = new System.Drawing.Point(8, 16);
this.radioButtonBUY.Name = "radioButtonBUY";
this.radioButtonBUY.Size = new System.Drawing.Size(48, 16);
this.radioButtonBUY.TabIndex = 0;
this.radioButtonBUY.Text = "Buy";
this.radioButtonBUY.CheckedChanged += new System.EventHandler(this.radioButtonBUY_CheckedChanged);
//
// buttonQuit
//
this.buttonQuit.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.buttonQuit.Location = new System.Drawing.Point(344, 168);
this.buttonQuit.Name = "buttonQuit";
this.buttonQuit.Size = new System.Drawing.Size(56, 24);
this.buttonQuit.TabIndex = 13;
this.buttonQuit.Text = "Quit";
this.buttonQuit.Click += new System.EventHandler(this.buttonQuit_Click);
//
// timerUpdate
//
this.timerUpdate.Enabled = true;
this.timerUpdate.SynchronizingObject = this;
this.timerUpdate.Elapsed += new System.Timers.ElapsedEventHandler(this.timerUpdate_Elapsed);
//
// TransactionEditor
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(410, 354);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.buttonQuit,
this.groupBoxET,
this.buttonEdit,
this.buttonNew,
this.label2,
this.label1,
this.listBoxBuys,
this.listBoxSells,
this.buttonDel});
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "TransactionEditor";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Transactions";
this.groupBoxET.ResumeLayout(false);
this.groupBoxL.ResumeLayout(false);
this.groupBox6.ResumeLayout(false);
this.groupBox5.ResumeLayout(false);
this.groupBoxQuatity.ResumeLayout(false);
this.groupBox4.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.timerUpdate)).EndInit();
this.ResumeLayout(false);
}
#endregion
private int SelB = -1;
private int SelS = -1;
private void MakeInvalid()
{
this.Height = 224;
bNew = false;
bEdit = false;
buttonEdit.Enabled = false;
buttonDel.Enabled = false;
SelB = -1;
SelS = -1;
}
private void MakeValid()
{
if(SelB * SelS <= 0)
{
buttonEdit.Enabled = true;
buttonDel.Enabled = true;
}
}
private void listBoxBuys_SelectedIndexChanged(object sender, System.EventArgs e)
{ MakeInvalid();
listBoxSells.SelectedIndex = -1;
SelB = listBoxBuys.SelectedIndex;
MakeValid();
}
private void listBoxSells_SelectedIndexChanged(object sender, System.EventArgs e)
{
MakeInvalid();
listBoxBuys.SelectedIndex = -1;
SelS = listBoxSells.SelectedIndex;
MakeValid();
}
void ShowEditor()
{
this.Height = 376;
if(bNew)
{
radioButtonMarket.Checked = true;
radioButtonAbs.Checked = true;
radioButtonPartial.Checked = true;
radioButtonBUY.Checked = true;
comboBoxCommodity.Text = "";
comboBoxCommodity.Enabled = true;
radioButtonBUY.Enabled = true;
UpdateComm();
UpdateCargoStyle();
UpdateLimit();
}
if(bEdit)
{
string val;
if(SelB >= 0){ radioButtonBUY.Checked = true; val = listBoxBuys.Items[SelB] as string; }
if(SelS >= 0){ radioButtonSELL.Checked = true; val = listBoxSells.Items[SelS] as string; }
comboBoxCommodity.Enabled = false;
radioButtonBUY.Enabled = false;
radioButtonSELL.Enabled = false;
// set bools
UpdateComm();
UpdateCargoStyle();
UpdateLimit();
// set values
}
}
public void UpdateComm()
{
int tSI = comboBoxCommodity.SelectedIndex;
string tSIs = null;
if(tSI >= 0) tSIs = comboBoxCommodity.SelectedItem as string;
int rJ = 0;
bool didIT = false;
comboBoxCommodity.Items.Clear();
if(radioButtonBUY.Checked == true)
{
groupBoxET.Text = "Transaction: BUY";
for(int j = 0; j < _EC._TradeDepots._comm_names.Length ; j++)
{
bool add = true;
for(int i = 0; i < listBoxBuys.Items.Count && add; i++)
{
string val = listBoxBuys.Items[i] as string;
if(val.IndexOf(_EC._TradeDepots._comm_names[j]) == 0)
{
add = false;
}
else
{
didIT = true;
if(val==tSIs)
tSI = rJ;
}
}
if(add)
{
comboBoxCommodity.Items.Add(_EC._TradeDepots._comm_names[j]);
rJ++;
}
}
}
else
{
groupBoxET.Text = "Transaction: SELL";
for(int j = 0; j < _EC._TradeDepots._comm_names.Length ; j++)
{
bool add = true;
for(int i = 0; i < listBoxSells.Items.Count; i++)
{
string val = listBoxSells.Items[i] as string;
if(val.IndexOf(_EC._TradeDepots._comm_names[j]) == 0)
{
add = false;
}
else
{
didIT = true;
if(val==tSIs)
tSI = rJ;
}
}
if(add)
{
comboBoxCommodity.Items.Add(_EC._TradeDepots._comm_names[j]);
rJ++;
}
}
}
if(didIT && tSI < comboBoxCommodity.Items.Count ) comboBoxCommodity.SelectedIndex = tSI;
}
public void UpdateCargoStyle()
{
if(radioButtonAbs.Checked == true)
{
groupBoxQuatity.Text = "Quantity";
textBoxQuatity.Text = "100";
}
else
{
groupBoxQuatity.Text = "Percentage";
textBoxQuatity.Text = "100";
}
}
public void UpdateLimit()
{
groupBoxL.Enabled = !radioButtonMarket.Checked;
}
private void buttonNew_Click(object sender, System.EventArgs e)
{
bNew = true; ShowEditor();
}
private void buttonEdit_Click(object sender, System.EventArgs e)
{
bEdit = true; ShowEditor();
}
private void buttonQuit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void buttonTCancel_Click(object sender, System.EventArgs e)
{
MakeInvalid();
}
private void textBoxQuatity_TextChanged(object sender, System.EventArgs e)
{
string nText = "";
for(int i = 0; i < textBoxQuatity.Text.Length; i++)
{
if(textBoxQuatity.Text[i]>='0' && textBoxQuatity.Text[i]<='9')
{
nText+=textBoxQuatity.Text[i];
}
}
if(textBoxQuatity.Text!=nText) textBoxQuatity.Text = nText;
}
private void textBoxLimit_TextChanged(object sender, System.EventArgs e)
{
string nText = "";
for(int i = 0; i < textBoxLimit.Text.Length; i++)
{
if(textBoxLimit.Text[i]>='0' && textBoxLimit.Text[i]<='9')
{
nText+=textBoxLimit.Text[i];
}
}
if(textBoxLimit.Text!=nText) textBoxLimit.Text = nText;
}
private void radioButtonPerc_CheckedChanged(object sender, System.EventArgs e)
{ UpdateCargoStyle(); }
private void radioButtonAbs_CheckedChanged(object sender, System.EventArgs e)
{ UpdateCargoStyle(); }
private void radioButtonLimit_CheckedChanged(object sender, System.EventArgs e)
{ UpdateLimit(); }
private void radioButtonMarket_CheckedChanged(object sender, System.EventArgs e)
{ UpdateLimit();}
private void radioButtonBUY_CheckedChanged(object sender, System.EventArgs e)
{UpdateComm();}
private void radioButtonSELL_CheckedChanged(object sender, System.EventArgs e)
{UpdateComm();}
private void timerUpdate_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if(!bNew && !bEdit)
{ UpdateLists(); }
}
public void UpdateLists()
{
if(_LW.bUpdate == true)
{
_LW.bUpdate = false;
int SelBefore = listBoxBuys.SelectedIndex;
listBoxBuys.Items.Clear();
for(int i=0;i<_LW.trans_Buys.Count;i++)
{
LocalTransaction LT = _LW.trans_Buys[i] as LocalTransaction;
listBoxBuys.Items.Add(LT.getAsString());
}
if(SelBefore >= _LW.trans_Buys.Count - 1)
SelBefore = _LW.trans_Buys.Count - 1;
if(SelBefore >= 0) listBoxBuys.SelectedIndex = SelBefore;
SelBefore = listBoxSells.SelectedIndex;
listBoxSells.Items.Clear();
for(int i=0;i<_LW.trans_Sells.Count;i++)
{
LocalTransaction LT = _LW.trans_Sells[i] as LocalTransaction;
listBoxSells.Items.Add(LT.getAsString());
}
if(SelBefore >= _LW.trans_Sells.Count - 1)
SelBefore = _LW.trans_Sells.Count - 1;
if(SelBefore >= 0) listBoxSells.SelectedIndex = SelBefore;
}
}
private void buttonSave_Click(object sender, System.EventArgs e)
{
LocalTransaction LT = new LocalTransaction();
LT.commodity = comboBoxCommodity.Text;
LT.isBuy = radioButtonBUY.Checked;
LT.isMarket = radioButtonMarket.Checked;
LT.isAbs = radioButtonAbs.Checked;
LT.isAll = radioButtonAllorNone.Checked;
LT.limit = Int32.Parse(textBoxLimit.Text);
LT.quantity = Int32.Parse(textBoxQuatity.Text);
if(bNew)
{
string bA, bB, bC, bD;
bA = LT.isBuy ? "T" : "F";
bB = LT.isMarket ? "T" : "F";
bC = LT.isAbs ? "T" : "F";
bD = LT.isAll ? "T" : "F";
string msg = "WT_ADD:" + _LW.route + ":" + _LWi + ":" + LT.commodity + ":" + LT.quantity + ":" + bA + ":" + bB + ":" + bC + ":" + bD + ":" + LT.limit + ":<end>";
_GC.WriteString(msg);
}
if(bEdit)
{
MessageBox.Show("working on it");
}
buttonTCancel_Click(sender, e);
}
private void buttonDel_Click(object sender, System.EventArgs e)
{
if(SelB >= 0)
{
string msg = "WT_DEL:" + _LW.route + ":" + _LWi + ":" + SelB + ":T:<end>";
_GC.WriteString(msg);
}
if(SelS >= 0)
{
string msg = "WT_DEL:" + _LW.route + ":" + _LWi + ":" + SelS + ":F:<end>";
_GC.WriteString(msg);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementSingle0()
{
var test = new VectorGetAndWithElement__GetAndWithElementSingle0();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementSingle0
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector128<Single> value = Vector128.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
Single result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Single insertedValue = TestLibrary.Generator.GetSingle();
try
{
Vector128<Single> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector128<Single> value = Vector128.Create(values[0], values[1], values[2], values[3]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector128)
.GetMethod(nameof(Vector128.GetElement))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((Single)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Single insertedValue = TestLibrary.Generator.GetSingle();
try
{
object result2 = typeof(Vector128)
.GetMethod(nameof(Vector128.WithElement))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector128<Single>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(Single result, Single[] values, [CallerMemberName] string method = "")
{
if (result != values[0])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector128<Single.GetElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector128<Single> result, Single[] values, Single insertedValue, [CallerMemberName] string method = "")
{
Single[] resultElements = new Single[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(Single[] result, Single[] values, Single insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 0) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[0] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using AutoMapper.UnitTests;
using Should;
using Xunit;
namespace AutoMapper.Tests
{
public class EnumMappingFixture
{
public EnumMappingFixture()
{
Cleanup();
}
public void Cleanup()
{
}
[Fact]
public void ShouldMapSharedEnum()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDto>());
var order = new Order
{
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<Order, OrderDto>(order);
dto.Status.ShouldEqual(Status.InProgress);
}
[Fact]
public void ShouldMapToUnderlyingType() {
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoInt>());
var order = new Order {
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<Order, OrderDtoInt>(order);
dto.Status.ShouldEqual(1);
}
[Fact]
public void ShouldMapToStringType() {
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoString>());
var order = new Order {
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<Order, OrderDtoString>(order);
dto.Status.ShouldEqual("InProgress");
}
[Fact]
public void ShouldMapFromUnderlyingType() {
var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderDtoInt, Order>());
var order = new OrderDtoInt {
Status = 1
};
var mapper = config.CreateMapper();
var dto = mapper.Map<OrderDtoInt, Order>(order);
dto.Status.ShouldEqual(Status.InProgress);
}
[Fact]
public void ShouldMapFromStringType() {
var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderDtoString, Order>());
var order = new OrderDtoString {
Status = "InProgress"
};
var mapper = config.CreateMapper();
var dto = mapper.Map<OrderDtoString, Order>(order);
dto.Status.ShouldEqual(Status.InProgress);
}
[Fact]
public void ShouldMapEnumByMatchingNames()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>());
var order = new Order
{
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);
dto.Status.ShouldEqual(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapEnumByMatchingValues()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>());
var order = new Order
{
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);
dto.Status.ShouldEqual(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapSharedNullableEnum()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithNullableStatus>());
var order = new OrderWithNullableStatus {
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<OrderWithNullableStatus, OrderDtoWithNullableStatus>(order);
dto.Status.ShouldEqual(Status.InProgress);
}
[Fact]
public void ShouldMapNullableEnumByMatchingValues()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>());
var order = new OrderWithNullableStatus {
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var dto = mapper.Map<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(order);
dto.Status.ShouldEqual(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapNullableEnumToNullWhenSourceEnumIsNullAndDestinationWasNotNull()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AllowNullDestinationValues = true;
cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>();
});
var dto = new OrderDtoWithOwnNullableStatus()
{
Status = StatusForDto.Complete
};
var order = new OrderWithNullableStatus
{
Status = null
};
var mapper = config.CreateMapper();
mapper.Map(order, dto);
dto.Status.ShouldBeNull();
}
[Fact]
public void ShouldMapNullableEnumToNullWhenSourceEnumIsNull()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>());
var order = new OrderWithNullableStatus {
Status = null
};
var mapper = config.CreateMapper();
var dto = mapper.Map<OrderWithNullableStatus, OrderDtoWithOwnNullableStatus>(order);
dto.Status.ShouldBeNull();
}
[Fact]
public void ShouldMapEnumUsingCustomResolver()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>()
.ForMember(dto => dto.Status, options => options
.ResolveUsing<DtoStatusValueResolver>()));
var order = new Order
{
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var mappedDto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);
mappedDto.Status.ShouldEqual(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapEnumUsingGenericEnumResolver()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>()
.ForMember(dto => dto.Status, options => options
.ResolveUsing<EnumValueResolver<Status, StatusForDto>>()
.FromMember(m => m.Status)));
var order = new Order
{
Status = Status.InProgress
};
var mapper = config.CreateMapper();
var mappedDto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);
mappedDto.Status.ShouldEqual(StatusForDto.InProgress);
}
[Fact]
public void ShouldMapEnumWithInvalidValue()
{
var config = new MapperConfiguration(cfg => cfg.CreateMap<Order, OrderDtoWithOwnStatus>());
var order = new Order
{
Status = 0
};
var mapper = config.CreateMapper();
var dto = mapper.Map<Order, OrderDtoWithOwnStatus>(order);
var expected = (StatusForDto)0;
dto.Status.ShouldEqual(expected);
}
public enum Status
{
InProgress = 1,
Complete = 2
}
public enum StatusForDto
{
InProgress = 1,
Complete = 2
}
public class Order
{
public Status Status { get; set; }
}
public class OrderDto
{
public Status Status { get; set; }
}
public class OrderDtoInt {
public int Status { get; set; }
}
public class OrderDtoString {
public string Status { get; set; }
}
public class OrderDtoWithOwnStatus
{
public StatusForDto Status { get; set; }
}
public class OrderWithNullableStatus
{
public Status? Status { get; set; }
}
public class OrderDtoWithNullableStatus
{
public Status? Status { get; set; }
}
public class OrderDtoWithOwnNullableStatus
{
public StatusForDto? Status { get; set; }
}
public class DtoStatusValueResolver : IValueResolver
{
public ResolutionResult Resolve(ResolutionResult source)
{
return source.New(((Order)source.Value).Status);
}
}
public class EnumValueResolver<TInputEnum, TOutputEnum> : IValueResolver
{
public ResolutionResult Resolve(ResolutionResult source)
{
return source.New(((TOutputEnum)Enum.Parse(typeof(TOutputEnum), Enum.GetName(typeof(TInputEnum), source.Value), false)));
}
}
}
public class When_mapping_from_a_null_object_with_an_enum : AutoMapperSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.AllowNullDestinationValues = false;
cfg.CreateMap<SourceClass, DestinationClass>();
});
public enum EnumValues
{
One, Two, Three
}
public class DestinationClass
{
public EnumValues Values { get; set; }
}
public class SourceClass
{
public EnumValues Values { get; set; }
}
[Fact]
public void Should_set_the_target_enum_to_the_default_value()
{
SourceClass sourceClass = null;
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values.ShouldEqual(default(EnumValues));
}
}
public class When_mapping_from_a_null_object_with_an_enum_on_a_nullable_enum : AutoMapperSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.AllowNullDestinationValues = false;
cfg.CreateMap<SourceClass, DestinationClass>();
});
public enum EnumValues
{
One, Two, Three
}
public class DestinationClass
{
public EnumValues? Values { get; set; }
}
public class SourceClass
{
public EnumValues Values { get; set; }
}
[Fact]
public void Should_set_the_target_enum_to_null()
{
SourceClass sourceClass = null;
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values.ShouldEqual(null);
}
}
public class When_mapping_from_a_null_object_with_a_nullable_enum : AutoMapperSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.AllowNullDestinationValues = false;
cfg.CreateMap<SourceClass, DestinationClass>();
});
public enum EnumValues
{
One, Two, Three
}
public class DestinationClass
{
public EnumValues Values { get; set; }
}
public class SourceClass
{
public EnumValues? Values { get; set; }
}
[Fact]
public void Should_set_the_target_enum_to_the_default_value()
{
SourceClass sourceClass = null;
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values.ShouldEqual(default(EnumValues));
}
}
public class When_mapping_from_a_null_object_with_a_nullable_enum_as_string : AutoMapperSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<SourceClass, DestinationClass>();
});
public enum EnumValues
{
One, Two, Three
}
public class DestinationClass
{
public EnumValues Values1 { get; set; }
public EnumValues? Values2 { get; set; }
public EnumValues Values3 { get; set; }
}
public class SourceClass
{
public string Values1 { get; set; }
public string Values2 { get; set; }
public string Values3 { get; set; }
}
[Fact]
public void Should_set_the_target_enum_to_the_default_value()
{
var sourceClass = new SourceClass();
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values1.ShouldEqual(default(EnumValues));
}
[Fact]
public void Should_set_the_target_nullable_to_null()
{
var sourceClass = new SourceClass();
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values2.ShouldBeNull();
}
[Fact]
public void Should_set_the_target_empty_to_null()
{
var sourceClass = new SourceClass
{
Values3 = ""
};
var dest = Mapper.Map<SourceClass, DestinationClass>(sourceClass);
dest.Values3.ShouldEqual(default(EnumValues));
}
}
public class When_mapping_a_flags_enum : NonValidatingSpecBase
{
private DestinationFlags _result;
[Flags]
private enum SourceFlags
{
None = 0,
One = 1,
Two = 2,
Four = 4,
Eight = 8
}
[Flags]
private enum DestinationFlags
{
None = 0,
One = 1,
Two = 2,
Four = 4,
Eight = 8
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { });
protected override void Because_of()
{
_result = Mapper.Map<SourceFlags, DestinationFlags>(SourceFlags.One | SourceFlags.Four | SourceFlags.Eight);
}
[Fact]
public void Should_include_all_source_enum_values()
{
_result.ShouldEqual(DestinationFlags.One | DestinationFlags.Four | DestinationFlags.Eight);
}
}
}
| |
//
// Mono.Google.Picasa.PicasaAlbum.cs:
//
// Authors:
// Gonzalo Paniagua Javier ([email protected])
// Stephane Delcroix ([email protected])
//
// (C) Copyright 2006 Novell, Inc. (http://www.novell.com)
// (C) Copyright 2007 S. Delcroix
//
// 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.Text;
using System.Xml;
namespace Mono.Google.Picasa {
public class PicasaAlbum {
GoogleConnection conn;
string user;
string title;
string description;
string id;
string link;
string authkey = null;
AlbumAccess access = AlbumAccess.Public;
int num_photos = -1;
int num_photos_remaining = -1;
long bytes_used = -1;
private PicasaAlbum (GoogleConnection conn)
{
if (conn == null)
throw new ArgumentNullException ("conn");
this.conn = conn;
}
public PicasaAlbum (GoogleConnection conn, string aid) : this (conn)
{
if (conn.User == null)
throw new ArgumentException ("Need authentication before being used.", "conn");
if (aid == null || aid == String.Empty)
throw new ArgumentNullException ("aid");
this.user = conn.User;
this.id = aid;
string received = conn.DownloadString (GDataApi.GetAlbumEntryById (conn.User, aid));
XmlDocument doc = new XmlDocument ();
doc.LoadXml (received);
XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
XmlUtil.AddDefaultNamespaces (nsmgr);
XmlNode entry = doc.SelectSingleNode ("atom:entry", nsmgr);
ParseAlbum (entry, nsmgr);
}
public PicasaAlbum (GoogleConnection conn, string user, string aid, string authkey) : this (conn)
{
if (user == null || user == String.Empty)
throw new ArgumentNullException ("user");
if (aid == null || aid == String.Empty)
throw new ArgumentNullException ("aid");
this.user = user;
this.id = aid;
this.authkey = authkey;
string download_link = GDataApi.GetAlbumEntryById (user, id);
if (authkey != null && authkey != "")
download_link += "&authkey=" + authkey;
string received = conn.DownloadString (download_link);
XmlDocument doc = new XmlDocument ();
doc.LoadXml (received);
XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
XmlUtil.AddDefaultNamespaces (nsmgr);
XmlNode entry = doc.SelectSingleNode ("atom:entry", nsmgr);
ParseAlbum (entry, nsmgr);
}
internal PicasaAlbum (GoogleConnection conn, string user, XmlNode nodeitem, XmlNamespaceManager nsmgr) : this (conn)
{
this.user = user ?? conn.User;
ParseAlbum (nodeitem, nsmgr);
}
private void ParseAlbum (XmlNode nodeitem, XmlNamespaceManager nsmgr)
{
title = nodeitem.SelectSingleNode ("atom:title", nsmgr).InnerText;
description = nodeitem.SelectSingleNode ("media:group/media:description", nsmgr).InnerText;
XmlNode node = nodeitem.SelectSingleNode ("gphoto:id", nsmgr);
if (node != null)
id = node.InnerText;
foreach (XmlNode xlink in nodeitem.SelectNodes ("atom:link", nsmgr)) {
if (xlink.Attributes.GetNamedItem ("rel").Value == "alternate") {
link = xlink.Attributes.GetNamedItem ("href").Value;
break;
}
}
node = nodeitem.SelectSingleNode ("gphoto:access", nsmgr);
if (node != null) {
string acc = node.InnerText;
access = (acc == "public") ? AlbumAccess.Public : AlbumAccess.Private;
}
node = nodeitem.SelectSingleNode ("gphoto:numphotos", nsmgr);
if (node != null)
num_photos = (int) UInt32.Parse (node.InnerText);
node = nodeitem.SelectSingleNode ("gphoto:numphotosremaining", nsmgr);
if (node != null)
num_photos_remaining = (int) UInt32.Parse (node.InnerText);
node = nodeitem.SelectSingleNode ("gphoto:bytesused", nsmgr);
if (node != null)
bytes_used = (long) UInt64.Parse (node.InnerText);
}
public PicasaPictureCollection GetPictures ()
{
string download_link = GDataApi.GetAlbumFeedById (user, id);
if (authkey != null && authkey != "")
download_link += "&authkey=" + authkey;
string received = conn.DownloadString (download_link);
XmlDocument doc = new XmlDocument ();
doc.LoadXml (received);
XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
XmlUtil.AddDefaultNamespaces (nsmgr);
XmlNode feed = doc.SelectSingleNode ("atom:feed", nsmgr);
PicasaPictureCollection coll = new PicasaPictureCollection ();
foreach (XmlNode item in feed.SelectNodes ("atom:entry", nsmgr)) {
coll.Add (new PicasaPicture (conn, this, item, nsmgr));
}
coll.SetReadOnly ();
return coll;
}
/* from http://code.google.com/apis/picasaweb/gdata.html#Add_Photo
<entry xmlns='http://www.w3.org/2005/Atom'>
<title>darcy-beach.jpg</title>
<summary>Darcy on the beach</summary>
<category scheme="http://schemas.google.com/g/2005#kind"
term="http://schemas.google.com/photos/2007#photo"/>
</entry>
*/
static string GetXmlForUpload (string title, string description)
{
XmlUtil xml = new XmlUtil ();
xml.WriteElementString ("title", title);
xml.WriteElementString ("summary", description);
xml.WriteElementStringWithAttributes ("category", null,
"scheme", "http://schemas.google.com/g/2005#kind",
"term", "http://schemas.google.com/photos/2007#photo");
return xml.GetDocumentString ();
}
public PicasaPicture UploadPicture (string title, Stream input)
{
return UploadPicture (title, null, input);
}
public PicasaPicture UploadPicture (string title, string description, Stream input)
{
return UploadPicture (title, description, "image/jpeg", input);
}
public PicasaPicture UploadPicture (string title, string description, string mime_type, Stream input)
{
if (title == null)
throw new ArgumentNullException ("title");
if (input == null)
throw new ArgumentNullException ("input");
if (!input.CanRead)
throw new ArgumentException ("Cannot read from stream", "input");
string url = GDataApi.GetURLForUpload (conn.User, id);
if (url == null)
throw new UnauthorizedAccessException ("You are not authorized to upload to this album.");
MultipartRequest request = new MultipartRequest (conn, url);
MemoryStream ms = null;
if (UploadProgress != null) {
// We do 'manual' buffering
request.Request.AllowWriteStreamBuffering = false;
ms = new MemoryStream ();
request.OutputStream = ms;
}
request.BeginPart (true);
request.AddHeader ("Content-Type: application/atom+xml; \r\n", true);
string upload = GetXmlForUpload (title, description);
request.WriteContent (upload);
request.EndPart (false);
request.BeginPart ();
request.AddHeader ("Content-Type: " + mime_type + "\r\n", true);
byte [] data = new byte [8192];
int nread;
while ((nread = input.Read (data, 0, data.Length)) > 0) {
request.WritePartialContent (data, 0, nread);
}
request.EndPartialContent ();
request.EndPart (true); // It won't call Close() on the MemoryStream
if (UploadProgress != null) {
int req_length = (int) ms.Length;
request.Request.ContentLength = req_length;
DoUploadProgress (title, 0, req_length);
using (Stream req_stream = request.Request.GetRequestStream ()) {
byte [] buffer = ms.GetBuffer ();
int nwrite = 0;
int offset;
for (offset = 0; offset < req_length; offset += nwrite) {
nwrite = System.Math.Min (16384, req_length - offset);
req_stream.Write (buffer, offset, nwrite);
// The progress uses the actual request size, not file size.
DoUploadProgress (title, offset, req_length);
}
DoUploadProgress (title, offset, req_length);
}
}
string received = request.GetResponseAsString ();
XmlDocument doc = new XmlDocument ();
doc.LoadXml (received);
XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
XmlUtil.AddDefaultNamespaces (nsmgr);
XmlNode entry = doc.SelectSingleNode ("atom:entry", nsmgr);
return new PicasaPicture (conn, this, entry, nsmgr);
}
public PicasaPicture UploadPicture (string filename)
{
return UploadPicture (filename, "");
}
public PicasaPicture UploadPicture (string filename, string description)
{
return UploadPicture (filename, Path.GetFileName (filename), description);
}
public PicasaPicture UploadPicture (string filename, string title, string description)
{
if (filename == null)
throw new ArgumentNullException ("filename");
if (title == null)
throw new ArgumentNullException ("title");
using (Stream stream = File.OpenRead (filename)) {
return UploadPicture (title, description, stream);
}
}
public string Title {
get { return title; }
}
public string Description {
get { return description; }
}
public string Link {
get { return link; }
}
public string UniqueID {
get { return id; }
}
public AlbumAccess Access {
get { return access; }
}
public int PicturesCount {
get { return num_photos; }
}
public int PicturesRemaining {
get { return num_photos_remaining; }
}
public string User {
get { return user; }
}
public long BytesUsed {
get { return bytes_used; }
}
internal GoogleConnection Connection {
get { return conn; }
}
void DoUploadProgress (string title, long sent, long total)
{
if (UploadProgress != null) {
UploadProgress (this, new UploadProgressEventArgs (title, sent, total));
}
}
public event UploadProgressEventHandler UploadProgress;
}
}
| |
using System.Windows.Controls;
using System.Windows.Data;
using DevExpress.Mvvm.UI.Interactivity;
using NUnit.Framework;
using DevExpress.Mvvm.Native;
using DevExpress.Mvvm.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Windows;
using System.Linq;
namespace DevExpress.Mvvm.Tests {
[TestFixture]
public class ViewModelExtensionsTests {
class ViewModel : ViewModelBase, IDocumentContent {
public IDocumentOwner DocumentOwner { get; set; }
public void OnClose(CancelEventArgs e) {
throw new NotImplementedException();
}
object title = "title";
public object Title{
get { return title; }
set { SetProperty(ref title, value, nameof(Title)); }
}
void IDocumentContent.OnDestroy() { }
}
class ViewModelWithAnotherTitle : ViewModelBase, IDocumentContent {
public IDocumentOwner DocumentOwner { get; set; }
public void OnClose(CancelEventArgs e) {
throw new NotImplementedException();
}
object title = "bad title";
public object Title {
get { return title; }
set { SetProperty(ref title, value, nameof(Title)); }
}
object documentTitle = "title";
public object DocumentTitle {
get { return documentTitle; }
set { SetProperty(ref documentTitle, value, nameof(DocumentTitle)); }
}
object IDocumentContent.Title { get { return DocumentTitle; } }
void IDocumentContent.OnDestroy() { }
}
class DObject : DependencyObject {
}
[Test]
public void SetProperties() {
var button1 = new Button();
var parentViewModel = new ViewModel();
var viewModel = new ViewModel();
ViewModelExtensions.SetParameter(button1, "test");
ViewModelExtensions.SetParentViewModel(button1, parentViewModel);
var dObject = new DObject();
ViewModelExtensions.SetParameter(dObject, "test");
ViewModelExtensions.SetParentViewModel(dObject, parentViewModel);
var button2 = new Button() { DataContext = viewModel };
ViewModelExtensions.SetParameter(button2, "test");
Assert.AreEqual("test", viewModel.With(x => x as ISupportParameter).Parameter);
ViewModelExtensions.SetParentViewModel(button2, parentViewModel);
Assert.AreEqual(parentViewModel, viewModel.With(x => x as ISupportParentViewModel).ParentViewModel);
}
[Test]
public void OldScaffoldedCode_SetParameterTest_T191302() {
var viewModel = new ViewModelSupportedParameter();
var button = new Button() { DataContext = viewModel };
ViewModelExtensions.SetParameter(button, null);
Assert.IsTrue(viewModel.ParameterChanged);
}
public class ViewModelSupportedParameter : ISupportParameter {
public bool ParameterChanged;
object ISupportParameter.Parameter {
get { return null; }
set {
ParameterChanged = true;
}
}
}
public class DocumentViewModel : BindableBase, IDocumentContent {
public IDocumentOwner DocumentOwner { get; set; }
object IDocumentContent.Title {
get { return "foo2"; }
}
void IDocumentContent.OnClose(CancelEventArgs e) {
throw new NotImplementedException();
}
void IDocumentContent.OnDestroy() { }
}
[Test]
public void ViewHelperTest() {
var button = new Button();
var viewModel = new ViewModel();
var parentViewModel = new ViewModel();
var textBlock = new TextBlock() { Text = "foo" };
Assert.AreEqual(null, ViewHelper.GetViewModelFromView(button));
ViewHelper.InitializeView(button, null, "test", parentViewModel);
DocumentUIServiceBase.SetTitleBinding(button, TextBlock.TextProperty, textBlock);
Assert.AreEqual("foo", textBlock.Text);
button.DataContext = viewModel;
Assert.AreEqual(viewModel, ViewHelper.GetViewModelFromView(button));
ViewHelper.InitializeView(button, null, "test", parentViewModel);
Assert.AreEqual("test", viewModel.With(x => x as ISupportParameter).Parameter);
Assert.AreEqual(parentViewModel, viewModel.With(x => x as ISupportParentViewModel).ParentViewModel);
DocumentUIServiceBase.SetTitleBinding(button, TextBlock.TextProperty, textBlock);
Assert.AreEqual("title", textBlock.Text);
viewModel.Title = "title2";
Assert.AreEqual("title2", textBlock.Text);
var dObject = new DObject();
Assert.AreEqual(null, ViewHelper.GetViewModelFromView(dObject));
ViewHelper.InitializeView(button, null, "test", parentViewModel);
var button2 = new Button();
button2.DataContext = new DocumentViewModel();
DocumentUIServiceBase.SetTitleBinding(button2, TextBlock.TextProperty, textBlock);
Assert.AreEqual("foo2", textBlock.Text);
ViewModelWithAnotherTitle anotherViewModel = new ViewModelWithAnotherTitle();
ViewHelper.InitializeView(button, anotherViewModel, "test", null);
Assert.AreEqual(anotherViewModel, button.DataContext);
DocumentUIServiceBase.SetTitleBinding(button, TextBlock.TextProperty, textBlock);
Assert.AreEqual("title", textBlock.Text);
viewModel.Title = "title3";
Assert.AreEqual("title", textBlock.Text);
}
[Test]
public void ViewHelperShouldWrapDocumentOwnerIfDependencyObject_Test_T122209() {
var button = new Button();
var viewModel = new ViewModel();
var parentViewModel = new ViewModel();
IDocumentOwner owner = new TestDocumentOwner();
button.DataContext = viewModel;
ViewHelper.InitializeView(button, null, "test", parentViewModel, owner);
Assert.AreEqual(owner, viewModel.DocumentOwner);
Assert.AreEqual(owner, ViewModelExtensions.GetDocumentOwner(button));
button = new Button();
button.DataContext = viewModel;
owner = new TestServiceDocumentOwner();
ViewHelper.InitializeView(button, null, "test", parentViewModel, owner);
ViewHelper.DocumentOwnerWrapper ownerWrapper = viewModel.DocumentOwner as ViewHelper.DocumentOwnerWrapper;
Assert.IsNotNull(ownerWrapper);
Assert.IsTrue(ownerWrapper.Equals(owner));
Assert.AreEqual(owner, ownerWrapper.ActualOwner);
Assert.AreEqual(ownerWrapper, ViewModelExtensions.GetDocumentOwner(button));
}
class TestViewLocator : IViewLocator {
public FrameworkElement ResolvedView { get; private set; }
string IViewLocator.GetViewTypeName(Type type) {
throw new NotImplementedException();
}
object IViewLocator.ResolveView(string name) {
ResolvedView = null;
if(name == "foo") {
ResolvedView = new TestViewElement();
}
return ResolvedView;
}
Type IViewLocator.ResolveViewType(string name) {
throw new NotImplementedException();
}
}
[Test]
public void ResolveViewTest() {
var parentViewModel = new ViewModel();
DependencyObject fallbackView;
TextBlock fallbackElement;
fallbackView = (DependencyObject)ViewHelper.CreateAndInitializeView(null, "TestView", null, "param", parentViewModel);
fallbackElement = LayoutTreeHelper.GetVisualChildren(fallbackView).OfType<TextBlock>().First();
Assert.AreEqual("\"TestView\" type not found.", fallbackElement.Text);
ViewLocator.Default = new ViewLocator(new[] { this.GetType().Assembly });
try {
var testView = ViewHelper.CreateAndInitializeView(null, "TestView", null, "param", parentViewModel);
AssertHelper.IsInstanceOf(typeof(TestView), testView);
fallbackView = (DependencyObject)ViewHelper.CreateAndInitializeView(null, "foo", null, "param", parentViewModel);
fallbackElement = LayoutTreeHelper.GetVisualChildren(fallbackView).OfType<TextBlock>().First();
Assert.AreEqual("\"foo\" type not found.", fallbackElement.Text);
TestViewElement testViewElement = (TestViewElement)ViewHelper.CreateAndInitializeView(null, "TestViewElement", null, "param", parentViewModel);
ViewModelBase viewModel = ViewHelper.GetViewModelFromView(testViewElement).With(x => x as ViewModelBase);
Assert.AreEqual("param", viewModel.With(x => x as ISupportParameter).Parameter);
Assert.AreEqual(parentViewModel, viewModel.With(x => x as ISupportParentViewModel).ParentViewModel);
testViewElement = (TestViewElement)ViewHelper.CreateAndInitializeView(new TestViewLocator(), "foo", null, "param", parentViewModel);
viewModel = ViewHelper.GetViewModelFromView(testViewElement).With(x => x as ViewModelBase);
Assert.AreEqual("param", viewModel.With(x => x as ISupportParameter).Parameter);
Assert.AreEqual(parentViewModel, viewModel.With(x => x as ISupportParentViewModel).ParentViewModel);
ViewLocator.Default = new TestViewLocator();
testViewElement = (TestViewElement)ViewHelper.CreateAndInitializeView(null, "foo", null, "param", parentViewModel);
viewModel = ViewHelper.GetViewModelFromView(testViewElement).With(x => x as ViewModelBase);
Assert.AreEqual("param", viewModel.With(x => x as ISupportParameter).Parameter);
Assert.AreEqual(parentViewModel, viewModel.With(x => x as ISupportParentViewModel).ParentViewModel);
testViewElement = (TestViewElement)ViewHelper.CreateAndInitializeView(null, "foo", "param", "param", parentViewModel);
Assert.AreEqual("param", testViewElement.DataContext);
} finally {
ViewLocator.Default = null;
}
}
[Test]
public void CreateViewThrowExceptionOnNullArgumentsTest() {
Action<InvalidOperationException> checkExceptionAction = x => {
Assert.IsTrue(x.Message.Contains(ViewHelper.Error_CreateViewMissArguments));
Assert.IsTrue(x.Message.Contains(ViewHelper.HelpLink_CreateViewMissArguments));
Assert.AreEqual(ViewHelper.HelpLink_CreateViewMissArguments, x.HelpLink);
};
AssertHelper.AssertThrows<InvalidOperationException>(() => ViewHelper.CreateView(ViewLocator.Default, null), checkExceptionAction);
AssertHelper.AssertThrows<InvalidOperationException>(() => ViewHelper.CreateAndInitializeView(viewLocator: ViewLocator.Default, documentType: null, viewModel: null, parameter: null, parentViewModel: null, viewTemplate: null, viewTemplateSelector: null), checkExceptionAction);
AssertHelper.AssertThrows<InvalidOperationException>(() => ViewHelper.CreateAndInitializeView(viewLocator: ViewLocator.Default, documentType: null, viewModel: null, parameter: null, parentViewModel: null, documentOwner: null, viewTemplate: null, viewTemplateSelector: null), checkExceptionAction);
}
[Test]
public void CreateAndInitializeViewTest1() {
TestView viewModel = new TestView();
TestView parentViewModel = new TestView();
TestView currentViewModel = null;
TestViewLocator locator = new TestViewLocator();
ViewLocator.Default = locator;
ViewHelper.CreateAndInitializeView(ViewLocator.Default, "foo", viewModel, null, null);
currentViewModel = (TestView)locator.ResolvedView.DataContext;
Assert.AreEqual(currentViewModel, viewModel);
ViewHelper.CreateAndInitializeView(ViewLocator.Default, "foo", viewModel, "1", parentViewModel);
currentViewModel = (TestView)locator.ResolvedView.DataContext;
Assert.AreEqual(currentViewModel, viewModel);
Assert.AreEqual(((ISupportParameter)currentViewModel).Parameter, "1");
Assert.AreEqual(((ISupportParentViewModel)currentViewModel).ParentViewModel, parentViewModel);
ViewHelper.CreateAndInitializeView(ViewLocator.Default, "foo", null, "1", parentViewModel);
currentViewModel = (TestView)locator.ResolvedView.DataContext;
Assert.AreNotEqual(currentViewModel, viewModel);
Assert.AreEqual(((ISupportParameter)currentViewModel).Parameter, "1");
Assert.AreEqual(((ISupportParentViewModel)currentViewModel).ParentViewModel, parentViewModel);
ViewLocator.Default = null;
}
[Test]
public void TestQ536034() {
object parameter = 1;
TestViewElement view = new TestViewElement() { DataContext = null };
BindingOperations.SetBinding(view, ViewModelExtensions.ParameterProperty, new Binding() { Source = parameter });
TestView viewModel = new TestView();
view.DataContext = viewModel;
Assert.AreEqual(1, ((ISupportParameter)viewModel).Parameter);
viewModel = new TestView();
view.DataContext = viewModel;
Assert.AreEqual(1, ((ISupportParameter)viewModel).Parameter);
parameter = 2;
ViewModelExtensions.SetParameter(view, 2);
Assert.AreEqual(2, ((ISupportParameter)viewModel).Parameter);
Assert.AreEqual(1, Interaction.GetBehaviors(view).Count);
}
class TestVM : ISupportParameter, ISupportParentViewModel, IDocumentContent {
public int ParameterChangingCounter { get; private set; }
public int ParentViewModelChangingCounter { get; private set; }
public int DocumentOwnerChangingCounter { get; private set; }
public object Parameter { get { return parameter; } set { ParameterChangingCounter++; parameter = value; } }
public object ParentViewModel { get { return parentViewModel; } set { ParentViewModelChangingCounter++; parentViewModel = value; } }
public IDocumentOwner DocumentOwner { get { return documentOwner; } set { DocumentOwnerChangingCounter++; documentOwner = value; } }
object parameter;
object parentViewModel;
IDocumentOwner documentOwner;
public object Title { get { throw new NotImplementedException(); } }
public void OnClose(CancelEventArgs e) { throw new NotImplementedException(); }
public void OnDestroy() { throw new NotImplementedException(); }
}
class TestDocumentOwner : IDocumentOwner {
public void Close(IDocumentContent documentContent, bool force = true) { throw new NotImplementedException(); }
}
[Test]
public void SetParameterTest() {
var viewModel = new TestVM();
Button button = new Button() { DataContext = viewModel };
ViewModelExtensions.SetParameter(button, 13);
Assert.AreEqual(13, viewModel.Parameter);
Assert.AreEqual(1, viewModel.ParameterChangingCounter);
}
[Test]
public void SetParentViewModelTest() {
var viewModel = new TestVM();
Button button = new Button() { DataContext = viewModel };
ViewModelExtensions.SetParentViewModel(button, 13);
Assert.AreEqual(13, viewModel.ParentViewModel);
Assert.AreEqual(1, viewModel.ParentViewModelChangingCounter);
}
[Test]
public void SetDocumentOwnerTest() {
var viewModel = new TestVM();
Button button = new Button() { DataContext = viewModel };
var documentOwner = new TestDocumentOwner();
ViewModelExtensions.SetDocumentOwner(button, documentOwner);
Assert.AreSame(documentOwner, viewModel.DocumentOwner);
Assert.AreEqual(1, viewModel.DocumentOwnerChangingCounter);
}
[Test]
public void T370425() {
var vm1 = new ViewModel();
var vm2 = new ViewModel();
var vm3 = new ViewModel();
var vm4 = new ViewModel();
ViewHelper.InitializeView(null, vm2, null, vm1);
ViewHelper.InitializeView(null, vm3, null, vm2);
ViewHelper.InitializeView(null, vm4, null, vm3);
ViewHelper.InitializeView(null, vm2, null, vm4);
Assert.AreEqual(vm1, ((ISupportParentViewModel)vm2).ParentViewModel);
Assert.AreEqual(vm2, ((ISupportParentViewModel)vm3).ParentViewModel);
Assert.AreEqual(vm3, ((ISupportParentViewModel)vm4).ParentViewModel);
}
}
public class TestView : ViewModelBase {
}
class TestServiceDocumentOwner : ServiceBase, IDocumentOwner {
public void Close(IDocumentContent documentContent, bool force = true) {
throw new NotImplementedException();
}
}
class TestDocumentOwner : IDocumentOwner {
public void Close(IDocumentContent documentContent, bool force = true) {
throw new NotImplementedException();
}
}
public class TestViewElement : FrameworkElement {
public TestViewElement() {
DataContext = new TestView();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AcademyEcosystem
{
public abstract class Animal : Organism
{
protected int sleepRemaining;
public AnimalState State { get; protected set; }
public string Name { get; private set; }
protected Animal(string name, Point location, int size)
: base(location, size)
{
this.Name = name;
this.sleepRemaining = 0;
}
public virtual int GetMeatFromKillQuantity()
{
this.IsAlive = false;
return this.Size;
}
public void GoTo(Point destination)
{
this.Location = destination;
if (this.State == AnimalState.Sleeping)
{
this.Awake();
}
}
public void Sleep(int time)
{
this.sleepRemaining = time;
this.State = AnimalState.Sleeping;
}
protected void Awake()
{
this.sleepRemaining = 0;
this.State = AnimalState.Awake;
}
public override void Update(int timeElapsed)
{
if (this.sleepRemaining == 0)
{
this.Awake();
}
}
public override string ToString()
{
return base.ToString() + " " + this.Name;
}
}
}
namespace AcademyEcosystem
{
public enum AnimalState
{
Sleeping,
Awake
}
}
namespace AcademyEcosystem
{
public class Bush : Plant
{
public Bush(Point location)
: base(location, 4)
{
}
}
}
namespace AcademyEcosystem
{
public class Deer : Animal, IHerbivore
{
private int biteSize;
public Deer(string name, Point location)
: base(name, location, 3)
{
this.biteSize = 1;
}
public override void Update(int timeElapsed)
{
if (this.State == AnimalState.Sleeping)
{
if (timeElapsed >= sleepRemaining)
{
this.Awake();
}
else
{
this.sleepRemaining -= timeElapsed;
}
}
base.Update(timeElapsed);
}
public int EatPlant(Plant p)
{
if (p != null)
{
return p.GetEatenQuantity(this.biteSize);
}
return 0;
}
}
}
namespace AcademyEcosystem
{
public class Engine
{
protected static readonly char[] separators = new char[] { ' ' };
protected List<Organism> allOrganisms;
protected List<Plant> plants;
protected List<Animal> animals;
public Engine()
{
this.allOrganisms = new List<Organism>();
this.plants = new List<Plant>();
this.animals = new List<Animal>();
}
public void AddOrganism(Organism organism)
{
this.allOrganisms.Add(organism);
var organismAsAnimal = organism as Animal;
var organismAsPlant = organism as Plant;
if (organismAsAnimal != null)
{
this.animals.Add(organismAsAnimal);
}
if (organismAsPlant != null)
{
this.plants.Add(organismAsPlant);
}
}
public void ExecuteCommand(string command)
{
string[] commandWords = command.Split(Engine.separators, StringSplitOptions.RemoveEmptyEntries);
if (commandWords[0] == "birth")
{
this.ExecuteBirthCommand(commandWords);
}
else
{
this.ExecuteAnimalCommand(commandWords);
}
this.RemoveAndReportDead();
}
protected virtual void ExecuteBirthCommand(string[] commandWords)
{
switch (commandWords[1])
{
case "deer":
{
string name = commandWords[2];
Point position = Point.Parse(commandWords[3]);
this.AddOrganism(new Deer(name, position));
break;
}
case "tree":
{
Point position = Point.Parse(commandWords[2]);
this.AddOrganism(new Tree(position));
break;
}
case "bush":
{
Point position = Point.Parse(commandWords[2]);
this.AddOrganism(new Bush(position));
break;
}
}
}
protected virtual void ExecuteAnimalCommand(string[] commandWords)
{
switch (commandWords[0])
{
case "go":
{
string name = commandWords[1];
Point destination = Point.Parse(commandWords[2]);
destination = HandleGo(name, destination);
break;
}
case "sleep":
{
string name = commandWords[1];
int sleepTime = int.Parse(commandWords[2]);
HandleSleep(name, sleepTime);
break;
}
}
}
private Point HandleGo(string name, Point destination)
{
Animal current = GetAnimalByName(name);
if (current != null)
{
int travelTime = Point.GetManhattanDistance(current.Location, destination);
this.UpdateAll(travelTime);
current.GoTo(destination);
HandleEncounters(current);
}
return destination;
}
private void HandleEncounters(Animal current)
{
List<Organism> allEncountered = new List<Organism>();
foreach (var organism in this.allOrganisms)
{
if (organism.Location == current.Location && !(organism == current))
{
allEncountered.Add(organism);
}
}
var currentAsHerbivore = current as IHerbivore;
if (currentAsHerbivore != null)
{
foreach (var encountered in allEncountered)
{
int eatenQuantity = currentAsHerbivore.EatPlant(encountered as Plant);
if (eatenQuantity != 0)
{
Console.WriteLine("{0} ate {1} from {2}", current, eatenQuantity, encountered);
}
}
}
allEncountered.RemoveAll(o => !o.IsAlive);
var currentAsCarnivore = current as ICarnivore;
if (currentAsCarnivore != null)
{
foreach (var encountered in allEncountered)
{
int eatenQuantity = currentAsCarnivore.TryEatAnimal(encountered as Animal);
if (eatenQuantity != 0)
{
Console.WriteLine("{0} ate {1} from {2}", current, eatenQuantity, encountered);
}
}
}
this.RemoveAndReportDead();
}
private void HandleSleep(string name, int sleepTime)
{
Animal current = GetAnimalByName(name);
if (current != null)
{
current.Sleep(sleepTime);
}
}
private Animal GetAnimalByName(string name)
{
Animal current = null;
foreach (var animal in this.animals)
{
if (animal.Name == name)
{
current = animal;
break;
}
}
return current;
}
protected virtual void RemoveAndReportDead()
{
foreach (var organism in this.allOrganisms)
{
if (!organism.IsAlive)
{
Console.WriteLine("{0} is dead ;(", organism);
}
}
this.allOrganisms.RemoveAll(o => !o.IsAlive);
this.plants.RemoveAll(o => !o.IsAlive);
this.animals.RemoveAll(o => !o.IsAlive);
}
protected virtual void UpdateAll(int timeElapsed)
{
foreach (var organism in this.allOrganisms)
{
organism.Update(timeElapsed);
}
}
}
}
namespace AcademyEcosystem
{
public interface ICarnivore
{
int TryEatAnimal(Animal animal);
}
}
namespace AcademyEcosystem
{
public interface IHerbivore
{
int EatPlant(Plant plant);
}
}
namespace AcademyEcosystem
{
public interface IOrganism
{
bool IsAlive { get; }
Point Location { get; }
int Size { get; }
void Update(int timeElapsed);
}
}
namespace AcademyEcosystem
{
public abstract class Organism : IOrganism
{
public bool IsAlive { get; protected set; }
public Point Location { get; protected set; }
public int Size { get; protected set; }
public Organism(Point location, int size)
{
this.Location = location;
this.Size = size;
this.IsAlive = true;
}
public virtual void Update(int time)
{
}
public virtual void RespondTo(IOrganism organism)
{
}
public override string ToString()
{
return this.GetType().Name;
}
}
}
namespace AcademyEcosystem
{
public abstract class Plant : Organism
{
protected Plant(Point location, int size)
: base(location, size)
{
}
public int GetEatenQuantity(int biteSize)
{
if (biteSize > this.Size)
{
this.IsAlive = false;
this.Size = 0;
return this.Size;
}
else
{
this.Size -= biteSize;
return biteSize;
}
}
public override string ToString()
{
return base.ToString() + " " + this.Location;
}
}
}
namespace AcademyEcosystem
{
public struct Point
{
public readonly int X;
public readonly int Y;
public Point(int x, int y)
{
this.X = x;
this.Y = y;
}
public Point(string xString, string yString)
{
this.X = int.Parse(xString);
this.Y = int.Parse(yString);
}
public override int GetHashCode()
{
return this.X * 7 + this.Y;
}
public static bool operator ==(Point a, Point b)
{
return a.X == b.X && a.Y == b.Y;
}
public static bool operator !=(Point a, Point b)
{
return !(a == b);
}
public override string ToString()
{
return String.Format("({0},{1})", this.X, this.Y);
}
public static Point Parse(string pointString)
{
string coordinatesPairString = pointString.Substring(1, pointString.Length - 2);
string[] coordinates = coordinatesPairString.Split(',');
return new Point(coordinates[0], coordinates[1]);
}
public static int GetManhattanDistance(Point a, Point b)
{
return Math.Abs(a.X - b.X) + Math.Abs(a.Y - b.Y);
}
}
}
namespace AcademyEcosystem
{
public class Grass : Plant
{
public Grass(Point location)
: base(location, 2)
{
}
public override void Update(int time)
{
if (this.IsAlive)
{
this.Size+=time;
}
base.Update(time);
}
}
public class Zombie : Animal
{
public Zombie(string name, Point location)
: base(name, location, 10)
{
}
public override int GetMeatFromKillQuantity()
{
return this.Size;
}
}
public class Boar : Animal, ICarnivore, IHerbivore
{
private int biteSize;
public Boar(string name, Point location)
: base(name, location, 4)
{
this.biteSize = 2;
}
public int TryEatAnimal(Animal animal)
{
if (animal != null)
{
if (animal.GetType().Name == "Zombie")
{
return animal.GetMeatFromKillQuantity();
}
else if (animal.Size <= this.Size)
{
return animal.GetMeatFromKillQuantity();
}
else return 0;
}
else return 0;
}
public int EatPlant(Plant plant)
{
if (plant != null)
{
this.Size++;
return plant.GetEatenQuantity(this.biteSize);
}
else return 0;
}
}
public class Lion : Animal, ICarnivore
{
public Lion(string name, Point location)
: base(name, location, 6)
{
}
public int TryEatAnimal(Animal animal)
{
if (animal != null)
{
if (animal.GetType().Name == "Zombie")
{
return animal.GetMeatFromKillQuantity();
}
else if (animal.Size <= 2 * this.Size)
{
this.Size++;
return animal.GetMeatFromKillQuantity();
}
else return 0;
}
else return 0;
}
}
public class Wolf : Animal, ICarnivore
{
public Wolf(string name, Point location)
: base(name, location, 4)
{
}
public int TryEatAnimal(Animal animal)
{
if (animal != null)
{
if (animal.GetType().Name == "Zombie")
{
return animal.GetMeatFromKillQuantity();
}
else if (animal.Size <= 4 || animal.State == AnimalState.Sleeping)
{
return animal.GetMeatFromKillQuantity();
}
else return 0;
}
else return 0;
}
}
public class MyEngine : Engine
{
public MyEngine()
: base()
{
}
protected override void ExecuteBirthCommand(string[] commandWords)
{
switch (commandWords[1])
{
case "wolf":
{
string name = commandWords[2];
Point location = Point.Parse(commandWords[3]);
this.AddOrganism(new Wolf(name, location));
break;
}
case "lion":
{
string name = commandWords[2];
Point location = Point.Parse(commandWords[3]);
this.AddOrganism(new Lion(name, location));
break;
}
case "grass":
{
Point location = Point.Parse(commandWords[2]);
this.AddOrganism(new Grass(location));
break;
}
case "boar":
{
string name = commandWords[2];
Point location = Point.Parse(commandWords[3]);
this.AddOrganism(new Boar(name, location));
break;
}
case "zombie":
{
string name = commandWords[2];
Point location = Point.Parse(commandWords[3]);
this.AddOrganism(new Zombie(name, location));
break;
}
default:
{
base.ExecuteBirthCommand(commandWords);
break;
}
}
}
}
}
namespace AcademyEcosystem
{
class Program
{
static Engine GetEngineInstance()
{
return new MyEngine();
}
static void Main(string[] args)
{
Engine engine = GetEngineInstance();
string command = Console.ReadLine();
while (command != "end")
{
engine.ExecuteCommand(command);
command = Console.ReadLine();
}
}
}
}
namespace AcademyEcosystem
{
public class Tree : Plant
{
public Tree(Point location)
: base(location, 15)
{
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Apple;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class AppleCrypto
{
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainItemCopyKeychain(
IntPtr item,
out SafeKeychainHandle keychain);
[DllImport(Libraries.AppleCryptoNative, EntryPoint = "AppleCryptoNative_SecKeychainCreate")]
private static extern int AppleCryptoNative_SecKeychainCreateTemporary(
string path,
int utf8PassphraseLength,
byte[] utf8Passphrase,
out SafeTemporaryKeychainHandle keychain);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainCreate(
string path,
int utf8PassphraseLength,
byte[] utf8Passphrase,
out SafeKeychainHandle keychain);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainDelete(IntPtr keychain);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainCopyDefault(out SafeKeychainHandle keychain);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainOpen(
string keychainPath,
out SafeKeychainHandle keychain);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainUnlock(
SafeKeychainHandle keychain,
int utf8PassphraseLength,
byte[] utf8Passphrase);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SetKeychainNeverLock(SafeKeychainHandle keychain);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainEnumerateCerts(
SafeKeychainHandle keychain,
out SafeCFArrayHandle matches,
out int pOSStatus);
[DllImport(Libraries.AppleCryptoNative)]
private static extern int AppleCryptoNative_SecKeychainEnumerateIdentities(
SafeKeychainHandle keychain,
out SafeCFArrayHandle matches,
out int pOSStatus);
internal static SafeKeychainHandle SecKeychainItemCopyKeychain(SafeKeychainItemHandle item)
{
bool addedRef = false;
try
{
item.DangerousAddRef(ref addedRef);
var handle = SecKeychainItemCopyKeychain(item.DangerousGetHandle());
return handle;
}
finally
{
if (addedRef)
{
item.DangerousRelease();
}
}
}
internal static SafeKeychainHandle SecKeychainItemCopyKeychain(IntPtr item)
{
SafeKeychainHandle keychain;
int osStatus = AppleCryptoNative_SecKeychainItemCopyKeychain(item, out keychain);
// A whole lot of NULL is expected from this.
// Any key or cert which isn't keychain-backed, and this is the primary way we'd find that out.
if (keychain.IsInvalid)
{
GC.SuppressFinalize(keychain);
}
if (osStatus == 0)
{
return keychain;
}
throw CreateExceptionForOSStatus(osStatus);
}
internal static SafeKeychainHandle SecKeychainCopyDefault()
{
SafeKeychainHandle keychain;
int osStatus = AppleCryptoNative_SecKeychainCopyDefault(out keychain);
if (osStatus == 0)
{
return keychain;
}
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
internal static SafeKeychainHandle SecKeychainOpen(string keychainPath)
{
SafeKeychainHandle keychain;
int osStatus = AppleCryptoNative_SecKeychainOpen(keychainPath, out keychain);
if (osStatus == 0)
{
return keychain;
}
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
internal static SafeCFArrayHandle KeychainEnumerateCerts(SafeKeychainHandle keychainHandle)
{
SafeCFArrayHandle matches;
int osStatus;
int result = AppleCryptoNative_SecKeychainEnumerateCerts(keychainHandle, out matches, out osStatus);
if (result == 1)
{
return matches;
}
matches.Dispose();
if (result == 0)
throw CreateExceptionForOSStatus(osStatus);
Debug.Fail($"Unexpected result from AppleCryptoNative_SecKeychainEnumerateCerts: {result}");
throw new CryptographicException();
}
internal static SafeCFArrayHandle KeychainEnumerateIdentities(SafeKeychainHandle keychainHandle)
{
SafeCFArrayHandle matches;
int osStatus;
int result = AppleCryptoNative_SecKeychainEnumerateIdentities(keychainHandle, out matches, out osStatus);
if (result == 1)
{
return matches;
}
matches.Dispose();
if (result == 0)
throw CreateExceptionForOSStatus(osStatus);
Debug.Fail($"Unexpected result from AppleCryptoNative_SecKeychainEnumerateCerts: {result}");
throw new CryptographicException();
}
internal static SafeKeychainHandle CreateOrOpenKeychain(string keychainPath, bool createAllowed)
{
const int errSecAuthFailed = -25293;
const int errSecDuplicateKeychain = -25296;
SafeKeychainHandle keychain;
int osStatus;
if (createAllowed)
{
// Attempt to create first
osStatus = AppleCryptoNative_SecKeychainCreate(
keychainPath,
0,
Array.Empty<byte>(),
out keychain);
if (osStatus == 0)
{
return keychain;
}
if (osStatus != errSecDuplicateKeychain)
{
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
}
osStatus = AppleCryptoNative_SecKeychainOpen(keychainPath, out keychain);
if (osStatus == 0)
{
// Try to unlock with empty password to match our behaviour in CreateKeychain.
// If the password doesn't match then ignore it silently and fallback to the
// default behavior of user interaction.
osStatus = AppleCryptoNative_SecKeychainUnlock(keychain, 0, Array.Empty<byte>());
if (osStatus == 0 || osStatus == errSecAuthFailed)
{
return keychain;
}
}
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
internal static SafeTemporaryKeychainHandle CreateTemporaryKeychain()
{
string tmpKeychainPath = Path.Combine(
Path.GetTempPath(),
Guid.NewGuid().ToString("N") + ".keychain");
// Use a distinct GUID so that if a keychain is abandoned it isn't recoverable.
string tmpKeychainPassphrase = Guid.NewGuid().ToString("N");
byte[] utf8Passphrase = System.Text.Encoding.UTF8.GetBytes(tmpKeychainPassphrase);
SafeTemporaryKeychainHandle keychain;
int osStatus = AppleCryptoNative_SecKeychainCreateTemporary(
tmpKeychainPath,
utf8Passphrase.Length,
utf8Passphrase,
out keychain);
SafeTemporaryKeychainHandle.TrackKeychain(keychain);
if (osStatus == 0)
{
osStatus = AppleCryptoNative_SetKeychainNeverLock(keychain);
}
if (osStatus != 0)
{
keychain.Dispose();
throw CreateExceptionForOSStatus(osStatus);
}
return keychain;
}
internal static void SecKeychainDelete(IntPtr handle, bool throwOnError=true)
{
int osStatus = AppleCryptoNative_SecKeychainDelete(handle);
if (throwOnError && osStatus != 0)
{
throw CreateExceptionForOSStatus(osStatus);
}
}
}
}
namespace System.Security.Cryptography.Apple
{
internal class SafeKeychainItemHandle : SafeHandle
{
internal SafeKeychainItemHandle()
: base(IntPtr.Zero, ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
SafeTemporaryKeychainHandle.UntrackItem(handle);
Interop.CoreFoundation.CFRelease(handle);
SetHandle(IntPtr.Zero);
return true;
}
public override bool IsInvalid => handle == IntPtr.Zero;
}
internal class SafeKeychainHandle : SafeHandle
{
internal SafeKeychainHandle()
: base(IntPtr.Zero, ownsHandle: true)
{
}
internal SafeKeychainHandle(IntPtr handle)
: base(handle, ownsHandle: true)
{
}
protected override bool ReleaseHandle()
{
Interop.CoreFoundation.CFRelease(handle);
SetHandle(IntPtr.Zero);
return true;
}
public override bool IsInvalid => handle == IntPtr.Zero;
}
internal sealed class SafeTemporaryKeychainHandle : SafeKeychainHandle
{
private static readonly Dictionary<IntPtr, SafeTemporaryKeychainHandle> s_lookup =
new Dictionary<IntPtr, SafeTemporaryKeychainHandle>();
internal SafeTemporaryKeychainHandle()
{
}
protected override bool ReleaseHandle()
{
lock (s_lookup)
{
s_lookup.Remove(handle);
}
Interop.AppleCrypto.SecKeychainDelete(handle, throwOnError: false);
return base.ReleaseHandle();
}
protected override void Dispose(bool disposing)
{
if (disposing && SafeHandleCache<SafeTemporaryKeychainHandle>.IsCachedInvalidHandle(this))
{
return;
}
base.Dispose(disposing);
}
public static SafeTemporaryKeychainHandle InvalidHandle =>
SafeHandleCache<SafeTemporaryKeychainHandle>.GetInvalidHandle(() => new SafeTemporaryKeychainHandle());
internal static void TrackKeychain(SafeTemporaryKeychainHandle toTrack)
{
if (toTrack.IsInvalid)
{
return;
}
lock (s_lookup)
{
Debug.Assert(!s_lookup.ContainsKey(toTrack.handle));
s_lookup[toTrack.handle] = toTrack;
}
}
internal static void TrackItem(SafeKeychainItemHandle keychainItem)
{
if (keychainItem.IsInvalid)
return;
using (SafeKeychainHandle keychain = Interop.AppleCrypto.SecKeychainItemCopyKeychain(keychainItem))
{
if (keychain.IsInvalid)
{
return;
}
lock (s_lookup)
{
SafeTemporaryKeychainHandle temporaryHandle;
if (s_lookup.TryGetValue(keychain.DangerousGetHandle(), out temporaryHandle))
{
bool ignored = false;
temporaryHandle.DangerousAddRef(ref ignored);
}
}
}
}
internal static void UntrackItem(IntPtr keychainItem)
{
using (SafeKeychainHandle keychain = Interop.AppleCrypto.SecKeychainItemCopyKeychain(keychainItem))
{
if (keychain.IsInvalid)
{
return;
}
lock (s_lookup)
{
SafeTemporaryKeychainHandle temporaryHandle;
if (s_lookup.TryGetValue(keychain.DangerousGetHandle(), out temporaryHandle))
{
temporaryHandle.DangerousRelease();
}
}
}
}
}
}
| |
// <copyright file="OwinHelpers.cs" company="Microsoft Open Technologies, Inc.">
// Copyright 2013 Microsoft Open Technologies, 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.
// </copyright>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.Owin.StaticFiles.Infrastructure
{
[System.CodeDom.Compiler.GeneratedCode("App_Packages", "")]
internal struct HeaderSegment : IEquatable<HeaderSegment>
{
private readonly StringSegment _formatting;
private readonly StringSegment _data;
// <summary>
// Initializes a new instance of the <see cref="T:System.Object"/> class.
// </summary>
public HeaderSegment(StringSegment formatting, StringSegment data)
{
_formatting = formatting;
_data = data;
}
public StringSegment Formatting
{
get { return _formatting; }
}
public StringSegment Data
{
get { return _data; }
}
#region Equality members
public bool Equals(HeaderSegment other)
{
return _formatting.Equals(other._formatting) && _data.Equals(other._data);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is HeaderSegment && Equals((HeaderSegment)obj);
}
public override int GetHashCode()
{
unchecked
{
return (_formatting.GetHashCode() * 397) ^ _data.GetHashCode();
}
}
public static bool operator ==(HeaderSegment left, HeaderSegment right)
{
return left.Equals(right);
}
public static bool operator !=(HeaderSegment left, HeaderSegment right)
{
return !left.Equals(right);
}
#endregion
}
[System.CodeDom.Compiler.GeneratedCode("App_Packages", "")]
internal struct HeaderSegmentCollection : IEnumerable<HeaderSegment>, IEquatable<HeaderSegmentCollection>
{
private readonly string[] _headers;
public HeaderSegmentCollection(string[] headers)
{
_headers = headers;
}
public HeaderSegmentCollection(IList<string> headers)
{
_headers = headers.ToArray();
}
#region Equality members
public bool Equals(HeaderSegmentCollection other)
{
return Equals(_headers, other._headers);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is HeaderSegmentCollection && Equals((HeaderSegmentCollection)obj);
}
public override int GetHashCode()
{
return (_headers != null ? _headers.GetHashCode() : 0);
}
public static bool operator ==(HeaderSegmentCollection left, HeaderSegmentCollection right)
{
return left.Equals(right);
}
public static bool operator !=(HeaderSegmentCollection left, HeaderSegmentCollection right)
{
return !left.Equals(right);
}
#endregion
public Enumerator GetEnumerator()
{
return new Enumerator(_headers);
}
IEnumerator<HeaderSegment> IEnumerable<HeaderSegment>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
internal struct Enumerator : IEnumerator<HeaderSegment>
{
private readonly string[] _headers;
private int _index;
private string _header;
private int _headerLength;
private int _offset;
private int _leadingStart;
private int _leadingEnd;
private int _valueStart;
private int _valueEnd;
private int _trailingStart;
private Mode _mode;
private static readonly string[] NoHeaders = new string[0];
public Enumerator(string[] headers)
{
_headers = headers ?? NoHeaders;
_header = string.Empty;
_headerLength = -1;
_index = -1;
_offset = -1;
_leadingStart = -1;
_leadingEnd = -1;
_valueStart = -1;
_valueEnd = -1;
_trailingStart = -1;
_mode = Mode.Leading;
}
private enum Mode
{
Leading,
Value,
ValueQuoted,
Trailing,
Produce,
}
private enum Attr
{
Value,
Quote,
Delimiter,
Whitespace
}
public HeaderSegment Current
{
get
{
return new HeaderSegment(
new StringSegment(_header, _leadingStart, _leadingEnd - _leadingStart),
new StringSegment(_header, _valueStart, _valueEnd - _valueStart));
}
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
}
public bool MoveNext()
{
while (true)
{
if (_mode == Mode.Produce)
{
_leadingStart = _trailingStart;
_leadingEnd = -1;
_valueStart = -1;
_valueEnd = -1;
_trailingStart = -1;
if (_offset == _headerLength &&
_leadingStart != -1 &&
_leadingStart != _offset)
{
// Also produce trailing whitespace
_leadingEnd = _offset;
return true;
}
_mode = Mode.Leading;
}
// if end of a string
if (_offset == _headerLength)
{
++_index;
_offset = -1;
_leadingStart = 0;
_leadingEnd = -1;
_valueStart = -1;
_valueEnd = -1;
_trailingStart = -1;
// if that was the last string
if (_index == _headers.Length)
{
// no more move nexts
return false;
}
// grab the next string
_header = _headers[_index] ?? string.Empty;
_headerLength = _header.Length;
}
while (true)
{
++_offset;
var ch = _offset == _headerLength ? (char)0 : _header[_offset];
// todo - array of attrs
var attr = char.IsWhiteSpace(ch) ? Attr.Whitespace : ch == '\"' ? Attr.Quote : (ch == ',' || ch == (char)0) ? Attr.Delimiter : Attr.Value;
switch (_mode)
{
case Mode.Leading:
switch (attr)
{
case Attr.Delimiter:
_leadingEnd = _offset;
_mode = Mode.Produce;
break;
case Attr.Quote:
_leadingEnd = _offset;
_valueStart = _offset;
_mode = Mode.ValueQuoted;
break;
case Attr.Value:
_leadingEnd = _offset;
_valueStart = _offset;
_mode = Mode.Value;
break;
case Attr.Whitespace:
// more
break;
}
break;
case Mode.Value:
switch (attr)
{
case Attr.Quote:
_mode = Mode.ValueQuoted;
break;
case Attr.Delimiter:
_valueEnd = _offset;
_trailingStart = _offset;
_mode = Mode.Produce;
break;
case Attr.Value:
// more
break;
case Attr.Whitespace:
_valueEnd = _offset;
_trailingStart = _offset;
_mode = Mode.Trailing;
break;
}
break;
case Mode.ValueQuoted:
switch (attr)
{
case Attr.Quote:
_mode = Mode.Value;
break;
case Attr.Delimiter:
if (ch == (char)0)
{
_valueEnd = _offset;
_trailingStart = _offset;
_mode = Mode.Produce;
}
break;
case Attr.Value:
case Attr.Whitespace:
// more
break;
}
break;
case Mode.Trailing:
switch (attr)
{
case Attr.Delimiter:
_mode = Mode.Produce;
break;
case Attr.Quote:
// back into value
_trailingStart = -1;
_valueEnd = -1;
_mode = Mode.ValueQuoted;
break;
case Attr.Value:
// back into value
_trailingStart = -1;
_valueEnd = -1;
_mode = Mode.Value;
break;
case Attr.Whitespace:
// more
break;
}
break;
}
if (_mode == Mode.Produce)
{
return true;
}
}
}
}
public void Reset()
{
_index = 0;
_offset = 0;
_leadingStart = 0;
_leadingEnd = 0;
_valueStart = 0;
_valueEnd = 0;
}
}
}
[System.CodeDom.Compiler.GeneratedCode("App_Packages", "")]
internal struct StringSegment : IEquatable<StringSegment>
{
private readonly string _buffer;
private readonly int _offset;
private readonly int _count;
// <summary>
// Initializes a new instance of the <see cref="T:System.Object"/> class.
// </summary>
public StringSegment(string buffer, int offset, int count)
{
_buffer = buffer;
_offset = offset;
_count = count;
}
public string Buffer
{
get { return _buffer; }
}
public int Offset
{
get { return _offset; }
}
public int Count
{
get { return _count; }
}
public string Value
{
get
{
return _offset == -1 ? null : _buffer.Substring(_offset, _count);
}
}
public bool HasValue
{
get
{
return _offset != -1 && _count != 0 && _buffer != null;
}
}
#region Equality members
public bool Equals(StringSegment other)
{
return string.Equals(_buffer, other._buffer) && _offset == other._offset && _count == other._count;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is StringSegment && Equals((StringSegment)obj);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = (_buffer != null ? _buffer.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ _offset;
hashCode = (hashCode * 397) ^ _count;
return hashCode;
}
}
public static bool operator ==(StringSegment left, StringSegment right)
{
return left.Equals(right);
}
public static bool operator !=(StringSegment left, StringSegment right)
{
return !left.Equals(right);
}
#endregion
public bool StartsWith(string text, StringComparison comparisonType)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
var textLength = text.Length;
if (!HasValue || _count < textLength)
{
return false;
}
return string.Compare(_buffer, _offset, text, 0, textLength, comparisonType) == 0;
}
public bool EndsWith(string text, StringComparison comparisonType)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
var textLength = text.Length;
if (!HasValue || _count < textLength)
{
return false;
}
return string.Compare(_buffer, _offset + _count - textLength, text, 0, textLength, comparisonType) == 0;
}
public bool Equals(string text, StringComparison comparisonType)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
var textLength = text.Length;
if (!HasValue || _count != textLength)
{
return false;
}
return string.Compare(_buffer, _offset, text, 0, textLength, comparisonType) == 0;
}
public string Substring(int offset, int length)
{
return _buffer.Substring(_offset + offset, length);
}
public StringSegment Subsegment(int offset, int length)
{
return new StringSegment(_buffer, _offset + offset, length);
}
public override string ToString()
{
return Value ?? string.Empty;
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Uncomment to make asset Get requests for existing
// #define WAIT_ON_INPROGRESS_REQUESTS
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Timers;
using Aurora.Simulation.Base;
using Nini.Config;
using OpenMetaverse;
using Aurora.Framework;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using ProtoBuf;
namespace OpenSim.Services
{
public class FlotsamAssetCache : IService, IImprovedAssetCache
{
#region Declares
private const string m_ModuleName = "FlotsamAssetCache";
private const string m_DefaultCacheDirectory = m_ModuleName;
private string m_CacheDirectory = m_DefaultCacheDirectory;
private readonly List<char> m_InvalidChars = new List<char>();
private int m_logLevel;
private ulong m_HitRateDisplay = 1; // How often to display hit statistics, given in requests
private static ulong m_Requests;
private Dictionary<string, AssetRequest> m_assetRequests = new Dictionary<string, AssetRequest>();
private class AssetRequest
{
private int _amt = 1;
public int Amt
{
get { return _amt; }
set
{
_amt = value;
LastAccessedTimeSpan = DateTime.Now - LastAccessed;
if (LastAccessedTimeSpan.Seconds > 10)
_amt = 0;
LastAccessed = DateTime.Now;
}
}
private int _savedamt = 1;
public int SavedAmt
{
get { return _savedamt; }
set
{
_savedamt = value;
LastAccessedTimeSpan = DateTime.Now - LastAccessed;
if (LastAccessedTimeSpan.Seconds > 10)
_savedamt = 0;
LastAccessed = DateTime.Now;
}
}
public TimeSpan LastAccessedTimeSpan = TimeSpan.FromDays(1000);
public DateTime LastAccessed = DateTime.Now;
}
private static ulong m_RequestsForInprogress;
private static ulong m_DiskHits;
private static ulong m_MemoryHits;
private static double m_HitRateMemory;
private static double m_HitRateFile;
#if WAIT_ON_INPROGRESS_REQUESTS
private Dictionary<string, ManualResetEvent> m_CurrentlyWriting = new Dictionary<string, ManualResetEvent>();
private int m_WaitOnInprogressTimeout = 3000;
#else
private HashSet<string> m_CurrentlyWriting = new HashSet<string>();
#endif
private ExpiringCache<string, AssetBase> m_MemoryCache;
private bool m_MemoryCacheEnabled = true;
// Expiration is expressed in hours.
private const double m_DefaultMemoryExpiration = 1.0;
private const double m_DefaultFileExpiration = 48;
private TimeSpan m_MemoryExpiration = TimeSpan.Zero;
private TimeSpan m_FileExpiration = TimeSpan.Zero;
private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.Zero;
private readonly object m_fileCacheLock = new Object();
private static int m_CacheDirectoryTiers = 1;
private static int m_CacheDirectoryTierLen = 3;
private static int m_CacheWarnAt = 30000;
private Timer m_CacheCleanTimer;
private IAssetService m_AssetService;
private ISimulationBase m_simulationBase;
private bool m_DeepScanBeforePurge;
private static int _forceMemoryCacheAmount = 2;
private IAssetMonitor _assetMonitor;
public FlotsamAssetCache()
{
m_InvalidChars.AddRange(Path.GetInvalidPathChars());
m_InvalidChars.AddRange(Path.GetInvalidFileNameChars());
}
public string Name
{
get { return m_ModuleName; }
}
#endregion
#region IService Members
public void Initialize(IConfigSource config, IRegistryCore registry)
{
IConfig moduleConfig = config.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("AssetCaching", String.Empty);
if (name == Name)
{
m_MemoryCache = new ExpiringCache<string, AssetBase>();
//MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE]: {0} enabled", this.Name);
IConfig assetConfig = config.Configs["AssetCache"];
if (assetConfig == null)
{
//MainConsole.Instance.Warn("[FLOTSAM ASSET CACHE]: AssetCache missing from Aurora.ini, using defaults.");
//MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory", m_DefaultCacheDirectory);
return;
}
m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory);
//MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory", m_DefaultCacheDirectory);
m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", false);
m_MemoryExpiration =
TimeSpan.FromHours(assetConfig.GetDouble("MemoryCacheTimeout", m_DefaultMemoryExpiration));
#if WAIT_ON_INPROGRESS_REQUESTS
m_WaitOnInprogressTimeout = assetConfig.GetInt("WaitOnInprogressTimeout", 3000);
#endif
m_logLevel = assetConfig.GetInt("LogLevel", 0);
m_HitRateDisplay = (ulong) assetConfig.GetInt("HitRateDisplay", 1000);
m_FileExpiration =
TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration));
m_FileExpirationCleanupTimer =
TimeSpan.FromHours(assetConfig.GetDouble("FileCleanupTimer", m_DefaultFileExpiration));
if ((m_FileExpiration > TimeSpan.Zero) && (m_FileExpirationCleanupTimer > TimeSpan.Zero))
{
m_CacheCleanTimer = new Timer(m_FileExpirationCleanupTimer.TotalMilliseconds) {AutoReset = true};
m_CacheCleanTimer.Elapsed += CleanupExpiredFiles;
lock (m_CacheCleanTimer)
m_CacheCleanTimer.Start();
}
m_CacheDirectoryTiers = assetConfig.GetInt("CacheDirectoryTiers", 1);
if (m_CacheDirectoryTiers < 1)
{
m_CacheDirectoryTiers = 1;
}
else if (m_CacheDirectoryTiers > 3)
{
m_CacheDirectoryTiers = 3;
}
m_CacheDirectoryTierLen = assetConfig.GetInt("CacheDirectoryTierLength", 3);
if (m_CacheDirectoryTierLen < 1)
{
m_CacheDirectoryTierLen = 1;
}
else if (m_CacheDirectoryTierLen > 4)
{
m_CacheDirectoryTierLen = 4;
}
m_CacheWarnAt = assetConfig.GetInt("CacheWarnAt", 30000);
m_DeepScanBeforePurge = assetConfig.GetBoolean("DeepScanBeforePurge", false);
if (MainConsole.Instance != null)
{
MainConsole.Instance.Commands.AddCommand("fcache status", "fcache status",
"Display cache status", HandleConsoleCommand);
MainConsole.Instance.Commands.AddCommand("fcache clear", "fcache clear [file] [memory]",
"Remove all assets in the file and/or memory cache",
HandleConsoleCommand);
MainConsole.Instance.Commands.AddCommand("fcache assets", "fcache assets",
"Attempt a deep scan and cache of all assets in all scenes",
HandleConsoleCommand);
MainConsole.Instance.Commands.AddCommand("fcache expire", "fcache expire <datetime>",
"Purge cached assets older then the specified date/time",
HandleConsoleCommand);
}
registry.RegisterModuleInterface<IImprovedAssetCache>(this);
}
}
}
public void Configure(IConfigSource config, IRegistryCore registry)
{
}
public void Start(IConfigSource config, IRegistryCore registry)
{
m_AssetService = registry.RequestModuleInterface<IAssetService>();
m_simulationBase = registry.RequestModuleInterface<ISimulationBase>();
}
public void FinishedStartup()
{
IMonitorModule monitor = m_simulationBase.ApplicationRegistry.RequestModuleInterface<IMonitorModule>();
if(monitor != null)
_assetMonitor = (IAssetMonitor)monitor.GetMonitor("", MonitorModuleHelper.AssetMonitor);
}
#endregion
#region IImprovedAssetCache
////////////////////////////////////////////////////////////
// IImprovedAssetCache
//
private void UpdateMemoryCache(string key, AssetBase asset)
{
UpdateMemoryCache(key, asset, false);
}
private void UpdateMemoryCache(string key, AssetBase asset, bool forceMemCache)
{
if (m_MemoryCacheEnabled || forceMemCache)
{
if (m_MemoryExpiration > TimeSpan.Zero)
{
m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration);
}
else
{
m_MemoryCache.AddOrUpdate(key, asset, m_DefaultMemoryExpiration);
}
}
}
public void Cache(string assetID, AssetBase asset)
{
if (asset != null)
{
UpdateMemoryCache(asset.IDString, asset);
string filename = GetFileName(asset.IDString);
try
{
// If the file is already cached just update access time
if (File.Exists(filename))
{
lock (m_CurrentlyWriting)
{
if (!m_CurrentlyWriting.Contains(filename))
File.SetLastAccessTime(filename, DateTime.Now);
}
}
else
{
// Once we start writing, make sure we flag that we're writing
// that object to the cache so that we don't try to write the
// same file multiple times.
lock (m_CurrentlyWriting)
{
#if WAIT_ON_INPROGRESS_REQUESTS
if (m_CurrentlyWriting.ContainsKey(filename))
{
return;
}
else
{
m_CurrentlyWriting.Add(filename, new ManualResetEvent(false));
}
#else
if (m_CurrentlyWriting.Contains(filename))
{
return;
}
else
{
m_CurrentlyWriting.Add(filename);
}
#endif
}
Util.FireAndForget(
delegate { WriteFileCache(filename, asset); });
}
}
catch (Exception e)
{
LogException(e);
}
}
else
{
if (m_assetRequests.ContainsKey(assetID))
m_assetRequests[assetID].SavedAmt++;
else
m_assetRequests[assetID] = new AssetRequest();
if (m_assetRequests[assetID].SavedAmt > _forceMemoryCacheAmount)
UpdateMemoryCache(assetID, asset, true);
}
}
public AssetBase Get(string id)
{
bool found;
return Get(id, out found);
}
public AssetBase Get(string id, out bool found)
{
if (m_assetRequests.ContainsKey(id))
m_assetRequests[id].Amt++;
else
m_assetRequests[id] = new AssetRequest();
m_Requests++;
AssetBase asset = null;
found = false;
bool forceMemCache = m_assetRequests[id].Amt > _forceMemoryCacheAmount;
if ((m_MemoryCacheEnabled || forceMemCache) && m_MemoryCache.TryGetValue(id, out asset))
{
found = true;
m_MemoryHits++;
}
else
{
string filename = GetFileName(id);
if (File.Exists(filename))
{
try
{
asset = ExtractAsset(id, asset, filename, forceMemCache);
found = true;
if (asset == null)
m_assetRequests[id].Amt = _forceMemoryCacheAmount;
}
catch (Exception e)
{
LogException(e);
// If there was a problem deserializing the asset, the asset may
// either be corrupted OR was serialized under an old format
// {different version of AssetBase} -- we should attempt to
// delete it and re-cache
File.Delete(filename);
}
}
#if WAIT_ON_INPROGRESS_REQUESTS
// Check if we're already downloading this asset. If so, try to wait for it to
// download.
if (m_WaitOnInprogressTimeout > 0)
{
m_RequestsForInprogress++;
ManualResetEvent waitEvent;
if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
{
waitEvent.WaitOne(m_WaitOnInprogressTimeout);
return Get(id);
}
}
#else
// Track how often we have the problem that an asset is requested while
// it is still being downloaded by a previous request.
if (m_CurrentlyWriting.Contains(filename))
{
m_RequestsForInprogress++;
}
#endif
}
if (((m_logLevel >= 1)) && (m_HitRateDisplay != 0) && (m_Requests % m_HitRateDisplay == 0))
{
m_HitRateFile = (double) m_DiskHits/m_Requests*100.0;
MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Get :: {0} :: {1}", id, asset == null ? "Miss" : "Hit");
MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE]: File Hit Rate {0}% for {1} requests",
m_HitRateFile.ToString("0.00"), m_Requests);
if (m_MemoryCacheEnabled)
{
m_HitRateMemory = (double) m_MemoryHits/m_Requests*100.0;
MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE]: Memory Hit Rate {0}% for {1} requests",
m_HitRateMemory.ToString("0.00"), m_Requests);
}
MainConsole.Instance.InfoFormat(
"[FLOTSAM ASSET CACHE]: {0} unnessesary requests due to requests for assets that are currently downloading.",
m_RequestsForInprogress);
}
if (_assetMonitor != null)
_assetMonitor.AddAsset(asset);
return asset;
}
private AssetBase ExtractAsset(string id, AssetBase asset, string filename, bool forceMemCache)
{
try
{
Stream s = File.Open(filename, FileMode.Open);
asset = ProtoBuf.Serializer.Deserialize<AssetBase>(s);
s.Close();
}
catch
{
}
UpdateMemoryCache(id, asset, asset == null ? true : forceMemCache);
m_DiskHits++;
return asset;
}
private static void InsertAsset(string filename, AssetBase asset, string directory, string tempname)
{
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
Stream s = File.Open(tempname, FileMode.OpenOrCreate);
ProtoBuf.Serializer.Serialize<AssetBase>(s, asset);
s.Close();
//File.WriteAllText(tempname, OpenMetaverse.StructuredData.OSDParser.SerializeJsonString(asset.ToOSD()));
// Now that it's written, rename it so that it can be found.
if (File.Exists(filename))
File.Delete(filename);
try
{
File.Move(tempname, filename);
}
catch
{
File.Delete(tempname);
}
}
public void Expire(string id)
{
if (m_logLevel >= 2)
MainConsole.Instance.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}.", id);
try
{
string filename = GetFileName(id);
lock (m_fileCacheLock)
{
if (File.Exists(filename))
File.Delete(filename);
}
if (m_MemoryCacheEnabled)
m_MemoryCache.Remove(id);
}
catch (Exception e)
{
LogException(e);
}
}
public void Clear()
{
if (m_logLevel >= 2)
MainConsole.Instance.Debug("[FLOTSAM ASSET CACHE]: Clearing Cache.");
lock (m_fileCacheLock)
{
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
Directory.Delete(dir, true);
}
}
if (m_MemoryCacheEnabled)
m_MemoryCache.Clear();
IAssetMonitor monitor =
(IAssetMonitor)
m_simulationBase.ApplicationRegistry.RequestModuleInterface<IMonitorModule>().GetMonitor("",
MonitorModuleHelper
.
AssetMonitor);
if (monitor != null)
{
monitor.ClearAssetCacheStatistics();
}
}
public bool Contains(string id)
{
return (m_MemoryCacheEnabled && m_MemoryCache.Contains(id)) || (File.Exists(GetFileName(id)));
}
private void CleanupExpiredFiles(object source, ElapsedEventArgs e)
{
if (m_logLevel >= 2)
MainConsole.Instance.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.",
m_FileExpiration.ToString());
// Purge all files last accessed prior to this point
DateTime purgeLine = DateTime.Now - m_FileExpiration;
// An optional deep scan at this point will ensure assets present in scenes,
// or referenced by objects in the scene, but not recently accessed
// are not purged.
if (m_DeepScanBeforePurge)
{
CacheScenes();
}
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
CleanExpiredFiles(dir, purgeLine);
}
}
/// <summary>
/// Recurses through specified directory checking for asset files last
/// accessed prior to the specified purge line and deletes them. Also
/// removes empty tier directories.
/// </summary>
/// <param name = "dir"></param>
private void CleanExpiredFiles(string dir, DateTime purgeLine)
{
foreach (string file in Directory.GetFiles(dir))
{
lock (m_fileCacheLock)
{
if (File.GetLastAccessTime(file) < purgeLine)
File.Delete(file);
}
}
// Recurse into lower tiers
foreach (string subdir in Directory.GetDirectories(dir))
{
CleanExpiredFiles(subdir, purgeLine);
}
lock (m_fileCacheLock)
{
// Check if a tier directory is empty, if so, delete it
int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length;
if (dirSize == 0)
Directory.Delete(dir);
else if (dirSize >= m_CacheWarnAt)
{
MainConsole.Instance.WarnFormat(
"[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration",
dir, dirSize);
}
}
}
/// <summary>
/// Determines the filename for an AssetID stored in the file cache
/// </summary>
/// <param name = "id"></param>
/// <returns></returns>
private string GetFileName(string id)
{
// Would it be faster to just hash the darn thing?
#if (!ISWIN)
foreach (char invalidChar in m_InvalidChars)
id = id.Replace(invalidChar, '_');
#else
id = m_InvalidChars.Aggregate(id, (current, c) => current.Replace(c, '_'));
#endif
string path = m_CacheDirectory;
for (int p = 1; p <= m_CacheDirectoryTiers; p++)
{
string pathPart = id.Substring((p - 1)*m_CacheDirectoryTierLen, m_CacheDirectoryTierLen);
path = Path.Combine(path, pathPart);
}
return Path.Combine(path, id);
}
/// <summary>
/// Writes a file to the file cache, creating any nessesary
/// tier directories along the way
/// </summary>
/// <param name = "filename"></param>
/// <param name = "asset"></param>
private void WriteFileCache(string filename, AssetBase asset)
{
Stream stream = null;
// Make sure the target cache directory exists
string directory = Path.GetDirectoryName(filename);
// Write file first to a temp name, so that it doesn't look
// like it's already cached while it's still writing.
if (directory != null)
{
string tempname = Path.Combine(directory, Path.GetRandomFileName());
try
{
lock (m_fileCacheLock)
{
InsertAsset(filename, asset, directory, tempname);
}
if (m_logLevel >= 2)
MainConsole.Instance.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID);
}
catch (Exception e)
{
LogException(e);
}
finally
{
if (stream != null)
stream.Close();
// Even if the write fails with an exception, we need to make sure
// that we release the lock on that file, otherwise it'll never get
// cached
lock (m_CurrentlyWriting)
{
#if WAIT_ON_INPROGRESS_REQUESTS
ManualResetEvent waitEvent;
if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
{
m_CurrentlyWriting.Remove(filename);
waitEvent.Set();
}
#else
if (m_CurrentlyWriting.Contains(filename))
m_CurrentlyWriting.Remove(filename);
#endif
}
}
}
}
private static void LogException(Exception e)
{
string[] text = e.ToString().Split(new[] {'\n'});
foreach (string t in text)
{
if(t.Trim() != "")
MainConsole.Instance.ErrorFormat("[FLOTSAM ASSET CACHE]: {0} ", t);
}
}
/// <summary>
/// Scan through the file cache, and return number of assets currently cached.
/// </summary>
/// <param name = "dir"></param>
/// <returns></returns>
private int GetFileCacheCount(string dir)
{
#if (!ISWIN)
int sum = 0;
foreach (string subdir in Directory.GetDirectories(dir))
sum += GetFileCacheCount(subdir);
return Directory.GetFiles(dir).Length + sum;
#else
return Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Sum(subdir => GetFileCacheCount(subdir));
#endif
}
/// <summary>
/// This notes the last time the Region had a deep asset scan performed on it.
/// </summary>
/// <param name = "RegionID"></param>
private void StampRegionStatusFile(UUID RegionID)
{
string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + RegionID.ToString() + ".fac");
lock (m_fileCacheLock)
{
if (!Directory.Exists(m_CacheDirectory))
Directory.CreateDirectory(m_CacheDirectory);
if (File.Exists(RegionCacheStatusFile))
{
File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
}
else
{
File.WriteAllText(RegionCacheStatusFile,
"Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
}
}
}
/// <summary>
/// Iterates through all Scenes, doing a deep scan through assets
/// to cache all assets present in the scene or referenced by assets
/// in the scene
/// </summary>
/// <returns></returns>
private int CacheScenes()
{
//Make sure this is not null
if (m_AssetService == null)
return 0;
Dictionary<UUID, AssetType> assets = new Dictionary<UUID, AssetType>();
SceneManager manager = m_simulationBase.ApplicationRegistry.RequestModuleInterface<SceneManager>();
if (manager != null)
{
UuidGatherer gatherer = new UuidGatherer(m_AssetService);
foreach (IScene s in manager.Scenes)
{
StampRegionStatusFile(s.RegionInfo.RegionID);
IScene s1 = s;
#if (!ISWIN)
s.ForEachSceneEntity(delegate(ISceneEntity e)
{
gatherer.GatherAssetUuids(e, assets, s1);
});
#else
s.ForEachSceneEntity(e => gatherer.GatherAssetUuids(e, assets, s1));
#endif
}
foreach (UUID assetID in assets.Keys)
{
string filename = GetFileName(assetID.ToString());
if (File.Exists(filename))
{
File.SetLastAccessTime(filename, DateTime.Now);
}
else
{
m_AssetService.Get(assetID.ToString());
}
}
}
return assets.Keys.Count;
}
/// <summary>
/// Deletes all cache contents
/// </summary>
private void ClearFileCache()
{
lock (m_fileCacheLock)
{
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
try
{
Directory.Delete(dir, true);
}
catch (Exception e)
{
LogException(e);
}
}
foreach (string file in Directory.GetFiles(m_CacheDirectory))
{
try
{
File.Delete(file);
}
catch (Exception e)
{
LogException(e);
}
}
}
}
#region Console Commands
private void HandleConsoleCommand(string[] cmdparams)
{
if (cmdparams.Length >= 2)
{
string cmd = cmdparams[1];
switch (cmd)
{
case "status":
MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE] Memory Cache : {0} assets", m_MemoryCache.Count);
int fileCount = GetFileCacheCount(m_CacheDirectory);
MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE] File Cache : {0} assets", fileCount);
foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac"))
{
MainConsole.Instance.Info("[FLOTSAM ASSET CACHE] Deep Scans were performed on the following regions:");
string RegionID = s.Remove(0, s.IndexOf("_")).Replace(".fac", "");
DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s);
MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE] Region: {0}, {1}", RegionID,
RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss"));
}
break;
case "clear":
if (cmdparams.Length < 3)
{
MainConsole.Instance.Warn("[FLOTSAM ASSET CACHE] Please specify memory and/or file cache.");
break;
}
foreach (string s in cmdparams)
{
if (s.ToLower() == "memory")
{
m_MemoryCache.Clear();
MainConsole.Instance.Info("[FLOTSAM ASSET CACHE] Memory cache cleared.");
}
else if (s.ToLower() == "file")
{
ClearFileCache();
MainConsole.Instance.Info("[FLOTSAM ASSET CACHE] File cache cleared.");
}
}
break;
case "assets":
MainConsole.Instance.Info("[FLOTSAM ASSET CACHE] Caching all assets, in all scenes.");
Util.FireAndForget(delegate
{
int assetsCached = CacheScenes();
MainConsole.Instance.InfoFormat(
"[FLOTSAM ASSET CACHE] Completed Scene Caching, {0} assets found.",
assetsCached);
});
break;
case "expire":
if (cmdparams.Length < 3)
{
MainConsole.Instance.InfoFormat(
"[FLOTSAM ASSET CACHE] Invalid parameters for Expire, please specify a valid date & time",
cmd);
break;
}
string s_expirationDate = "";
DateTime expirationDate;
s_expirationDate = cmdparams.Length > 3
? string.Join(" ", cmdparams, 2, cmdparams.Length - 2)
: cmdparams[2];
if (!DateTime.TryParse(s_expirationDate, out expirationDate))
{
MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE] {0} is not a valid date & time", cmd);
break;
}
CleanExpiredFiles(m_CacheDirectory, expirationDate);
break;
default:
MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE] Unknown command {0}", cmd);
break;
}
}
else if (cmdparams.Length == 1)
{
MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache status - Display cache status");
MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache clearmem - Remove all assets cached in memory");
MainConsole.Instance.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache clearfile - Remove all assets cached on disk");
MainConsole.Instance.InfoFormat(
"[FLOTSAM ASSET CACHE] flotsamcache cachescenes - Attempt a deep cache of all assets in all scenes");
MainConsole.Instance.InfoFormat(
"[FLOTSAM ASSET CACHE] flotsamcache <datetime> - Purge assets older then the specified date & time");
}
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using umbraco.BasePages;
using System.Xml;
using System.Xml.XPath;
using umbraco.BusinessLogic.Actions;
using ClientDependency.Core;
using umbraco.IO;
using System.Linq;
using System.Text;
using ClientDependency.Core.Controls;
using System.Text.RegularExpressions;
namespace umbraco.cms.presentation
{
/// <summary>
/// The back office rendering page
/// </summary>
public class _umbraco : UmbracoEnsuredPage
{
[Obsolete("This property is no longer used")]
protected umbWindow UmbWindow1;
protected System.Web.UI.WebControls.PlaceHolder bubbleText;
public string DefaultApp { get; private set; }
protected void Page_Load(object sender, System.EventArgs e)
{
var apps = this.getUser().Applications.ToList();
bool userHasAccesstodefaultApp = apps.Where(x => x.alias == Umbraco.Core.Constants.Applications.Content).Count() > 0;
// Load user module icons ..
if (apps.Count() > 1)
{
var JSEvents = new StringBuilder();
PlaceHolderAppIcons.Text = ui.Text("main", "sections", base.getUser());
plcIcons.Text = "";
foreach (BusinessLogic.Application a in apps.OrderBy(x => x.sortOrder))
{
string appClass = a.icon.StartsWith(".") ? a.icon.Substring(1, a.icon.Length - 1) : a.alias;
//adds client side event handlers to the icon buttons
JSEvents.Append(@"jQuery('." + appClass + "').click(function() { appClick.call(this, '" + a.alias + "'); } );");
JSEvents.Append(@"jQuery('." + appClass + "').dblclick(function() { appDblClick.call(this, '" + a.alias + "'); } );");
string iconElement = String.Format("<li><a class=\"{0}\" title=\"" + ui.Text("sections", a.alias, base.getUser()) + "\" href=\"javascript:void(0);\">", appClass);
if (a.icon.StartsWith("."))
iconElement +=
"<img src=\"images/nada.gif\" class=\"trayHolder\" alt=\"\" /></a></li>";
else
iconElement += "<img src=\"images/tray/" + a.icon + "\" class=\"trayIcon\" alt=\"" + ui.Text("sections", a.alias, base.getUser()) + "\"></a></li>";
plcIcons.Text += iconElement;
}
//registers the jquery event handlers.
Page.ClientScript.RegisterStartupScript(this.GetType(), "AppIcons", "jQuery(document).ready(function() { " + JSEvents.ToString() + " } );", true);
}
else
PlaceHolderAppIcons.Visible = false;
//if user does not have access to content (ie, he's probably a translator)...
//then change the default tree app
if (!userHasAccesstodefaultApp)
{
JTree.App = apps[0].alias;
DefaultApp = apps[0].alias;
}
else
{
DefaultApp = Umbraco.Core.Constants.Applications.Content;
}
// Load globalized labels
treeWindow.Text = ui.Text("main", "tree", base.getUser());
RenderActionJS();
// Version check goes here!
// zb-00004 #29956 : refactor cookies names & handling
var updChkCookie = new umbraco.BusinessLogic.StateHelper.Cookies.Cookie("UMB_UPDCHK", GlobalSettings.VersionCheckPeriod); // was "updateCheck"
string updateCheckCookie = updChkCookie.HasValue ? updChkCookie.GetValue() : "";
if (GlobalSettings.VersionCheckPeriod > 0 && String.IsNullOrEmpty(updateCheckCookie) && base.getUser().UserType.Alias == "admin")
{
// Add scriptmanager version check
ScriptManager sm = ScriptManager.GetCurrent(Page);
sm.Scripts.Add(new ScriptReference(SystemDirectories.Umbraco + "/js/umbracoUpgradeChecker.js"));
sm.Services.Add(new ServiceReference(SystemDirectories.Webservices + "/CheckForUpgrade.asmx"));
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "upgradeChecker", "jQuery(document).ready(function() {umbraco.presentation.webservices.CheckForUpgrade.CallUpgradeService(umbracoCheckUpgrade);});", true);
updChkCookie.SetValue("1");
}
DataBind();
AddIe9Meta();
}
private void AddIe9Meta()
{
if (Request.Browser.Browser == "IE" && Request.Browser.MajorVersion == 9)
{
StringBuilder metadata = new StringBuilder();
metadata.AppendFormat(
@"<link rel='icon' href='{0}' type='image/x-icon'>
<link rel='shortcut icon' href='{0}' type='image/x-icon'>
<meta name='application-name' content='Umbraco CMS - {1}' />
<meta name='msapplication-tooltip' content='Umbraco CMS - {1}' />
<meta name='msapplication-navbutton-color' content='#f36f21' />
<meta name='msapplication-starturl' content='./umbraco.aspx' />",
IOHelper.ResolveUrl(SystemDirectories.Umbraco + "/images/pinnedIcons/umb.ico"),
HttpContext.Current.Request.Url.Host.ToLower().Replace("www.", ""));
var user = base.getUser();
if (user != null && user.Applications != null && user.Applications.Length > 0)
{
foreach (var app in user.Applications)
{
metadata.AppendFormat(
@"<meta name='msapplication-task' content='name={0}; action-uri={1}; icon-uri={2}' />",
ui.Text("sections", app.alias, user),
IOHelper.ResolveUrl(string.Format("{0}/umbraco.aspx#{1}", SystemDirectories.Umbraco, app.alias)),
File.Exists(
IOHelper.MapPath(
IOHelper.ResolveUrl(
string.Format("{0}/images/pinnedIcons/task_{1}.ico", SystemDirectories.Umbraco, app.alias))))
? "/umbraco/images/pinnedIcons/task_" + app.alias + ".ico"
: "/umbraco/images/pinnedIcons/task_default.ico");
}
}
this.Header.Controls.Add(new LiteralControl(metadata.ToString()));
}
}
/// <summary>
/// Renders out all JavaScript references that have bee declared in IActions
/// </summary>
private void RenderActionJS()
{
var item = 0;
foreach (var jsFile in umbraco.BusinessLogic.Actions.Action.GetJavaScriptFileReferences())
{
//validate that this is a url, if it is not, we'll assume that it is a text block and render it as a text
//block instead.
var isValid = true;
try
{
var jsUrl = new Uri(jsFile, UriKind.RelativeOrAbsolute);
//ok it validates, but so does alert('hello'); ! so we need to do more checks
//here are the valid chars in a url without escaping
if (Regex.IsMatch(jsFile, @"[^a-zA-Z0-9-._~:/?#\[\]@!$&'\(\)*\+,%;=]"))
isValid = false;
//we'll have to be smarter and just check for certain js patterns now too!
var jsPatterns = new string[] { @"\+\s*\=", @"\);", @"function\s*\(", @"!=", @"==" };
foreach (var p in jsPatterns)
{
if (Regex.IsMatch(jsFile, p))
{
isValid = false;
break;
}
}
if (isValid)
{
//add to page
Page.ClientScript.RegisterClientScriptInclude(this.GetType(), item.ToString(), jsFile);
}
}
catch (UriFormatException)
{
isValid = false;
}
if (!isValid)
{
//it is invalid, let's render it as a script block instead as devs may have written real Javascript instead
//of a JS path
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), item.ToString(), jsFile, true);
}
item++;
}
}
/// <summary>
/// ClientLoader control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::umbraco.uicontrols.UmbracoClientDependencyLoader ClientLoader;
/// <summary>
/// CssInclude1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.CssInclude CssInclude1;
/// <summary>
/// CssInclude2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.CssInclude CssInclude2;
/// <summary>
/// JsInclude1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude1;
/// <summary>
/// JsInclude2 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude2;
/// <summary>
/// JsInclude3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude3;
/// <summary>
/// JsInclude14 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude14;
/// <summary>
/// JsInclude5 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude5;
/// <summary>
/// JsInclude6 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude6;
/// <summary>
/// JsInclude13 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude13;
/// <summary>
/// JsInclude7 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude7;
/// <summary>
/// JsInclude8 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude8;
/// <summary>
/// JsInclude9 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude9;
/// <summary>
/// JsInclude10 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude10;
/// <summary>
/// JsInclude11 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude11;
/// <summary>
/// JsInclude4 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude4;
/// <summary>
/// JsInclude17 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude17;
/// <summary>
/// JsInclude12 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude12;
/// <summary>
/// JsInclude15 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude15;
/// <summary>
/// JsInclude16 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::ClientDependency.Core.Controls.JsInclude JsInclude16;
/// <summary>
/// Form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm Form1;
/// <summary>
/// umbracoScriptManager control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.ScriptManager umbracoScriptManager;
/// <summary>
/// FindDocuments control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel FindDocuments;
/// <summary>
/// Search control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::umbraco.presentation.Search.QuickSearch Search;
/// <summary>
/// treeWindow control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::umbraco.uicontrols.UmbracoPanel treeWindow;
/// <summary>
/// JTree control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::umbraco.controls.Tree.TreeControl JTree;
/// <summary>
/// PlaceHolderAppIcons control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::umbraco.uicontrols.UmbracoPanel PlaceHolderAppIcons;
/// <summary>
/// plcIcons control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal plcIcons;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Xml;
using System.Xml.XPath;
namespace MS.Internal.Xml.XPath
{
internal sealed class XPathScanner
{
private string xpathExpr;
private int xpathExprIndex;
private LexKind kind;
private char currentChar;
private string name;
private string prefix;
private string stringValue;
private double numberValue = double.NaN;
private bool canBeFunction;
private XmlCharType xmlCharType = XmlCharType.Instance;
public XPathScanner(string xpathExpr)
{
if (xpathExpr == null)
{
throw XPathException.Create(SR.Xp_ExprExpected, string.Empty);
}
this.xpathExpr = xpathExpr;
NextChar();
NextLex();
}
public string SourceText { get { return this.xpathExpr; } }
private char CurrentChar { get { return currentChar; } }
private bool NextChar()
{
Debug.Assert(0 <= xpathExprIndex && xpathExprIndex <= xpathExpr.Length);
if (xpathExprIndex < xpathExpr.Length)
{
currentChar = xpathExpr[xpathExprIndex++];
return true;
}
else
{
currentChar = '\0';
return false;
}
}
#if XML10_FIFTH_EDITION
private char PeekNextChar()
{
Debug.Assert(0 <= xpathExprIndex && xpathExprIndex <= xpathExpr.Length);
if (xpathExprIndex < xpathExpr.Length)
{
return xpathExpr[xpathExprIndex];
}
else
{
Debug.Assert(xpathExprIndex == xpathExpr.Length);
return '\0';
}
}
#endif
public LexKind Kind { get { return this.kind; } }
public string Name
{
get
{
Debug.Assert(this.kind == LexKind.Name || this.kind == LexKind.Axe);
Debug.Assert(this.name != null);
return this.name;
}
}
public string Prefix
{
get
{
Debug.Assert(this.kind == LexKind.Name);
Debug.Assert(this.prefix != null);
return this.prefix;
}
}
public string StringValue
{
get
{
Debug.Assert(this.kind == LexKind.String);
Debug.Assert(this.stringValue != null);
return this.stringValue;
}
}
public double NumberValue
{
get
{
Debug.Assert(this.kind == LexKind.Number);
Debug.Assert(!double.IsNaN(this.numberValue));
return this.numberValue;
}
}
// To parse PathExpr we need a way to distinct name from function.
// THis distinction can't be done without context: "or (1 != 0)" this this a function or 'or' in OrExp
public bool CanBeFunction
{
get
{
Debug.Assert(this.kind == LexKind.Name);
return this.canBeFunction;
}
}
void SkipSpace()
{
while (xmlCharType.IsWhiteSpace(this.CurrentChar) && NextChar()) ;
}
public bool NextLex()
{
SkipSpace();
switch (this.CurrentChar)
{
case '\0':
kind = LexKind.Eof;
return false;
case ',':
case '@':
case '(':
case ')':
case '|':
case '*':
case '[':
case ']':
case '+':
case '-':
case '=':
case '#':
case '$':
kind = (LexKind)Convert.ToInt32(this.CurrentChar, CultureInfo.InvariantCulture);
NextChar();
break;
case '<':
kind = LexKind.Lt;
NextChar();
if (this.CurrentChar == '=')
{
kind = LexKind.Le;
NextChar();
}
break;
case '>':
kind = LexKind.Gt;
NextChar();
if (this.CurrentChar == '=')
{
kind = LexKind.Ge;
NextChar();
}
break;
case '!':
kind = LexKind.Bang;
NextChar();
if (this.CurrentChar == '=')
{
kind = LexKind.Ne;
NextChar();
}
break;
case '.':
kind = LexKind.Dot;
NextChar();
if (this.CurrentChar == '.')
{
kind = LexKind.DotDot;
NextChar();
}
else if (XmlCharType.IsDigit(this.CurrentChar))
{
kind = LexKind.Number;
numberValue = ScanFraction();
}
break;
case '/':
kind = LexKind.Slash;
NextChar();
if (this.CurrentChar == '/')
{
kind = LexKind.SlashSlash;
NextChar();
}
break;
case '"':
case '\'':
this.kind = LexKind.String;
this.stringValue = ScanString();
break;
default:
if (XmlCharType.IsDigit(this.CurrentChar))
{
kind = LexKind.Number;
numberValue = ScanNumber();
}
else if (xmlCharType.IsStartNCNameSingleChar(this.CurrentChar)
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar)
#endif
)
{
kind = LexKind.Name;
this.name = ScanName();
this.prefix = string.Empty;
// "foo:bar" is one lexem not three because it doesn't allow spaces in between
// We should distinct it from "foo::" and need process "foo ::" as well
if (this.CurrentChar == ':')
{
NextChar();
// can be "foo:bar" or "foo::"
if (this.CurrentChar == ':')
{ // "foo::"
NextChar();
kind = LexKind.Axe;
}
else
{ // "foo:*", "foo:bar" or "foo: "
this.prefix = this.name;
if (this.CurrentChar == '*')
{
NextChar();
this.name = "*";
}
else if (xmlCharType.IsStartNCNameSingleChar(this.CurrentChar)
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar)
#endif
)
{
this.name = ScanName();
}
else
{
throw XPathException.Create(SR.Xp_InvalidName, SourceText);
}
}
}
else
{
SkipSpace();
if (this.CurrentChar == ':')
{
NextChar();
// it can be "foo ::" or just "foo :"
if (this.CurrentChar == ':')
{
NextChar();
kind = LexKind.Axe;
}
else
{
throw XPathException.Create(SR.Xp_InvalidName, SourceText);
}
}
}
SkipSpace();
this.canBeFunction = (this.CurrentChar == '(');
}
else
{
throw XPathException.Create(SR.Xp_InvalidToken, SourceText);
}
break;
}
return true;
}
private double ScanNumber()
{
Debug.Assert(this.CurrentChar == '.' || XmlCharType.IsDigit(this.CurrentChar));
int start = xpathExprIndex - 1;
int len = 0;
while (XmlCharType.IsDigit(this.CurrentChar))
{
NextChar(); len++;
}
if (this.CurrentChar == '.')
{
NextChar(); len++;
while (XmlCharType.IsDigit(this.CurrentChar))
{
NextChar(); len++;
}
}
return XmlConvertEx.ToXPathDouble(this.xpathExpr.Substring(start, len));
}
private double ScanFraction()
{
Debug.Assert(XmlCharType.IsDigit(this.CurrentChar));
int start = xpathExprIndex - 2;
Debug.Assert(0 <= start && this.xpathExpr[start] == '.');
int len = 1; // '.'
while (XmlCharType.IsDigit(this.CurrentChar))
{
NextChar(); len++;
}
return XmlConvertEx.ToXPathDouble(this.xpathExpr.Substring(start, len));
}
private string ScanString()
{
char endChar = this.CurrentChar;
NextChar();
int start = xpathExprIndex - 1;
int len = 0;
while (this.CurrentChar != endChar)
{
if (!NextChar())
{
throw XPathException.Create(SR.Xp_UnclosedString);
}
len++;
}
Debug.Assert(this.CurrentChar == endChar);
NextChar();
return this.xpathExpr.Substring(start, len);
}
private string ScanName()
{
Debug.Assert(xmlCharType.IsStartNCNameSingleChar(this.CurrentChar)
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar)
#endif
);
int start = xpathExprIndex - 1;
int len = 0;
for (; ;)
{
if (xmlCharType.IsNCNameSingleChar(this.CurrentChar))
{
NextChar();
len++;
}
#if XML10_FIFTH_EDITION
else if (xmlCharType.IsNCNameSurrogateChar(this.PeekNextChar(), this.CurerntChar))
{
NextChar();
NextChar();
len += 2;
}
#endif
else
{
break;
}
}
return this.xpathExpr.Substring(start, len);
}
public enum LexKind
{
Comma = ',',
Slash = '/',
At = '@',
Dot = '.',
LParens = '(',
RParens = ')',
LBracket = '[',
RBracket = ']',
Star = '*',
Plus = '+',
Minus = '-',
Eq = '=',
Lt = '<',
Gt = '>',
Bang = '!',
Dollar = '$',
Apos = '\'',
Quote = '"',
Union = '|',
Ne = 'N', // !=
Le = 'L', // <=
Ge = 'G', // >=
And = 'A', // &&
Or = 'O', // ||
DotDot = 'D', // ..
SlashSlash = 'S', // //
Name = 'n', // XML _Name
String = 's', // Quoted string constant
Number = 'd', // _Number constant
Axe = 'a', // Axe (like child::)
Eof = 'E',
};
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.LayoutRenderers
{
using System;
using System.Collections.Generic;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using NLog.Internal;
using Xunit;
using NLog.Config;
public class ExceptionTests : NLogTestBase
{
const int E_FAIL = 80004005;
private ILogger logger = LogManager.GetLogger("NLog.UnitTests.LayoutRenderer.ExceptionTests");
private const string ExceptionDataFormat = "{0}: {1}";
[Fact]
public void ExceptionWithStackTrace_ObsoleteMethodTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
<target name='debug10' type='Debug' layout='${exception:format=source}' />
<target name='debug11' type='Debug' layout='${exception:format=hresult}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9,debug10,debug11' />
</rules>
</nlog>");
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
#pragma warning restore 0618
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", ex.StackTrace);
AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName);
AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
AssertDebugLastMessage("debug10", GetType().ToString());
#if NET4_5
AssertDebugLastMessage("debug11", $"0x{E_FAIL:X8}");
#endif
// each version of the framework produces slightly different information for MethodInfo, so we just
// make sure it's not empty
var debug7Target = (DebugTarget)LogManager.Configuration.FindTargetByName("debug7");
Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage));
AssertDebugLastMessage("debug8", "Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionWithStackTraceTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
<target name='debug10' type='Debug' layout='${exception:format=source}' />
<target name='debug11' type='Debug' layout='${exception:format=hresult}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9,debug10,debug11' />
</rules>
</nlog>");
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", ex.StackTrace);
AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName);
AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
AssertDebugLastMessage("debug10", GetType().ToString());
#if NET4_5
AssertDebugLastMessage("debug11", $"0x{E_FAIL:X8}");
#endif
// each version of the framework produces slightly different information for MethodInfo, so we just
// make sure it's not empty
var debug7Target = (DebugTarget)LogManager.Configuration.FindTargetByName("debug7");
Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage));
AssertDebugLastMessage("debug8", exceptionMessage + "*" + typeof(CustomArgumentException).Name);
}
/// <summary>
/// Just wrrite exception, no message argument.
/// </summary>
[Fact]
public void ExceptionWithoutMessageParam()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
<target name='debug10' type='Debug' layout='${exception:format=source}' />
<target name='debug11' type='Debug' layout='${exception:format=hresult}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9,debug10,debug11' />
</rules>
</nlog>");
const string exceptionMessage = "I don't like nullref exception!";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex);
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", ex.StackTrace);
AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName);
AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
AssertDebugLastMessage("debug10", GetType().ToString());
#if NET4_5
AssertDebugLastMessage("debug11", $"0x{E_FAIL:X8}");
#endif
// each version of the framework produces slightly different information for MethodInfo, so we just
// make sure it's not empty
var debug7Target = (DebugTarget)LogManager.Configuration.FindTargetByName("debug7");
Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage));
AssertDebugLastMessage("debug8", exceptionMessage + "*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionWithoutStackTrace_ObsoleteMethodTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
<target name='debug10' type='Debug' layout='${exception:format=source}' />
<target name='debug11' type='Debug' layout='${exception:format=hresult}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9,debug10,debug11' />
</rules>
</nlog>");
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
#pragma warning restore 0618
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", "");
AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName);
AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug7", "");
AssertDebugLastMessage("debug8", "Test exception*" + typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
AssertDebugLastMessage("debug10", "");
#if NET4_5
AssertDebugLastMessage("debug11", $"0x{E_FAIL:X8}");
#endif
}
[Fact]
public void ExceptionWithoutStackTraceTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
<target name='debug10' type='Debug' layout='${exception:format=source}' />
<target name='debug11' type='Debug' layout='${exception:format=hresult}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9,debug10,debug11' />
</rules>
</nlog>");
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", "");
AssertDebugLastMessage("debug3", typeof(CustomArgumentException).FullName);
AssertDebugLastMessage("debug4", typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug7", "");
AssertDebugLastMessage("debug8", "Test exception*" + typeof(CustomArgumentException).Name);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
AssertDebugLastMessage("debug10", "");
#if NET4_5
AssertDebugLastMessage("debug11", $"0x{E_FAIL:X8}");
#endif
}
[Fact]
public void ExceptionNewLineSeparatorTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=message,shorttype:separator= }' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
AssertDebugLastMessage("debug1", "Test exception\r\n" + typeof(CustomArgumentException).Name);
#pragma warning restore 0618
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "Test exception\r\n" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingLogMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Log(LogLevel.Error, ex, "msg");
AssertDebugLastMessage("debug1", "ERROR*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Log(LogLevel.Error, ex, () => "msg func");
AssertDebugLastMessage("debug1", "ERROR*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingTraceMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Trace(ex, "msg");
AssertDebugLastMessage("debug1", "TRACE*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Trace(ex, () => "msg func");
AssertDebugLastMessage("debug1", "TRACE*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingDebugMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Debug(ex, "msg");
AssertDebugLastMessage("debug1", "DEBUG*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Debug(ex, () => "msg func");
AssertDebugLastMessage("debug1", "DEBUG*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingInfoMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Info(ex, "msg");
AssertDebugLastMessage("debug1", "INFO*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Info(ex, () => "msg func");
AssertDebugLastMessage("debug1", "INFO*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingWarnMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Warn(ex, "msg");
AssertDebugLastMessage("debug1", "WARN*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Warn(ex, () => "msg func");
AssertDebugLastMessage("debug1", "WARN*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingErrorMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "ERROR*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Error(ex, () => "msg func");
AssertDebugLastMessage("debug1", "ERROR*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void ExceptionUsingFatalMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Fatal(ex, "msg");
AssertDebugLastMessage("debug1", "FATAL*msg*Test exception*" + typeof(CustomArgumentException).Name);
logger.Fatal(ex, () => "msg func");
AssertDebugLastMessage("debug1", "FATAL*msg func*Test exception*" + typeof(CustomArgumentException).Name);
}
[Fact]
public void InnerExceptionTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=3}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
string exceptionMessage = "Test exception";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
AssertDebugLastMessage("debug1", "ApplicationException Wrapper2" + EnvironmentHelper.NewLine +
"ArgumentException Wrapper1" + EnvironmentHelper.NewLine +
"CustomArgumentException Test exception");
#pragma warning restore 0618
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "ApplicationException Wrapper2" + EnvironmentHelper.NewLine +
"ArgumentException Wrapper1" + EnvironmentHelper.NewLine +
"CustomArgumentException Test exception");
}
[Fact]
public void InnerExceptionTest_Serialize()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=@}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
string exceptionMessage = "Test exception";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
var lastMessage1 = GetDebugLastMessage("debug1");
Assert.StartsWith("{\"Type\":\"System.ApplicationException\", \"Message\":\"Wrapper2\"", lastMessage1);
Assert.Contains("\"InnerException\":{\"Type\":\"System.ArgumentException\", \"Message\":\"Wrapper1\"", lastMessage1);
Assert.Contains("\"ParamName\":\"exceptionMessage\"", lastMessage1);
Assert.Contains("1Really_Bad_Boy_", lastMessage1);
#pragma warning restore 0618
logger.Error(ex, "msg");
var lastMessage2 = GetDebugLastMessage("debug1");
Assert.StartsWith("{\"Type\":\"System.ApplicationException\", \"Message\":\"Wrapper2\"", lastMessage2);
Assert.Contains("\"InnerException\":{\"Type\":\"System.ArgumentException\", \"Message\":\"Wrapper1\"", lastMessage2);
Assert.Contains("\"ParamName\":\"exceptionMessage\"", lastMessage2);
Assert.Contains("1Really_Bad_Boy_", lastMessage1);
}
[Fact]
public void CustomInnerException_ObsoleteMethodTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message}' />
<target name='debug2' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message,data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
<logger minlevel='Info' writeTo='debug2' />
</rules>
</nlog>");
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer;
Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator);
string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
#pragma warning restore 0618
AssertDebugLastMessage("debug1", "ApplicationException Wrapper2" +
"\r\n----INNER----\r\n" +
"System.ArgumentException Wrapper1");
AssertDebugLastMessage("debug2", string.Format("ApplicationException Wrapper2" +
"\r\n----INNER----\r\n" +
"System.ArgumentException Wrapper1 " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
}
[Fact]
public void CustomInnerExceptionTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message}' />
<target name='debug2' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message,data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
<logger minlevel='Info' writeTo='debug2' />
</rules>
</nlog>");
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer;
Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator);
string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "ApplicationException Wrapper2" +
"\r\n----INNER----\r\n" +
"System.ArgumentException Wrapper1");
AssertDebugLastMessage("debug2", string.Format("ApplicationException Wrapper2" +
"\r\n----INNER----\r\n" +
"System.ArgumentException Wrapper1 " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
}
[Fact]
public void ErrorException_should_not_throw_exception_when_exception_message_property_throw_exception()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
var ex = new ExceptionWithBrokenMessagePropertyException();
var exRecorded = Record.Exception(() => logger.Error(ex, "msg"));
Assert.Null(exRecorded);
}
[Fact]
public void ErrorException_should_not_throw_exception_when_exception_message_property_throw_exception_serialize()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=@}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
var ex = new ExceptionWithBrokenMessagePropertyException();
var exRecorded = Record.Exception(() => logger.Error(ex, "msg"));
Assert.Null(exRecorded);
}
#if NET3_5
[Fact(Skip = "NET3_5 not supporting AggregateException")]
#else
[Fact]
#endif
public void AggregateExceptionMultiTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=5}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
var task1 = System.Threading.Tasks.Task.Factory.StartNew(() => { throw new Exception("Test exception 1", new Exception("Test Inner 1")); },
System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default);
var task2 = System.Threading.Tasks.Task.Factory.StartNew(() => { throw new Exception("Test exception 2", new Exception("Test Inner 2")); },
System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default);
var aggregateExceptionMessage = "nothing thrown!";
try
{
System.Threading.Tasks.Task.WaitAll(new[] { task1, task2 });
}
catch (AggregateException ex)
{
aggregateExceptionMessage = ex.ToString();
logger.Error(ex, "msg");
}
Assert.Contains("Test exception 1", aggregateExceptionMessage);
Assert.Contains("Test exception 2", aggregateExceptionMessage);
Assert.Contains("Test Inner 1", aggregateExceptionMessage);
Assert.Contains("Test Inner 2", aggregateExceptionMessage);
AssertDebugLastMessageContains("debug1", "AggregateException");
AssertDebugLastMessageContains("debug1", "One or more errors occurred");
AssertDebugLastMessageContains("debug1", "Test exception 1");
AssertDebugLastMessageContains("debug1", "Test exception 2");
AssertDebugLastMessageContains("debug1", "Test Inner 1");
AssertDebugLastMessageContains("debug1", "Test Inner 2");
}
#if NET3_5
[Fact(Skip = "NET3_5 not supporting AggregateException")]
#else
[Fact]
#endif
public void AggregateExceptionSingleTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=message,shorttype:maxInnerExceptionLevel=5}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
var task1 = System.Threading.Tasks.Task.Factory.StartNew(() => { throw new Exception("Test exception 1", new Exception("Test Inner 1")); },
System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default);
var aggregateExceptionMessage = "nothing thrown!";
try
{
System.Threading.Tasks.Task.WaitAll(new[] { task1 });
}
catch (AggregateException ex)
{
aggregateExceptionMessage = ex.ToString();
logger.Error(ex, "msg");
}
Assert.Contains(typeof(AggregateException).Name, aggregateExceptionMessage);
Assert.Contains("Test exception 1", aggregateExceptionMessage);
Assert.Contains("Test Inner 1", aggregateExceptionMessage);
var lastMessage = GetDebugLastMessage("debug1");
Assert.StartsWith("Test exception 1", lastMessage);
Assert.Contains("Test Inner 1", lastMessage);
}
[Fact]
public void CustomExceptionProperties_Layout_Test()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=Properties}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
var ex = new CustomArgumentException("Goodbye World", "Nuke");
logger.Fatal(ex, "msg");
AssertDebugLastMessage("debug1", $"{nameof(CustomArgumentException.ParamName)}: Nuke");
}
private class ExceptionWithBrokenMessagePropertyException : NLogConfigurationException
{
public override string Message => throw new Exception("Exception from Message property");
}
private void SetConfigurationForExceptionUsingRootMethodTests()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${level:uppercase=true}*${message}*${exception:format=message,shorttype:separator=*}' />
</targets>
<rules>
<logger minlevel='Trace' writeTo='debug1' />
</rules>
</nlog>");
}
/// <summary>
/// Get an exception with stacktrace by generating a exception
/// </summary>
/// <param name="exceptionMessage"></param>
/// <returns></returns>
private Exception GetExceptionWithStackTrace(string exceptionMessage)
{
try
{
GenericClass<int, string, bool>.Method1("aaa", true, null, 42, DateTime.Now, exceptionMessage);
return null;
}
catch (Exception exception)
{
exception.Source = GetType().ToString();
return exception;
}
}
private Exception GetNestedExceptionWithStackTrace(string exceptionMessage)
{
try
{
try
{
try
{
GenericClass<int, string, bool>.Method1("aaa", true, null, 42, DateTime.Now, exceptionMessage);
}
catch (Exception exception)
{
throw new System.ArgumentException("Wrapper1", exception);
}
}
catch (Exception exception)
{
throw new ApplicationException("Wrapper2", exception);
}
return null;
}
catch (Exception ex)
{
ex.Data["1Really.Bad-Boy!"] = "Hello World";
return ex;
}
}
private Exception GetExceptionWithoutStackTrace(string exceptionMessage)
{
return new CustomArgumentException(exceptionMessage, "exceptionMessage");
}
private class GenericClass<TA, TB, TC>
{
internal static List<GenericClass<TA, TB, TC>> Method1(string aaa, bool b, object o, int i, DateTime now, string exceptionMessage)
{
Method2(aaa, b, o, i, now, null, null, exceptionMessage);
return null;
}
internal static int Method2<T1, T2, T3>(T1 aaa, T2 b, T3 o, int i, DateTime now, Nullable<int> gfff, List<int>[] something, string exceptionMessage)
{
throw new CustomArgumentException(exceptionMessage, "exceptionMessage");
}
}
public class CustomArgumentException : ApplicationException
{
public CustomArgumentException(string message, string paramName)
:base(message)
{
ParamName = paramName;
StrangeProperty = "Strange World";
HResult = E_FAIL;
}
public string ParamName { get; }
public string StrangeProperty { private get; set; }
}
[Fact]
public void ExcpetionTestAPI()
{
var config = new LoggingConfiguration();
var debugTarget = new DebugTarget();
config.AddTarget("debug1", debugTarget);
debugTarget.Layout = @"${exception:format=shorttype,message:maxInnerExceptionLevel=3}";
var rule = new LoggingRule("*", LogLevel.Info, debugTarget);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
string exceptionMessage = "Test exception";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
AssertDebugLastMessage("debug1", "ApplicationException Wrapper2" + EnvironmentHelper.NewLine +
"ArgumentException Wrapper1" + EnvironmentHelper.NewLine +
"CustomArgumentException Test exception");
#pragma warning restore 0618
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "ApplicationException Wrapper2" + EnvironmentHelper.NewLine +
"ArgumentException Wrapper1" + EnvironmentHelper.NewLine +
"CustomArgumentException Test exception");
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer;
Assert.Equal(ExceptionRenderingFormat.ShortType, elr.Formats[0]);
Assert.Equal(ExceptionRenderingFormat.Message, elr.Formats[1]);
}
[Fact]
public void InnerExceptionTestAPI()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=3:innerFormat=message}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
string exceptionMessage = "Test exception";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
AssertDebugLastMessage("debug1", "ApplicationException Wrapper2" + EnvironmentHelper.NewLine +
"Wrapper1" + EnvironmentHelper.NewLine +
"Test exception");
#pragma warning restore 0618
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "ApplicationException Wrapper2" + EnvironmentHelper.NewLine +
"Wrapper1" + EnvironmentHelper.NewLine +
"Test exception");
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer;
Assert.Equal(ExceptionRenderingFormat.ShortType, elr.Formats[0]);
Assert.Equal(ExceptionRenderingFormat.Message, elr.Formats[1]);
Assert.Equal(ExceptionRenderingFormat.Message, elr.InnerFormats[0]);
}
[Fact]
public void CustomExceptionLayoutRendrerInnerExceptionTest()
{
ConfigurationItemFactory.Default.LayoutRenderers.RegisterDefinition("exception-custom", typeof(CustomExceptionLayoutRendrer));
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception-custom:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message}' />
<target name='debug2' type='Debug' layout='${exception-custom:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message,data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
<logger minlevel='Info' writeTo='debug2' />
</rules>
</nlog>");
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var elr = ((SimpleLayout)t.Layout).Renderers[0] as CustomExceptionLayoutRendrer;
Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator);
string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "ApplicationException Wrapper2" + "\r\ncustom-exception-renderer" +
"\r\n----INNER----\r\n" +
"System.ArgumentException Wrapper1" + "\r\ncustom-exception-renderer");
AssertDebugLastMessage("debug2", string.Format("ApplicationException Wrapper2" + "\r\ncustom-exception-renderer" +
"\r\n----INNER----\r\n" +
"System.ArgumentException Wrapper1" + "\r\ncustom-exception-renderer " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue + "\r\ncustom-exception-renderer-data"));
}
[Fact]
public void ExceptionDataWithDifferentSeparators()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=data}' />
<target name='debug2' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=*}' />
<target name='debug3' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=## **}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1, debug2, debug3' />
</rules>
</nlog>");
const string defaultExceptionDataSeparator = ";";
const string exceptionMessage = "message for exception";
const string exceptionDataKey1 = "testkey1";
const string exceptionDataValue1 = "testvalue1";
const string exceptionDataKey2 = "testkey2";
const string exceptionDataValue2 = "testvalue2";
var target = (DebugTarget)LogManager.Configuration.AllTargets[0];
var exceptionLayoutRenderer = ((SimpleLayout)target.Layout).Renderers[0] as ExceptionLayoutRenderer;
Assert.NotNull(exceptionLayoutRenderer);
Assert.Equal(defaultExceptionDataSeparator, exceptionLayoutRenderer.ExceptionDataSeparator);
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey1, exceptionDataValue1);
ex.Data.Add(exceptionDataKey2, exceptionDataValue2);
logger.Error(ex);
AssertDebugLastMessage("debug1", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + defaultExceptionDataSeparator + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2));
AssertDebugLastMessage("debug2", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "*" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2));
AssertDebugLastMessage("debug3", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "## **" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2));
}
[Fact]
public void ExceptionDataWithNewLineSeparator()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=\r\n}' />
<target name='debug2' type='Debug' layout='${exception:format=data:ExceptionDataSeparator=\r\n----DATA----\r\n}' />
<target name='debug3' type='Debug' layout='${exception:format=data:ExceptionDataSeparator= ----DATA---- }' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1, debug2, debug3' />
</rules>
</nlog>");
const string exceptionMessage = "message for exception";
const string exceptionDataKey1 = "testkey1";
const string exceptionDataValue1 = "testvalue1";
const string exceptionDataKey2 = "testkey2";
const string exceptionDataValue2 = "testvalue2";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey1, exceptionDataValue1);
ex.Data.Add(exceptionDataKey2, exceptionDataValue2);
logger.Error(ex);
AssertDebugLastMessage("debug1", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "\r\n" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2));
AssertDebugLastMessage("debug2", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "\r\n----DATA----\r\n" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2));
AssertDebugLastMessage("debug3", string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) + "\r\n----DATA----\r\n" + string.Format(ExceptionDataFormat, exceptionDataKey2, exceptionDataValue2));
}
[Fact]
public void ExceptionWithSeparatorForExistingRender()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=tostring,data:separator=\r\nXXX}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
const string exceptionMessage = "message for exception";
const string exceptionDataKey1 = "testkey1";
const string exceptionDataValue1 = "testvalue1";
Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey1, exceptionDataValue1);
logger.Error(ex);
AssertDebugLastMessage("debug1", string.Format(ExceptionDataFormat, ex.GetType().FullName, exceptionMessage) + "\r\nXXX" + string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1));
}
[Fact]
public void ExceptionWithSeparatorForExistingBetweenRender()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=tostring,data,type:separator=\r\nXXX}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
const string exceptionMessage = "message for exception";
const string exceptionDataKey1 = "testkey1";
const string exceptionDataValue1 = "testvalue1";
Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey1, exceptionDataValue1);
logger.Error(ex);
AssertDebugLastMessage(
"debug1",
string.Format(ExceptionDataFormat, ex.GetType().FullName, exceptionMessage) +
"\r\nXXX" +
string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1) +
"\r\nXXX" +
ex.GetType().FullName);
}
[Fact]
public void ExceptionWithoutSeparatorForNoRender()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=tostring,data:separator=\r\nXXX}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
const string exceptionMessage = "message for exception";
Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);
logger.Error(ex);
AssertDebugLastMessage("debug1", string.Format(ExceptionDataFormat, ex.GetType().FullName, exceptionMessage));
}
[Fact]
public void ExceptionWithoutSeparatorForNoBetweenRender()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=tostring,data,type:separator=\r\nXXX}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
const string exceptionMessage = "message for exception";
Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);
logger.Error(ex);
AssertDebugLastMessage(
"debug1",
string.Format(ExceptionDataFormat, ex.GetType().FullName, exceptionMessage) +
"\r\nXXX" +
ex.GetType().FullName);
}
}
[LayoutRenderer("exception-custom")]
[ThreadAgnostic]
public class CustomExceptionLayoutRendrer : ExceptionLayoutRenderer
{
protected override void AppendMessage(System.Text.StringBuilder sb, Exception ex)
{
base.AppendMessage(sb, ex);
sb.Append("\r\ncustom-exception-renderer");
}
protected override void AppendData(System.Text.StringBuilder sb, Exception ex)
{
base.AppendData(sb, ex);
sb.Append("\r\ncustom-exception-renderer-data");
}
}
}
| |
// 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.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class ReliabilityTestSet
{
private int _maximumTestLoops = 0; // default run based on time.
private int _maximumExecutionTime = 60; // 60 minute run by default.
private int _percentPassIsPass = System.Environment.GetEnvironmentVariable("PERCENTPASSISPASS") == null ? -1 : Convert.ToInt32(System.Environment.GetEnvironmentVariable("PERCENTPASSISPASS"));
private int[] _minPercentCPUStaggered_times = null;
private int[] _minPercentCPUStaggered_usage = null;
private int _minimumCPUpercent = 0,_minimumMemoryPercent = 0,_minimumTestsRunning = 0,_maximumTestsRunning = -1; // minimum CPU & memory requirements.
private ReliabilityTest[] _tests;
private string[] _discoveryPaths = null;
private string _friendlyName;
private bool _enablePerfCounters = true,_disableLogging = false,_installDetours = false;
private bool _suppressConsoleOutputFromTests = false;
private bool _debugBreakOnTestHang = true;
private bool _debugBreakOnBadTest = false;
private bool _debugBreakOnOutOfMemory = false;
private bool _debugBreakOnPathTooLong = false;
private bool _debugBreakOnMissingTest = false;
private TestStartModeEnum _testStartMode = TestStartModeEnum.AppDomainLoader;
private string _defaultDebugger,_defaultDebuggerOptions;
private int _ulGeneralUnloadPercent = 0,_ulAppDomainUnloadPercent = 0,_ulAssemblyLoadPercent = 0,_ulWaitTime = 0;
private bool _reportResults = false;
private string _reportResultsTo = "http://clrqa/SmartAPI/result.asmx";
private Guid _bvtCategory = Guid.Empty;
private string _ccFailMail;
private AppDomainLoaderMode _adLoaderMode = AppDomainLoaderMode.Normal;
private AssemblyLoadContextLoaderMode _alcLoaderMode = AssemblyLoadContextLoaderMode.Normal;
private int _numAppDomains = 10; //used for roundRobin scheduling, our app domain index
private int _numAssemblyLoadContexts = 10; //used for roundRobin scheduling, our AssemblyLoadContext index
private Random _rand = new Random();
private LoggingLevels _loggingLevel = LoggingLevels.All; // by default log everything
public ReliabilityTest[] Tests
{
get
{
return (_tests);
}
set
{
_tests = value;
}
}
public int MaximumLoops
{
get
{
return (_maximumTestLoops);
}
set
{
_maximumTestLoops = value;
}
}
public LoggingLevels LoggingLevel
{
get
{
return (_loggingLevel);
}
set
{
_loggingLevel = value;
}
}
/// <summary>
/// Maximum execution time, in minutes.
/// </summary>
public int MaximumTime
{
get
{
return (_maximumExecutionTime);
}
set
{
_maximumExecutionTime = value;
}
}
public string FriendlyName
{
get
{
return (_friendlyName);
}
set
{
_friendlyName = value;
}
}
public string[] DiscoveryPaths
{
get
{
return (_discoveryPaths);
}
set
{
_discoveryPaths = value;
}
}
public int MinPercentCPU
{
get
{
return (_minimumCPUpercent);
}
set
{
_minimumCPUpercent = value;
}
}
public int GetCurrentMinPercentCPU(TimeSpan timeRunning)
{
if (_minPercentCPUStaggered_usage == null)
{
return (MinPercentCPU);
}
int curCpu = _minPercentCPUStaggered_usage[0];
int curTime = 0;
for (int i = 1; i < _minPercentCPUStaggered_usage.Length; i++)
{
curTime += _minPercentCPUStaggered_times[i - 1];
if (curTime > timeRunning.TotalMinutes)
{
// we're in this time zone, return our current cpu
return (curCpu);
}
// we're in a later time zone, keep looking...
curCpu = _minPercentCPUStaggered_usage[i];
}
return (curCpu);
}
public string MinPercentCPUStaggered
{
set
{
string[] minPercentCPUStaggered = value.Split(';');
_minPercentCPUStaggered_times = new int[minPercentCPUStaggered.Length];
_minPercentCPUStaggered_usage = new int[minPercentCPUStaggered.Length];
for (int i = 0; i < minPercentCPUStaggered.Length; i++)
{
string[] split = minPercentCPUStaggered[i].Split(':');
string time = split[0];
string usage = split[1];
_minPercentCPUStaggered_times[i] = GetValue(time);
_minPercentCPUStaggered_usage[i] = GetValue(usage);
}
}
}
/// <summary>
/// Gets the integer value or the random value specified in the string.
/// accepted format:
/// 30:50 run for 30 minutes at 50% usage
/// rand(30,60):50 run at 50% usage for somewhere between 30 and 60 minutes.
/// 30:rand(50, 75) run for 30 minutes at somewhere between 50 and 75 % CPU usage
/// rand(30, 60) : rand(50, 75) run for somewhere between 30-60 minutes at 50-75% CPU usage.
/// </summary>
/// <param name="times"></param>
/// <returns></returns>
private int GetValue(string times)
{
times = times.Trim();
if (String.Compare(times, 0, "rand(", 0, 5) == 0)
{
string trimmedTimes = times.Substring(5).Trim();
string[] values = trimmedTimes.Split(new char[] { ',' });
int min = Convert.ToInt32(values[0]);
int max = Convert.ToInt32(values[1].Substring(0, values[1].Length - 1)); // remove the ending )
return (_rand.Next(min, max));
}
else
{
return (Convert.ToInt32(times));
}
}
public int MinPercentMem
{
get
{
return (_minimumMemoryPercent);
}
set
{
_minimumMemoryPercent = value;
}
}
public int MinTestsRunning
{
get
{
return (_minimumTestsRunning);
}
set
{
_minimumTestsRunning = value;
}
}
public int MaxTestsRunning
{
get
{
return (_maximumTestsRunning);
}
set
{
_maximumTestsRunning = value;
}
}
public bool EnablePerfCounters
{
get
{
#if PROJECTK_BUILD
return false;
#else
if (enablePerfCounters)
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
enablePerfCounters = false;
}
}
return (enablePerfCounters);
#endif
}
set
{
_enablePerfCounters = value;
}
}
public bool DisableLogging
{
get
{
return (_disableLogging);
}
set
{
_disableLogging = value;
}
}
public bool InstallDetours
{
get
{
return (_installDetours);
}
set
{
_installDetours = value;
}
}
public TestStartModeEnum DefaultTestStartMode
{
get
{
return (_testStartMode);
}
set
{
_testStartMode = value;
}
}
public int PercentPassIsPass
{
get
{
return (_percentPassIsPass);
}
set
{
_percentPassIsPass = value;
}
}
public AppDomainLoaderMode AppDomainLoaderMode
{
get
{
return (_adLoaderMode);
}
set
{
_adLoaderMode = value;
}
}
public AssemblyLoadContextLoaderMode AssemblyLoadContextLoaderMode
{
get
{
return (_alcLoaderMode);
}
set
{
_alcLoaderMode = value;
}
}
/// <summary>
/// Used for round-robin scheduling. Number of AssemblyLoadContexts domains to schedule tests into.
/// </summary>
public int NumAssemblyLoadContexts
{
get
{
return (_numAssemblyLoadContexts);
}
set
{
_numAssemblyLoadContexts = value;
}
}
/// <summary>
/// Used for round-robin scheduling. Number of app domains to schedule tests into.
/// </summary>
public int NumAppDomains
{
get
{
return (_numAppDomains);
}
set
{
_numAppDomains = value;
}
}
public string DefaultDebugger
{
get
{
return (_defaultDebugger);
}
set
{
_defaultDebugger = value;
}
}
public string DefaultDebuggerOptions
{
get
{
return (_defaultDebuggerOptions);
}
set
{
_defaultDebuggerOptions = value;
}
}
public int ULGeneralUnloadPercent
{
get
{
return (_ulGeneralUnloadPercent);
}
set
{
_ulGeneralUnloadPercent = value;
}
}
public int ULAppDomainUnloadPercent
{
get
{
return (_ulAppDomainUnloadPercent);
}
set
{
_ulAppDomainUnloadPercent = value;
}
}
public int ULAssemblyLoadPercent
{
get
{
return (_ulAssemblyLoadPercent);
}
set
{
_ulAssemblyLoadPercent = value;
}
}
public int ULWaitTime
{
get
{
return (_ulWaitTime);
}
set
{
_ulWaitTime = value;
}
}
public bool ReportResults
{
get
{
if (_reportResults && Environment.GetEnvironmentVariable("RF_NOREPORT") == null)
{
_reportResults = false;
}
return (_reportResults);
}
set
{
_reportResults = value;
}
}
public string ReportResultsTo
{
get
{
return (_reportResultsTo);
}
set
{
_reportResultsTo = value;
}
}
public Guid BvtCategory
{
get
{
return (_bvtCategory);
}
set
{
_bvtCategory = value;
}
}
public string CCFailMail
{
get
{
return (_ccFailMail);
}
set
{
_ccFailMail = value;
}
}
public bool SuppressConsoleOutputFromTests
{
get
{
return _suppressConsoleOutputFromTests;
}
set
{
_suppressConsoleOutputFromTests = value;
}
}
public bool DebugBreakOnTestHang
{
get
{
return _debugBreakOnTestHang;
}
set
{
_debugBreakOnTestHang = value;
}
}
public bool DebugBreakOnBadTest
{
get
{
return _debugBreakOnBadTest;
}
set
{
_debugBreakOnBadTest = value;
}
}
public bool DebugBreakOnOutOfMemory
{
get
{
return _debugBreakOnOutOfMemory;
}
set
{
_debugBreakOnOutOfMemory = value;
}
}
public bool DebugBreakOnPathTooLong
{
get
{
return _debugBreakOnPathTooLong;
}
set
{
_debugBreakOnPathTooLong = value;
}
}
public bool DebugBreakOnMissingTest
{
get
{
return _debugBreakOnMissingTest;
}
set
{
_debugBreakOnMissingTest = value;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MefCompositionContainerBuilder.cs" company="Quartz Software SRL">
// Copyright (c) Quartz Software SRL. All rights reserved.
// </copyright>
// <summary>
// Builder for the MEF composition container.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Composition.Mef.Hosting
{
using System;
using System.Collections.Generic;
using System.Composition.Convention;
using System.Composition.Hosting;
using System.Composition.Hosting.Core;
using System.Diagnostics.Contracts;
using System.Linq;
using Kephas.Composition.Conventions;
using Kephas.Composition.Hosting;
using Kephas.Composition.Mef.Conventions;
using Kephas.Composition.Mef.ExportProviders;
using Kephas.Composition.Mef.Resources;
using Kephas.Composition.Mef.ScopeFactory;
using Kephas.Composition.Metadata;
using Kephas.Services;
/// <summary>
/// Builder for the MEF composition container.
/// </summary>
/// <remarks>
/// This class is not thread safe.
/// </remarks>
public class MefCompositionContainerBuilder : CompositionContainerBuilderBase<MefCompositionContainerBuilder>
{
/// <summary>
/// The scope factories.
/// </summary>
private readonly ICollection<Type> scopeFactories = new HashSet<Type>();
/// <summary>
/// The container configuration.
/// </summary>
private ContainerConfiguration configuration;
/// <summary>
/// Initializes a new instance of the <see cref="MefCompositionContainerBuilder"/> class.
/// </summary>
/// <param name="context">The context.</param>
public MefCompositionContainerBuilder(IContext context)
: base(context)
{
Contract.Requires(context != null);
}
/// <summary>
/// Sets the composition conventions.
/// </summary>
/// <param name="conventions">The conventions.</param>
/// <returns>This builder.</returns>
public override MefCompositionContainerBuilder WithConventions(IConventionsBuilder conventions)
{
// ReSharper disable once SuspiciousTypeConversion.Global
var mefConventions = conventions as IMefConventionBuilderProvider;
if (mefConventions == null)
{
throw new InvalidOperationException(string.Format(Strings.InvalidConventions, typeof(IMefConventionBuilderProvider).FullName));
}
return base.WithConventions(conventions);
}
/// <summary>
/// Sets the container configuration.
/// </summary>
/// <param name="containerConfiguration">The container configuration.</param>
/// <returns>This builder.</returns>
public MefCompositionContainerBuilder WithConfiguration(ContainerConfiguration containerConfiguration)
{
Contract.Requires(containerConfiguration != null);
this.configuration = containerConfiguration;
return this;
}
/// <summary>
/// Registers the scope factory <typeparamref name="TFactory"/>.
/// </summary>
/// <typeparam name="TFactory">Type of the factory.</typeparam>
/// <returns>
/// This builder.
/// </returns>
public MefCompositionContainerBuilder WithScopeFactory<TFactory>()
where TFactory : IMefScopeFactory
{
this.scopeFactories.Add(typeof(TFactory));
return this;
}
/// <summary>
/// Registers the scope factory.
/// </summary>
/// <typeparam name="TFactory">Type of the factory.</typeparam>
/// <param name="conventions">The conventions.</param>
/// <returns>
/// This builder.
/// </returns>
protected MefCompositionContainerBuilder RegisterScopeFactory<TFactory>(IConventionsBuilder conventions)
where TFactory : IMefScopeFactory
{
return this.RegisterScopeFactory(conventions, typeof(TFactory));
}
/// <summary>
/// Registers the scope factory.
/// </summary>
/// <param name="conventions">The conventions.</param>
/// <param name="factoryType">Type of the factory.</param>
/// <returns>
/// This builder.
/// </returns>
protected MefCompositionContainerBuilder RegisterScopeFactory(IConventionsBuilder conventions, Type factoryType)
{
var mefConventions = ((IMefConventionBuilderProvider)conventions).GetConventionBuilder();
var scopeName = factoryType.ExtractMetadataValue<SharingBoundaryScopeAttribute, string>(a => a.Value);
if (string.IsNullOrEmpty(scopeName))
{
throw new InvalidOperationException(string.Format(Strings.MefCompositionContainerBuilder_MissingScopeName_Exception, factoryType.FullName));
}
mefConventions
.ForType(factoryType)
.Export(b => b.AsContractType<IMefScopeFactory>()
.AsContractName(scopeName))
.Shared();
return this;
}
/// <summary>
/// Creates a new factory provider.
/// </summary>
/// <typeparam name="TContract">The type of the contract.</typeparam>
/// <param name="factory">The factory.</param>
/// <param name="isShared">If set to <c>true</c>, the factory returns a shared component, otherwise an instance component.</param>
/// <returns>
/// The export provider.
/// </returns>
protected override IExportProvider CreateFactoryExportProvider<TContract>(Func<TContract> factory, bool isShared = false)
{
var provider = new FactoryExportDescriptorProvider<TContract>(factory, isShared);
return provider;
}
/// <summary>
/// Creates a new export provider based on a <see cref="IServiceProvider"/>.
/// </summary>
/// <param name="serviceProvider">The service provider.</param>
/// <returns>
/// The export provider.
/// </returns>
protected override IExportProvider CreateServiceProviderExportProvider(IServiceProvider serviceProvider)
{
var provider = new ServiceProviderExportDescriptorProvider(serviceProvider);
return provider;
}
/// <summary>
/// Factory method for creating the MEF conventions builder.
/// </summary>
/// <returns>A newly created MEF conventions builder.</returns>
protected override IConventionsBuilder CreateConventionsBuilder()
{
return new MefConventionsBuilder();
}
/// <summary>
/// Creates a new composition container based on the provided conventions and assembly parts.
/// </summary>
/// <param name="conventions">The conventions.</param>
/// <param name="parts">The parts candidating for composition.</param>
/// <returns>
/// A new composition container.
/// </returns>
protected override ICompositionContext CreateContainerCore(IConventionsBuilder conventions, IEnumerable<Type> parts)
{
this.RegisterScopeFactoryConventions(conventions);
var containerConfiguration = this.configuration ?? new ContainerConfiguration();
var conventionBuilder = this.GetConventionBuilder(conventions);
containerConfiguration
.WithDefaultConventions(conventionBuilder)
.WithParts(parts);
this.RegisterScopeFactoryParts(containerConfiguration, parts);
foreach (var provider in this.ExportProviders)
{
containerConfiguration.WithProvider((ExportDescriptorProvider)provider);
}
// add the default export descriptor providers.
containerConfiguration
.WithProvider(new ExportFactoryExportDescriptorProvider())
.WithProvider(new ExportFactoryWithMetadataExportDescriptorProvider());
return this.CreateCompositionContext(containerConfiguration);
}
/// <summary>
/// Creates the composition context based on the provided container configuration.
/// </summary>
/// <param name="containerConfiguration">The container configuration.</param>
/// <returns>
/// The new composition context.
/// </returns>
protected virtual ICompositionContext CreateCompositionContext(ContainerConfiguration containerConfiguration)
{
return new MefCompositionContainer(containerConfiguration);
}
/// <summary>
/// Gets the convention builder out of the provided abstract conventions.
/// </summary>
/// <param name="conventions">The conventions.</param>
/// <returns>
/// The convention builder.
/// </returns>
protected virtual ConventionBuilder GetConventionBuilder(IConventionsBuilder conventions)
{
var mefConventions = ((IMefConventionBuilderProvider)conventions).GetConventionBuilder();
return mefConventions;
}
/// <summary>
/// Registers the scope factories into the conventions.
/// </summary>
/// <param name="conventions">The conventions.</param>
private void RegisterScopeFactoryConventions(IConventionsBuilder conventions)
{
this.scopeFactories.Add(typeof(DefaultMefScopeFactory));
foreach (var scopeFactory in this.scopeFactories)
{
this.RegisterScopeFactory(conventions, scopeFactory);
}
}
/// <summary>
/// Registers the scope factory parts into the container configuration.
/// </summary>
/// <param name="containerConfiguration">The container configuration.</param>
/// <param name="registeredParts">The registered parts.</param>
private void RegisterScopeFactoryParts(ContainerConfiguration containerConfiguration, IEnumerable<Type> registeredParts)
{
if (this.scopeFactories.Count == 0)
{
return;
}
containerConfiguration.WithParts(this.scopeFactories.Where(f => !registeredParts.Contains(f)));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using System.IO;
using System.Linq;
namespace Libraries.Starlight
{
public class AdvanceableRule : List<AdvanceableProduction>, ICloneable,
IEqualityComparer<AdvanceableRule>, IAdvanceableRule
{
private long oldHashCode = 0L;
private int oldLength = 0;
#if GATHERING_STATS
public static long InstanceCount = 0L, DeleteCount = 0L;
// public static HashSet<TimeSpan> Lifetimes = new HashSet<TimeSpan>();
// private DateTime bornOn;
#endif
private string name;
public string Name
{
get
{
return name;
}
protected set
{
name = value;
}
}
public AdvanceableRule(Rule r, int offset)
{
#if GATHERING_STATS
InstanceCount++;
// bornOn = DateTime.Now;
#endif
if(r != null)
{
name = r.Name;
for(int i = 0; i < r.Count; i++)
Add(r[i].MakeAdvanceable(offset));
}
}
public AdvanceableRule(Rule r) : this(r, 0) { }
public AdvanceableRule(string name)
{
#if GATHERING_STATS
InstanceCount++;
// bornOn = DateTime.Now;
#endif
this.name = name;
}
public AdvanceableRule(string name, params AdvanceableProduction[] prods)
: this(name)
{
for(int i = 0; i < prods.Length; i++)
Add(prods[i]);
}
public AdvanceableRule(string name, IEnumerable<AdvanceableProduction> prods)
: this(name)
{
foreach(var v in prods)
Add(v);
}
public AdvanceableRule(AdvanceableRule rule)
{
#if GATHERING_STATS
InstanceCount++;
// bornOn = DateTime.Now;
#endif
name = rule.name;
for(int i = 0; i < rule.Count; i++)
Add(rule[i]); //lets see what this does...
}
#if GATHERING_STATS
~AdvanceableRule()
{
DeleteCount++;
// Lifetimes.Add(DateTime.Now - bornOn);
}
#endif
IAdvanceableProduction IAdvanceableRule.this[int ind] { get { return (IAdvanceableProduction)this[ind]; } }
IProduction IRule.this[int ind] { get { return (IProduction)this[ind]; } }
IEnumerable<IProduction> IRule.GetEnumerableInterface()
{
return ((IAdvanceableRule)this).GetEnumerableInterface();
}
IEnumerable<IAdvanceableProduction> IAdvanceableRule.GetEnumerableInterface()
{
return ((IEnumerable<AdvanceableProduction>)this);
}
public object Clone()
{
return new AdvanceableRule(this);
}
protected bool Equals(AdvanceableRule rr)
{
if(!rr.name.Equals(name) || rr.Count != Count)
return false;
else
{
for(int i = 0; i < Count; i++)
if(!this[i].Equals(rr[i]))
return false;
return true;
}
}
bool IAdvanceableRule.Equals(object other)
{
AdvanceableRule rr = (AdvanceableRule)other;
return Equals(rr);
}
int IAdvanceableRule.GetHashCode()
{
return GetHashCode0();
}
public override bool Equals(object other)
{
AdvanceableRule rr = (AdvanceableRule)other;
return Equals(rr);
}
private int GetHashCode0()
{
if(oldLength != Count)
{
long total = name.GetHashCode();
for(int i = 0; i < Count; i++)
total += this[i].GetHashCode();
oldHashCode = total;
oldLength = Count;
}
return (int)oldHashCode;
}
bool IEqualityComparer<AdvanceableRule>.Equals(AdvanceableRule x, AdvanceableRule y)
{
return x.Equals(y);
}
int IEqualityComparer<AdvanceableRule>.GetHashCode(AdvanceableRule x)
{
return x.GetHashCode0();
}
public override int GetHashCode()
{
return GetHashCode0();
}
public AdvanceableRule FunctionalNext()
{
var clone = this.Clone() as AdvanceableRule;
clone.Next();
return clone;
}
public AdvanceableRule FunctionalPrevious()
{
var clone = this.Clone() as AdvanceableRule;
clone.Previous();
return clone;
}
public void Next()
{
for(int i = 0; i < Count ; i++)
if(this[i].HasNext)
this[i].Next();
}
public void Previous()
{
for(int i = 0; i < Count; i++)
if(this[i].HasPrevious)
this[i].Previous();
}
public void Reset()
{
for(int i = 0; i < Count; i++)
this[i].Reset();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < Count; i++)
sb.AppendFormat("[{0} => {1}]\n", name, this[i].ToString());
return sb.ToString();
}
public IEnumerable<AdvanceableRule> Subdivide()
{
for(int i = 0; i < Count; i++)
yield return new AdvanceableRule(name) { this[i] };
}
public void Repurpose(Rule target)
{
Repurpose(new AdvanceableRule(target));
}
public void Repurpose(AdvanceableRule target)
{
Clear();
Repurpose(target.name);
// if(!target.Name.Equals(Name))
// Name = target.Name;
for(int i = 0; i < target.Count; i++)
Add(target[i]);
}
public void Repurpose(string name, params AdvanceableProduction[] prods)
{
Repurpose(name);
Repurpose(prods);
}
public void Repurpose(params AdvanceableProduction[] prods)
{
Clear();
for(int i = 0; i < prods.Length; i++)
Add(prods[i]);
}
public void Repurpose(string name)
{
if(!name.Equals(this.name))
this.name = name;
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Core;
using Orleans.Providers;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Scheduler;
using Orleans.Storage;
namespace Orleans.Runtime
{
internal class Catalog : SystemTarget, ICatalog, IPlacementContext, ISiloStatusListener
{
/// <summary>
/// Exception to indicate that the activation would have been a duplicate so messages pending for it should be redirected.
/// </summary>
[Serializable]
internal class DuplicateActivationException : Exception
{
public ActivationAddress ActivationToUse { get; private set; }
public SiloAddress PrimaryDirectoryForGrain { get; private set; } // for diagnostics only!
public DuplicateActivationException() : base("DuplicateActivationException") { }
public DuplicateActivationException(string msg) : base(msg) { }
public DuplicateActivationException(string message, Exception innerException) : base(message, innerException) { }
public DuplicateActivationException(ActivationAddress activationToUse)
: base("DuplicateActivationException")
{
ActivationToUse = activationToUse;
}
public DuplicateActivationException(ActivationAddress activationToUse, SiloAddress primaryDirectoryForGrain)
: base("DuplicateActivationException")
{
ActivationToUse = activationToUse;
PrimaryDirectoryForGrain = primaryDirectoryForGrain;
}
// Implementation of exception serialization with custom properties according to:
// http://stackoverflow.com/questions/94488/what-is-the-correct-way-to-make-a-custom-net-exception-serializable
protected DuplicateActivationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
ActivationToUse = (ActivationAddress) info.GetValue("ActivationToUse", typeof (ActivationAddress));
PrimaryDirectoryForGrain = (SiloAddress) info.GetValue("PrimaryDirectoryForGrain", typeof (SiloAddress));
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info != null)
{
info.AddValue("ActivationToUse", ActivationToUse, typeof (ActivationAddress));
info.AddValue("PrimaryDirectoryForGrain", PrimaryDirectoryForGrain, typeof (SiloAddress));
}
// MUST call through to the base class to let it save its own state
base.GetObjectData(info, context);
}
}
[Serializable]
internal class NonExistentActivationException : Exception
{
public ActivationAddress NonExistentActivation { get; private set; }
public bool IsStatelessWorker { get; private set; }
public NonExistentActivationException() : base("NonExistentActivationException") { }
public NonExistentActivationException(string msg) : base(msg) { }
public NonExistentActivationException(string message, Exception innerException)
: base(message, innerException) { }
public NonExistentActivationException(string msg, ActivationAddress nonExistentActivation, bool isStatelessWorker)
: base(msg)
{
NonExistentActivation = nonExistentActivation;
IsStatelessWorker = isStatelessWorker;
}
protected NonExistentActivationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
NonExistentActivation = (ActivationAddress)info.GetValue("NonExistentActivation", typeof(ActivationAddress));
IsStatelessWorker = (bool)info.GetValue("IsStatelessWorker", typeof(bool));
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info != null)
{
info.AddValue("NonExistentActivation", NonExistentActivation, typeof(ActivationAddress));
info.AddValue("IsStatelessWorker", IsStatelessWorker, typeof(bool));
}
// MUST call through to the base class to let it save its own state
base.GetObjectData(info, context);
}
}
public GrainTypeManager GrainTypeManager { get; private set; }
public SiloAddress LocalSilo { get; private set; }
internal ISiloStatusOracle SiloStatusOracle { get; set; }
internal readonly ActivationCollector ActivationCollector;
private readonly ILocalGrainDirectory directory;
private readonly OrleansTaskScheduler scheduler;
private readonly ActivationDirectory activations;
private IStorageProviderManager storageProviderManager;
private Dispatcher dispatcher;
private readonly TraceLogger logger;
private int collectionNumber;
private int destroyActivationsNumber;
private IDisposable gcTimer;
private readonly GlobalConfiguration config;
private readonly string localSiloName;
private readonly CounterStatistic activationsCreated;
private readonly CounterStatistic activationsDestroyed;
private readonly CounterStatistic activationsFailedToActivate;
private readonly IntValueStatistic inProcessRequests;
private readonly CounterStatistic collectionCounter;
private readonly IGrainRuntime grainRuntime;
internal Catalog(
GrainId grainId,
SiloAddress silo,
string siloName,
ILocalGrainDirectory grainDirectory,
GrainTypeManager typeManager,
OrleansTaskScheduler scheduler,
ActivationDirectory activationDirectory,
ClusterConfiguration config,
IGrainRuntime grainRuntime,
out Action<Dispatcher> setDispatcher)
: base(grainId, silo)
{
LocalSilo = silo;
localSiloName = siloName;
directory = grainDirectory;
activations = activationDirectory;
this.scheduler = scheduler;
GrainTypeManager = typeManager;
this.grainRuntime = grainRuntime;
collectionNumber = 0;
destroyActivationsNumber = 0;
logger = TraceLogger.GetLogger("Catalog", TraceLogger.LoggerType.Runtime);
this.config = config.Globals;
setDispatcher = d => dispatcher = d;
ActivationCollector = new ActivationCollector(config);
GC.GetTotalMemory(true); // need to call once w/true to ensure false returns OK value
config.OnConfigChange("Globals/Activation", () => scheduler.RunOrQueueAction(Start, SchedulingContext), false);
IntValueStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COUNT, () => activations.Count);
activationsCreated = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_CREATED);
activationsDestroyed = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DESTROYED);
activationsFailedToActivate = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_FAILED_TO_ACTIVATE);
collectionCounter = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COLLECTION_NUMBER_OF_COLLECTIONS);
inProcessRequests = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGING_PROCESSING_ACTIVATION_DATA_ALL, () =>
{
long counter = 0;
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
counter += data.GetRequestCount();
}
}
return counter;
});
}
internal void SetStorageManager(IStorageProviderManager storageManager)
{
storageProviderManager = storageManager;
}
internal void Start()
{
if (gcTimer != null) gcTimer.Dispose();
var t = GrainTimer.FromTaskCallback(OnTimer, null, TimeSpan.Zero, ActivationCollector.Quantum, "Catalog.GCTimer");
t.Start();
gcTimer = t;
}
private Task OnTimer(object _)
{
return CollectActivationsImpl(true);
}
public Task CollectActivations(TimeSpan ageLimit)
{
return CollectActivationsImpl(false, ageLimit);
}
private async Task CollectActivationsImpl(bool scanStale, TimeSpan ageLimit = default(TimeSpan))
{
var watch = new Stopwatch();
watch.Start();
var number = Interlocked.Increment(ref collectionNumber);
long memBefore = GC.GetTotalMemory(false) / (1024 * 1024);
logger.Info(ErrorCode.Catalog_BeforeCollection, "Before collection#{0}: memory={1}MB, #activations={2}, collector={3}.",
number, memBefore, activations.Count, ActivationCollector.ToString());
List<ActivationData> list = scanStale ? ActivationCollector.ScanStale() : ActivationCollector.ScanAll(ageLimit);
collectionCounter.Increment();
var count = 0;
if (list != null && list.Count > 0)
{
count = list.Count;
if (logger.IsVerbose) logger.Verbose("CollectActivations{0}", list.ToStrings(d => d.Grain.ToString() + d.ActivationId));
await DeactivateActivationsFromCollector(list);
}
long memAfter = GC.GetTotalMemory(false) / (1024 * 1024);
watch.Stop();
logger.Info(ErrorCode.Catalog_AfterCollection, "After collection#{0}: memory={1}MB, #activations={2}, collected {3} activations, collector={4}, collection time={5}.",
number, memAfter, activations.Count, count, ActivationCollector.ToString(), watch.Elapsed);
}
public List<Tuple<GrainId, string, int>> GetGrainStatistics()
{
var counts = new Dictionary<string, Dictionary<GrainId, int>>();
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
if (data == null || data.GrainInstance == null) continue;
// TODO: generic type expansion
var grainTypeName = TypeUtils.GetFullName(data.GrainInstanceType);
Dictionary<GrainId, int> grains;
int n;
if (!counts.TryGetValue(grainTypeName, out grains))
{
counts.Add(grainTypeName, new Dictionary<GrainId, int> { { data.Grain, 1 } });
}
else if (!grains.TryGetValue(data.Grain, out n))
grains[data.Grain] = 1;
else
grains[data.Grain] = n + 1;
}
}
return counts
.SelectMany(p => p.Value.Select(p2 => Tuple.Create(p2.Key, p.Key, p2.Value)))
.ToList();
}
public IEnumerable<KeyValuePair<string, long>> GetSimpleGrainStatistics()
{
return activations.GetSimpleGrainStatistics();
}
public DetailedGrainReport GetDetailedGrainReport(GrainId grain)
{
var report = new DetailedGrainReport
{
Grain = grain,
SiloAddress = LocalSilo,
SiloName = localSiloName,
LocalCacheActivationAddresses = directory.GetLocalCacheData(grain),
LocalDirectoryActivationAddresses = directory.GetLocalDirectoryData(grain),
PrimaryForGrain = directory.GetPrimaryForGrain(grain)
};
try
{
PlacementStrategy unused;
string grainClassName;
GrainTypeManager.GetTypeInfo(grain.GetTypeCode(), out grainClassName, out unused);
report.GrainClassTypeName = grainClassName;
}
catch (Exception exc)
{
report.GrainClassTypeName = exc.ToString();
}
List<ActivationData> acts = activations.FindTargets(grain);
report.LocalActivations = acts != null ?
acts.Select(activationData => activationData.ToDetailedString()).ToList() :
new List<string>();
return report;
}
#region MessageTargets
/// <summary>
/// Register a new object to which messages can be delivered with the local lookup table and scheduler.
/// </summary>
/// <param name="activation"></param>
public void RegisterMessageTarget(ActivationData activation)
{
var context = new SchedulingContext(activation);
scheduler.RegisterWorkContext(context);
activations.RecordNewTarget(activation);
activationsCreated.Increment();
}
/// <summary>
/// Unregister message target and stop delivering messages to it
/// </summary>
/// <param name="activation"></param>
public void UnregisterMessageTarget(ActivationData activation)
{
activations.RemoveTarget(activation);
// this should be removed once we've refactored the deactivation code path. For now safe to keep.
ActivationCollector.TryCancelCollection(activation);
activationsDestroyed.Increment();
scheduler.UnregisterWorkContext(new SchedulingContext(activation));
if (activation.GrainInstance == null) return;
var grainTypeName = TypeUtils.GetFullName(activation.GrainInstanceType);
activations.DecrementGrainCounter(grainTypeName);
activation.SetGrainInstance(null);
}
/// <summary>
/// FOR TESTING PURPOSES ONLY!!
/// </summary>
/// <param name="grain"></param>
internal int UnregisterGrainForTesting(GrainId grain)
{
var acts = activations.FindTargets(grain);
if (acts == null) return 0;
int numActsBefore = acts.Count;
foreach (var act in acts)
UnregisterMessageTarget(act);
return numActsBefore;
}
#endregion
#region Grains
internal bool IsReentrantGrain(ActivationId running)
{
ActivationData target;
GrainTypeData data;
return TryGetActivationData(running, out target) &&
target.GrainInstance != null &&
GrainTypeManager.TryGetData(TypeUtils.GetFullName(target.GrainInstanceType), out data) &&
data.IsReentrant;
}
public void GetGrainTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, string genericArguments = null)
{
GrainTypeManager.GetTypeInfo(typeCode, out grainClass, out placement, genericArguments);
}
#endregion
#region Activations
public int ActivationCount { get { return activations.Count; } }
/// <summary>
/// If activation already exists, use it
/// Otherwise, create an activation of an existing grain by reading its state.
/// Return immediately using a dummy that will queue messages.
/// Concurrently start creating and initializing the real activation and replace it when it is ready.
/// </summary>
/// <param name="address">Grain's activation address</param>
/// <param name="newPlacement">Creation of new activation was requested by the placement director.</param>
/// <param name="grainType">The type of grain to be activated or created</param>
/// <param name="genericArguments">Specific generic type of grain to be activated or created</param>
/// <param name="activatedPromise"></param>
/// <returns></returns>
public ActivationData GetOrCreateActivation(
ActivationAddress address,
bool newPlacement,
string grainType,
string genericArguments,
Dictionary<string, object> requestContextData,
out Task activatedPromise)
{
ActivationData result;
activatedPromise = TaskDone.Done;
PlacementStrategy placement;
lock (activations)
{
if (TryGetActivationData(address.Activation, out result))
{
ActivationCollector.TryRescheduleCollection(result);
return result;
}
int typeCode = address.Grain.GetTypeCode();
string actualGrainType = null;
if (typeCode != 0) // special case for Membership grain.
GetGrainTypeInfo(typeCode, out actualGrainType, out placement);
else
placement = SystemPlacement.Singleton;
if (newPlacement && !SiloStatusOracle.CurrentStatus.IsTerminating())
{
// create a dummy activation that will queue up messages until the real data arrives
if (string.IsNullOrEmpty(grainType))
{
grainType = actualGrainType;
}
// We want to do this (RegisterMessageTarget) under the same lock that we tested TryGetActivationData. They both access ActivationDirectory.
result = new ActivationData(
address,
genericArguments,
placement,
ActivationCollector,
config.Application.GetCollectionAgeLimit(grainType));
RegisterMessageTarget(result);
}
} // End lock
// Did not find and did not start placing new
if (result == null)
{
var msg = String.Format("Non-existent activation: {0}, grain type: {1}.",
address.ToFullString(), grainType);
if (logger.IsVerbose) logger.Verbose(ErrorCode.CatalogNonExistingActivation2, msg);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_NON_EXISTENT_ACTIVATIONS).Increment();
throw new NonExistentActivationException(msg, address, placement is StatelessWorkerPlacement);
}
SetupActivationInstance(result, grainType, genericArguments);
activatedPromise = InitActivation(result, grainType, genericArguments, requestContextData);
return result;
}
private void SetupActivationInstance(ActivationData result, string grainType, string genericInterface)
{
var genericArguments = String.IsNullOrEmpty(genericInterface) ? null
: TypeUtils.GenericTypeArgsString(genericInterface);
lock (result)
{
if (result.GrainInstance == null)
{
CreateGrainInstance(grainType, result, genericArguments);
}
}
}
private async Task InitActivation(ActivationData activation, string grainType, string genericInterface, Dictionary<string, object> requestContextData)
{
// We've created a dummy activation, which we'll eventually return, but in the meantime we'll queue up (or perform promptly)
// the operations required to turn the "dummy" activation into a real activation
ActivationAddress address = activation.Address;
int initStage = 0;
// A chain of promises that will have to complete in order to complete the activation
// Register with the grain directory, register with the store if necessary and call the Activate method on the new activation.
try
{
initStage = 1;
await RegisterActivationInGrainDirectoryAndValidate(activation);
initStage = 2;
await SetupActivationState(activation, grainType);
initStage = 3;
await InvokeActivate(activation, requestContextData);
ActivationCollector.ScheduleCollection(activation);
// Success!! Log the result, and start processing messages
if (logger.IsVerbose) logger.Verbose("InitActivation is done: {0}", address);
}
catch (Exception ex)
{
lock (activation)
{
activation.SetState(ActivationState.Invalid);
try
{
UnregisterMessageTarget(activation);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget4, String.Format("UnregisterMessageTarget failed on {0}.", activation), exc);
}
switch (initStage)
{
case 1: // failed to RegisterActivationInGrainDirectory
ActivationAddress target = null;
Exception dupExc;
// Failure!! Could it be that this grain uses single activation placement, and there already was an activation?
if (Utils.TryFindException(ex, typeof (DuplicateActivationException), out dupExc))
{
target = ((DuplicateActivationException) dupExc).ActivationToUse;
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DUPLICATE_ACTIVATIONS)
.Increment();
}
activation.ForwardingAddress = target;
if (target != null)
{
var primary = ((DuplicateActivationException)dupExc).PrimaryDirectoryForGrain;
// If this was a duplicate, it's not an error, just a race.
// Forward on all of the pending messages, and then forget about this activation.
string logMsg = String.Format("Tried to create a duplicate activation {0}, but we'll use {1} instead. " +
"GrainInstanceType is {2}. " +
"{3}" +
"Full activation address is {4}. We have {5} messages to forward.",
address,
target,
activation.GrainInstanceType,
primary != null ? "Primary Directory partition for this grain is " + primary + ". " : String.Empty,
address.ToFullString(),
activation.WaitingCount);
if (activation.IsStatelessWorker)
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
else
{
logger.Info(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
RerouteAllQueuedMessages(activation, target, "Duplicate activation", ex);
}
else
{
logger.Warn(ErrorCode.Runtime_Error_100064,
String.Format("Failed to RegisterActivationInGrainDirectory for {0}.",
activation), ex);
// Need to undo the registration we just did earlier
if (!activation.IsStatelessWorker)
{
scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null,
"Failed RegisterActivationInGrainDirectory", ex);
}
break;
case 2: // failed to setup persistent state
logger.Warn(ErrorCode.Catalog_Failed_SetupActivationState,
String.Format("Failed to SetupActivationState for {0}.", activation), ex);
// Need to undo the registration we just did earlier
if (!activation.IsStatelessWorker)
{
scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null, "Failed SetupActivationState", ex);
break;
case 3: // failed to InvokeActivate
logger.Warn(ErrorCode.Catalog_Failed_InvokeActivate,
String.Format("Failed to InvokeActivate for {0}.", activation), ex);
// Need to undo the registration we just did earlier
if (!activation.IsStatelessWorker)
{
scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address),
SchedulingContext).Ignore();
}
RerouteAllQueuedMessages(activation, null, "Failed InvokeActivate", ex);
break;
}
}
throw;
}
}
/// <summary>
/// Perform just the prompt, local part of creating an activation object
/// Caller is responsible for registering locally, registering with store and calling its activate routine
/// </summary>
/// <param name="grainTypeName"></param>
/// <param name="data"></param>
/// <param name="genericArguments"></param>
/// <returns></returns>
private void CreateGrainInstance(string grainTypeName, ActivationData data, string genericArguments)
{
string grainClassName;
var interfaceToClassMap = GrainTypeManager.GetGrainInterfaceToClassMap();
if (!interfaceToClassMap.TryGetValue(grainTypeName, out grainClassName))
{
// Lookup from grain type code
var typeCode = data.Grain.GetTypeCode();
if (typeCode != 0)
{
PlacementStrategy unused;
GetGrainTypeInfo(typeCode, out grainClassName, out unused, genericArguments);
}
else
{
grainClassName = grainTypeName;
}
}
GrainTypeData grainTypeData = GrainTypeManager[grainClassName];
Type grainType = grainTypeData.Type;
Grain grain = (Grain) Activator.CreateInstance(grainType);
// Inject runtime hookups into grain instance
grain.Runtime = grainRuntime;
grain.Data = data;
Type stateObjectType = grainTypeData.StateObjectType;
GrainState state;
if (stateObjectType != null)
{
state = (GrainState) Activator.CreateInstance(stateObjectType);
state.InitState(null);
}
else
{
state = null;
}
lock (data)
{
grain.Identity = data.Identity;
data.SetGrainInstance(grain);
if (state != null)
{
SetupStorageProvider(data);
data.GrainInstance.GrainState = state;
data.GrainInstance.Storage = new GrainStateStorageBridge(data.GrainTypeName, data.GrainInstance, data.StorageProvider);
}
}
activations.IncrementGrainCounter(grainClassName);
if (logger.IsVerbose) logger.Verbose("CreateGrainInstance {0}{1}", data.Grain, data.ActivationId);
}
private void SetupStorageProvider(ActivationData data)
{
var grainTypeName = data.GrainInstanceType.FullName;
// Get the storage provider name, using the default if not specified.
var attrs = data.GrainInstanceType.GetCustomAttributes(typeof(StorageProviderAttribute), true);
var attr = attrs.FirstOrDefault() as StorageProviderAttribute;
var storageProviderName = attr != null ? attr.ProviderName : Constants.DEFAULT_STORAGE_PROVIDER_NAME;
IStorageProvider provider;
if (storageProviderManager == null || storageProviderManager.GetNumLoadedProviders() == 0)
{
var errMsg = string.Format("No storage providers found loading grain type {0}", grainTypeName);
logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_1, errMsg);
throw new BadProviderConfigException(errMsg);
}
if (string.IsNullOrWhiteSpace(storageProviderName))
{
// Use default storage provider
provider = storageProviderManager.GetDefaultProvider();
}
else
{
// Look for MemoryStore provider as special case name
bool caseInsensitive = Constants.MEMORY_STORAGE_PROVIDER_NAME.Equals(storageProviderName, StringComparison.OrdinalIgnoreCase);
storageProviderManager.TryGetProvider(storageProviderName, out provider, caseInsensitive);
if (provider == null)
{
var errMsg = string.Format(
"Cannot find storage provider with Name={0} for grain type {1}", storageProviderName,
grainTypeName);
logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_2, errMsg);
throw new BadProviderConfigException(errMsg);
}
}
data.StorageProvider = provider;
if (logger.IsVerbose2)
{
string msg = string.Format("Assigned storage provider with Name={0} to grain type {1}",
storageProviderName, grainTypeName);
logger.Verbose2(ErrorCode.Provider_CatalogStorageProviderAllocated, msg);
}
}
private async Task SetupActivationState(ActivationData result, string grainType)
{
var state = result.GrainInstance.GrainState;
if (result.StorageProvider != null && state != null)
{
var sw = Stopwatch.StartNew();
// Populate state data
try
{
var grainRef = result.GrainReference;
await scheduler.RunOrQueueTask(() =>
result.StorageProvider.ReadStateAsync(grainType, grainRef, state),
new SchedulingContext(result));
sw.Stop();
StorageStatisticsGroup.OnStorageActivate(result.StorageProvider, grainType, result.GrainReference, sw.Elapsed);
result.GrainInstance.GrainState = state;
}
catch (Exception ex)
{
StorageStatisticsGroup.OnStorageActivateError(result.StorageProvider, grainType, result.GrainReference);
sw.Stop();
if (!(ex.GetBaseException() is KeyNotFoundException))
throw;
result.GrainInstance.GrainState = state; // Just keep original empty state object
}
}
}
/// <summary>
/// Try to get runtime data for an activation
/// </summary>
/// <param name="activationId"></param>
/// <param name="data"></param>
/// <returns></returns>
public bool TryGetActivationData(ActivationId activationId, out ActivationData data)
{
data = null;
if (activationId.IsSystem) return false;
data = activations.FindTarget(activationId);
return data != null;
}
private Task DeactivateActivationsFromCollector(List<ActivationData> list)
{
logger.Info(ErrorCode.Catalog_ShutdownActivations_1, "DeactivateActivationsFromCollector: total {0} to promptly Destroy.", list.Count);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_COLLECTION).IncrementBy(list.Count);
foreach (var activation in list)
{
lock (activation)
{
activation.PrepareForDeactivation(); // Don't accept any new messages
}
}
return DestroyActivations(list);
}
// To be called fro within Activation context.
// Cannot be awaitable, since after DestroyActivation is done the activation is in Invalid state and cannot await any Task.
internal void DeactivateActivationOnIdle(ActivationData data)
{
bool promptly = false;
bool alreadBeingDestroyed = false;
lock (data)
{
if (data.State == ActivationState.Valid)
{
// Change the ActivationData state here, since we're about to give up the lock.
data.PrepareForDeactivation(); // Don't accept any new messages
if (!data.IsCurrentlyExecuting)
{
promptly = true;
}
else // busy, so destroy later.
{
data.AddOnInactive(() => DestroyActivationVoid(data));
}
}
else
{
alreadBeingDestroyed = true;
}
}
logger.Info(ErrorCode.Catalog_ShutdownActivations_2,
"DeactivateActivationOnIdle: {0} {1}.", data.ToString(), promptly ? "promptly" : (alreadBeingDestroyed ? "already being destroyed or invalid" : "later when become idle"));
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_ON_IDLE).Increment();
if (promptly)
{
DestroyActivationVoid(data); // Don't await or Ignore, since we are in this activation context and it may have alraedy been destroyed!
}
}
/// <summary>
/// Gracefully deletes activations, putting it into a shutdown state to
/// complete and commit outstanding transactions before deleting it.
/// To be called not from within Activation context, so can be awaited.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
internal async Task DeactivateActivations(List<ActivationData> list)
{
if (list == null || list.Count == 0) return;
if (logger.IsVerbose) logger.Verbose("DeactivateActivations: {0} activations.", list.Count);
List<ActivationData> destroyNow = null;
List<MultiTaskCompletionSource> destroyLater = null;
int alreadyBeingDestroyed = 0;
foreach (var d in list)
{
var activationData = d; // capture
lock (activationData)
{
if (activationData.State == ActivationState.Valid)
{
// Change the ActivationData state here, since we're about to give up the lock.
activationData.PrepareForDeactivation(); // Don't accept any new messages
if (!activationData.IsCurrentlyExecuting)
{
if (destroyNow == null)
{
destroyNow = new List<ActivationData>();
}
destroyNow.Add(activationData);
}
else // busy, so destroy later.
{
if (destroyLater == null)
{
destroyLater = new List<MultiTaskCompletionSource>();
}
var tcs = new MultiTaskCompletionSource(1);
destroyLater.Add(tcs);
activationData.AddOnInactive(() => DestroyActivationAsync(activationData, tcs));
}
}
else
{
alreadyBeingDestroyed++;
}
}
}
int numDestroyNow = destroyNow == null ? 0 : destroyNow.Count;
int numDestroyLater = destroyLater == null ? 0 : destroyLater.Count;
logger.Info(ErrorCode.Catalog_ShutdownActivations_3,
"DeactivateActivations: total {0} to shutdown, out of them {1} promptly, {2} later when become idle and {3} are already being destroyed or invalid.",
list.Count, numDestroyNow, numDestroyLater, alreadyBeingDestroyed);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DIRECT_SHUTDOWN).IncrementBy(list.Count);
if (destroyNow != null && destroyNow.Count > 0)
{
await DestroyActivations(destroyNow);
}
if (destroyLater != null && destroyLater.Count > 0)
{
await Task.WhenAll(destroyLater.Select(t => t.Task).ToArray());
}
}
public Task DeactivateAllActivations()
{
logger.Info(ErrorCode.Catalog_DeactivateAllActivations, "DeactivateAllActivations.");
var activationsToShutdown = activations.Select(kv => kv.Value).ToList();
return DeactivateActivations(activationsToShutdown);
}
/// <summary>
/// Deletes activation immediately regardless of active transactions etc.
/// For use by grain delete, transaction abort, etc.
/// </summary>
/// <param name="activation"></param>
private void DestroyActivationVoid(ActivationData activation)
{
StartDestroyActivations(new List<ActivationData> { activation });
}
private void DestroyActivationAsync(ActivationData activation, MultiTaskCompletionSource tcs)
{
StartDestroyActivations(new List<ActivationData> { activation }, tcs);
}
/// <summary>
/// Forcibly deletes activations now, without waiting for any outstanding transactions to complete.
/// Deletes activation immediately regardless of active transactions etc.
/// For use by grain delete, transaction abort, etc.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
// Overall code flow:
// Deactivating state was already set before, in the correct context under lock.
// that means no more new requests will be accepted into this activation and all timer were stopped (no new ticks will be delivered or enqueued)
// Wait for all already scheduled ticks to finish
// CallGrainDeactivate
// when AsyncDeactivate promise is resolved (NOT when all Deactivate turns are done, which may be orphan tasks):
// Unregister in the directory
// when all AsyncDeactivate turns are done (Dispatcher.OnActivationCompletedRequest):
// Set Invalid state
// UnregisterMessageTarget -> no new tasks will be enqueue (if an orphan task get enqueud, it is ignored and dropped on the floor).
// InvalidateCacheEntry
// Reroute pending
private Task DestroyActivations(List<ActivationData> list)
{
var tcs = new MultiTaskCompletionSource(list.Count);
StartDestroyActivations(list, tcs);
return tcs.Task;
}
private async void StartDestroyActivations(List<ActivationData> list, MultiTaskCompletionSource tcs = null)
{
int number = destroyActivationsNumber;
destroyActivationsNumber++;
try
{
logger.Info(ErrorCode.Catalog_DestroyActivations, "Starting DestroyActivations #{0} of {1} activations", number, list.Count);
// step 1 - WaitForAllTimersToFinish
var tasks1 = new List<Task>();
foreach (var activation in list)
{
tasks1.Add(activation.WaitForAllTimersToFinish());
}
try
{
await Task.WhenAll(tasks1);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_WaitForAllTimersToFinish_Exception, String.Format("WaitForAllTimersToFinish {0} failed.", list.Count), exc);
}
// step 2 - CallGrainDeactivate
var tasks2 = new List<Tuple<Task, ActivationData>>();
foreach (var activation in list)
{
var activationData = activation; // Capture loop variable
var task = scheduler.RunOrQueueTask(() => CallGrainDeactivateAndCleanupStreams(activationData), new SchedulingContext(activationData));
tasks2.Add(new Tuple<Task, ActivationData>(task, activationData));
}
var asyncQueue = new AsyncBatchedContinuationQueue<ActivationData>();
asyncQueue.Queue(tasks2, tupleList =>
{
FinishDestroyActivations(tupleList.Select(t => t.Item2).ToList(), number, tcs);
GC.KeepAlive(asyncQueue); // not sure about GC not collecting the asyncQueue local var prematuraly, so just want to capture it here to make sure. Just to be safe.
});
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_DeactivateActivation_Exception, String.Format("StartDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc);
}
}
private async void FinishDestroyActivations(List<ActivationData> list, int number, MultiTaskCompletionSource tcs)
{
try
{
//logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Starting FinishDestroyActivations #{0} - with {1} Activations.", number, list.Count);
// step 3 - UnregisterManyAsync
try
{
List<ActivationAddress> activationsToDeactivate = list.
Where((ActivationData d) => !d.IsStatelessWorker).
Select((ActivationData d) => ActivationAddress.GetAddress(LocalSilo, d.Grain, d.ActivationId)).ToList();
if (activationsToDeactivate.Count > 0)
{
await scheduler.RunOrQueueTask(() =>
directory.UnregisterManyAsync(activationsToDeactivate),
SchedulingContext);
}
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterManyAsync, String.Format("UnregisterManyAsync {0} failed.", list.Count), exc);
}
// step 4 - UnregisterMessageTarget and OnFinishedGrainDeactivate
foreach (var activationData in list)
{
try
{
lock (activationData)
{
activationData.SetState(ActivationState.Invalid); // Deactivate calls on this activation are finished
}
UnregisterMessageTarget(activationData);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget2, String.Format("UnregisterMessageTarget failed on {0}.", activationData), exc);
}
try
{
// IMPORTANT: no more awaits and .Ignore after that point.
// Just use this opportunity to invalidate local Cache Entry as well.
// If this silo is not the grain directory partition for this grain, it may have it in its cache.
directory.InvalidateCacheEntry(activationData.Address);
RerouteAllQueuedMessages(activationData, null, "Finished Destroy Activation");
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget3, String.Format("Last stage of DestroyActivations failed on {0}.", activationData), exc);
}
}
// step 5 - Resolve any waiting TaskCompletionSource
if (tcs != null)
{
tcs.SetMultipleResults(list.Count);
}
logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Done FinishDestroyActivations #{0} - Destroyed {1} Activations.", number, list.Count);
}catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishDeactivateActivation_Exception, String.Format("FinishDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc);
}
}
private void RerouteAllQueuedMessages(ActivationData activation, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null)
{
lock (activation)
{
List<Message> msgs = activation.DequeueAllWaitingMessages();
if (msgs == null || msgs.Count <= 0) return;
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_RerouteAllQueuedMessages, String.Format("RerouteAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count(), activation));
dispatcher.ProcessRequestsToInvalidActivation(msgs, activation.Address, forwardingAddress, failedOperation, exc);
}
}
private async Task CallGrainActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
var grainTypeName = activation.GrainInstanceType.FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingActivate, "About to call {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
// Call OnActivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
RequestContext.Import(requestContextData);
await activation.GrainInstance.OnActivateAsync();
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingActivate, "Returned from calling {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
lock (activation)
{
if (activation.State == ActivationState.Activating)
{
activation.SetState(ActivationState.Valid); // Activate calls on this activation are finished
}
if (!activation.IsCurrentlyExecuting)
{
activation.RunOnInactive();
}
// Run message pump to see if there is a new request is queued to be processed
dispatcher.RunMessagePump(activation);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingActivate,
string.Format("Error calling grain's AsyncActivate method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
activation.SetState(ActivationState.Invalid); // Mark this activation as unusable
activationsFailedToActivate.Increment();
throw;
}
}
private async Task<ActivationData> CallGrainDeactivateAndCleanupStreams(ActivationData activation)
{
try
{
var grainTypeName = activation.GrainInstanceType.FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingDeactivate, "About to call {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
// Call OnDeactivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
// just check in case this activation data is already Invalid or not here at all.
ActivationData ignore;
if (TryGetActivationData(activation.ActivationId, out ignore) &&
activation.State == ActivationState.Deactivating)
{
RequestContext.Clear(); // Clear any previous RC, so it does not leak into this call by mistake.
await activation.GrainInstance.OnDeactivateAsync();
}
if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingDeactivate, "Returned from calling {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingDeactivate,
string.Format("Error calling grain's OnDeactivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
}
if (activation.IsUsingStreams)
{
try
{
await activation.DeactivateStreamResources();
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_DeactivateStreamResources_Exception, String.Format("DeactivateStreamResources Grain type = {0} Activation = {1} failed.", grainTypeName, activation), exc);
}
}
}
catch(Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishGrainDeactivateAndCleanupStreams_Exception, String.Format("CallGrainDeactivateAndCleanupStreams Activation = {0} failed.", activation), exc);
}
return activation;
}
private async Task RegisterActivationInGrainDirectoryAndValidate(ActivationData activation)
{
ActivationAddress address = activation.Address;
bool singleActivationMode = !activation.IsStatelessWorker;
if (singleActivationMode)
{
ActivationAddress returnedAddress = await scheduler.RunOrQueueTask(() => directory.RegisterSingleActivationAsync(address), this.SchedulingContext);
if (address.Equals(returnedAddress)) return;
SiloAddress primaryDirectoryForGrain = directory.GetPrimaryForGrain(address.Grain);
throw new DuplicateActivationException(returnedAddress, primaryDirectoryForGrain);
}
else
{
StatelessWorkerPlacement stPlacement = activation.PlacedUsing as StatelessWorkerPlacement;
int maxNumLocalActivations = stPlacement.MaxLocal;
lock (activations)
{
List<ActivationData> local;
if (!LocalLookup(address.Grain, out local) || local.Count <= maxNumLocalActivations)
return;
var id = StatelessWorkerDirector.PickRandom(local).Address;
throw new DuplicateActivationException(id);
}
}
// We currently don't have any other case for multiple activations except for StatelessWorker.
//await scheduler.RunOrQueueTask(() => directory.RegisterAsync(address), this.SchedulingContext);
}
#endregion
#region Activations - private
/// <summary>
/// Invoke the activate method on a newly created activation
/// </summary>
/// <param name="activation"></param>
/// <returns></returns>
private Task InvokeActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
// NOTE: This should only be called with the correct schedulering context for the activation to be invoked.
lock (activation)
{
activation.SetState(ActivationState.Activating);
}
return scheduler.QueueTask(() => CallGrainActivate(activation, requestContextData), new SchedulingContext(activation)); // Target grain's scheduler context);
// ActivationData will transition out of ActivationState.Activating via Dispatcher.OnActivationCompletedRequest
}
#endregion
#region IPlacementContext
public TraceLogger Logger
{
get { return logger; }
}
public bool FastLookup(GrainId grain, out List<ActivationAddress> addresses)
{
return directory.LocalLookup(grain, out addresses) && addresses != null && addresses.Count > 0;
// NOTE: only check with the local directory cache.
// DO NOT check in the local activations TargetDirectory!!!
// The only source of truth about which activation should be legit to is the state of the ditributed directory.
// Everyone should converge to that (that is the meaning of "eventualy consistency - eventualy we converge to one truth").
// If we keep using the local activation, it may not be registered in th directory any more, but we will never know that and keep using it,
// thus volaiting the single-activation semantics and not converging even eventualy!
}
public Task<List<ActivationAddress>> FullLookup(GrainId grain)
{
return scheduler.RunOrQueueTask(() => directory.FullLookup(grain), this.SchedulingContext);
}
public bool LocalLookup(GrainId grain, out List<ActivationData> addresses)
{
addresses = activations.FindTargets(grain);
return addresses != null;
}
public List<SiloAddress> AllActiveSilos
{
get
{
var result = SiloStatusOracle.GetApproximateSiloStatuses(true).Select(s => s.Key).ToList();
if (result.Count > 0) return result;
logger.Warn(ErrorCode.Catalog_GetApproximateSiloStatuses, "AllActiveSilos SiloStatusOracle.GetApproximateSiloStatuses empty");
return new List<SiloAddress> { LocalSilo };
}
}
#endregion
#region Implementation of ICatalog
public Task CreateSystemGrain(GrainId grainId, string grainType)
{
ActivationAddress target = ActivationAddress.NewActivationAddress(LocalSilo, grainId);
Task activatedPromise;
GetOrCreateActivation(target, true, grainType, null, null, out activatedPromise);
return activatedPromise ?? TaskDone.Done;
}
public Task DeleteActivations(List<ActivationAddress> addresses)
{
return DestroyActivations(TryGetActivationDatas(addresses));
}
private List<ActivationData> TryGetActivationDatas(List<ActivationAddress> addresses)
{
var datas = new List<ActivationData>(addresses.Count);
foreach (var activationAddress in addresses)
{
ActivationData data;
if (TryGetActivationData(activationAddress.Activation, out data))
datas.Add(data);
}
return datas;
}
#endregion
#region Implementation of ISiloStatusListener
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// ignore joining events and also events on myself.
if (updatedSilo.Equals(LocalSilo)) return;
// We deactivate those activations when silo goes either of ShuttingDown/Stopping/Dead states,
// since this is what Directory is doing as well. Directory removes a silo based on all those 3 statuses,
// thus it will only deliver a "remove" notification for a given silo once to us. Therefore, we need to react the fist time we are notified.
// We may review the directory behaiviour in the future and treat ShuttingDown differently ("drain only") and then this code will have to change a well.
if (!status.IsTerminating()) return;
var activationsToShutdown = new List<ActivationData>();
try
{
// scan all activations in activation directory and deactivate the ones that the removed silo is their primary partition owner.
lock (activations)
{
foreach (var activation in activations)
{
try
{
var activationData = activation.Value;
if (!directory.GetPrimaryForGrain(activationData.Grain).Equals(updatedSilo)) continue;
lock (activationData)
{
// adapted from InsideGarinClient.DeactivateOnIdle().
activationData.ResetKeepAliveRequest();
activationsToShutdown.Add(activationData);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_SiloStatusChangeNotification_Exception,
String.Format("Catalog has thrown an exception while executing SiloStatusChangeNotification of silo {0}.", updatedSilo.ToStringWithHashCode()), exc);
}
}
}
logger.Info(ErrorCode.Catalog_SiloStatusChangeNotification,
String.Format("Catalog is deactivating {0} activations due to a failure of silo {1}, since it is a primary directory partiton to these grain ids.",
activationsToShutdown.Count, updatedSilo.ToStringWithHashCode()));
}
finally
{
// outside the lock.
if (activationsToShutdown.Count > 0)
{
DeactivateActivations(activationsToShutdown).Ignore();
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using FlatRedBall.Utilities;
using System.Globalization;
#if !SILVERLIGHT && !ZUNE
using FlatRedBall.IO;
#endif
#if FRB_XNA || ZUNE || SILVERLIGHT
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
#elif FRB_MDX
using Microsoft.DirectX;
using System.Drawing;
#endif
namespace FlatRedBall.Instructions.Reflection
{
public struct PropertyValuePair
{
static Type stringType = typeof(string);
public string Property;
public object Value;
static Dictionary<string, Type> mUnqualifiedTypeDictionary = new Dictionary<string, Type>();
#if WINDOWS_8
/// <summary>
/// Stores a reference to the current assembly. This is the
/// assembly of your game. This must be explicitly set.
/// </summary>
public static Assembly TopLevelAssembly
{
get;
set;
}
#endif
public static List<Assembly> AdditionalAssemblies
{
get;
private set;
}
static PropertyValuePair()
{
AdditionalAssemblies = new List<Assembly>();
}
public PropertyValuePair(string property, object value)
{
Property = property;
Value = value;
}
public static string ConvertTypeToString(object value)
{
if (value == null) return string.Empty;
// Get the type
Type typeToConvertTo = value.GetType();
// Do the conversion
#region Convert To String
if (typeToConvertTo == typeof(bool))
{
return ((bool)value).ToString();
}
if (typeToConvertTo == typeof(int) || typeToConvertTo == typeof(Int32) || typeToConvertTo == typeof(Int16))
{
return ((int)value).ToString();
}
if (typeToConvertTo == typeof(float) || typeToConvertTo == typeof(Single))
{
return ((float)value).ToString();
}
if (typeToConvertTo == typeof(double))
{
return ((double)value).ToString();
}
if (typeToConvertTo == typeof(string))
{
return (string)value;
}
#if !FRB_RAW
if (typeToConvertTo == typeof(Texture2D))
{
return ((Texture2D)value).Name;
}
if (typeToConvertTo == typeof(Matrix))
{
Matrix m = (Matrix)value;
float[] values = new float[16];
values[0] = m.M11;
values[1] = m.M12;
values[2] = m.M13;
values[3] = m.M14;
values[4] = m.M21;
values[5] = m.M22;
values[6] = m.M23;
values[7] = m.M24;
values[8] = m.M31;
values[9] = m.M32;
values[10] = m.M33;
values[11] = m.M34;
values[12] = m.M41;
values[13] = m.M42;
values[14] = m.M43;
values[15] = m.M44;
string outputString = string.Empty;
// output values in comma-delimited form
for (int i = 0; i < values.Length; i++)
{
outputString += ((i == 0) ? string.Empty : ",") +
ConvertTypeToString(values[i]);
}
return outputString;
}
if (typeToConvertTo == typeof(Vector2))
{
Vector2 v = (Vector2)value;
return ConvertTypeToString(v.X) + "," +
ConvertTypeToString(v.Y);
}
if (typeToConvertTo == typeof(Vector3))
{
Vector3 v = (Vector3)value;
return ConvertTypeToString(v.X) + "," +
ConvertTypeToString(v.Y) + "," +
ConvertTypeToString(v.Z);
}
if (typeToConvertTo == typeof(Vector4))
{
Vector4 v = (Vector4)value;
return ConvertTypeToString(v.X) + "," +
ConvertTypeToString(v.Y) + "," +
ConvertTypeToString(v.Z) + "," +
ConvertTypeToString(v.W);
}
#endif
#if WINDOWS_8
if (typeToConvertTo.IsEnum())
#else
if (typeToConvertTo.IsEnum)
#endif
{
return value.ToString();
}
#endregion
// No cases matched, return empty string
return String.Empty;
}
public static T ConvertStringToType<T>(string value)
{
return (T)ConvertStringToType(value, typeof(T));
}
public static object ConvertStringToType(string value, Type typeToConvertTo)
{
#if FRB_RAW
return ConvertStringToType(value, typeToConvertTo, "Global");
#else
return ConvertStringToType(value, typeToConvertTo, FlatRedBallServices.GlobalContentManager);
#endif
}
public static object ConvertStringToType(string value, Type typeToConvertTo, string contentManagerName)
{
return ConvertStringToType(value, typeToConvertTo, contentManagerName, false);
}
public static object ConvertStringToType(string value, Type typeToConvertTo, string contentManagerName, bool trimQuotes)
{
value = value.Trim(); // this is in case there is a space in front - I don't think we need it.
//Fix any exported CSV bugs (such as quotes around a boolean)
if (trimQuotes ||
(value != null && (typeToConvertTo != typeof(string) && typeToConvertTo != typeof(char))
&& value.Contains("\"") == false) // If it has a quote, then we don't want to trim.
)
{
if (!value.StartsWith("new ") && typeToConvertTo != typeof(string))
{
value = FlatRedBall.Utilities.StringFunctions.RemoveWhitespace(value);
}
value = value.Replace("\"", "");
}
// Do the conversion
#region Convert To Object
// String needs to be first because it could contain equals and
// we don't want to cause problems
bool handled = false;
object toReturn = null;
if (typeToConvertTo == typeof(string))
{
toReturn = value;
handled = true;
}
if (!handled)
{
TryHandleComplexType(value, typeToConvertTo, out handled, out toReturn);
}
if (!handled)
{
#region bool
if (typeToConvertTo == typeof(bool))
{
if (string.IsNullOrEmpty(value))
{
return false;
}
// value could be upper case like "TRUE" or "True". Make it lower
value = value.ToLower();
toReturn = bool.Parse(value);
handled = true;
}
#endregion
#region int, Int32, Int16, uint, long
else if (typeToConvertTo == typeof(int) || typeToConvertTo == typeof(Int32) || typeToConvertTo == typeof(Int16) ||
typeToConvertTo == typeof(uint) || typeToConvertTo == typeof(long) || typeToConvertTo == typeof(byte))
{
if (string.IsNullOrEmpty(value))
{
return 0;
}
int indexOfDecimal = value.IndexOf('.');
if (value.IndexOf(",") != -1)
{
value = value.Replace(",", "");
}
#region uint
if (typeToConvertTo == typeof(uint))
{
if (indexOfDecimal == -1)
{
return uint.Parse(value);
}
else
{
return (uint)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture)));
}
}
#endregion
#region byte
if (typeToConvertTo == typeof(byte))
{
if (indexOfDecimal == -1)
{
return byte.Parse(value);
}
else
{
return (byte)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture)));
}
}
#endregion
#region long
if (typeToConvertTo == typeof(long))
{
if (indexOfDecimal == -1)
{
return long.Parse(value);
}
else
{
return (long)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture)));
}
}
#endregion
#region regular int
else
{
if (indexOfDecimal == -1)
{
return int.Parse(value);
}
else
{
return (int)(Math.MathFunctions.RoundToInt(float.Parse(value, CultureInfo.InvariantCulture)));
}
}
#endregion
}
#endregion
#region float, Single
else if (typeToConvertTo == typeof(float) || typeToConvertTo == typeof(Single))
{
if (string.IsNullOrEmpty(value))
{
return 0f;
}
return float.Parse(value, CultureInfo.InvariantCulture);
}
#endregion
#region double
else if (typeToConvertTo == typeof(double))
{
if (string.IsNullOrEmpty(value))
{
return 0.0;
}
return double.Parse(value, CultureInfo.InvariantCulture);
}
#endregion
#if !FRB_RAW
#region Texture2D
else if (typeToConvertTo == typeof(Texture2D))
{
if (string.IsNullOrEmpty(value))
{
return null;
}
#if !SILVERLIGHT && !ZUNE
if (FileManager.IsRelative(value))
{
// Vic says: This used to throw an exception on relative values. I'm not quite
// sure why this is the case...why don't we just make it relative to the relative
// directory? Maybe there's a reason to have this exception, but I can't think of
// what it is, and I'm writing a tutorial on how to load Texture2Ds from CSVs right
// now and it totally makes sense that the user would want to use a relative directory.
// In fact, the user will want to always use a relative directory so that their project is
// portable.
//throw new ArgumentException("Texture path must be absolute to load texture. Path: " + value);
value = FileManager.RelativeDirectory + value;
}
// Try to load a compiled asset first
if (FileManager.FileExists(FileManager.RemoveExtension(value) + @".xnb"))
{
Texture2D texture =
FlatRedBallServices.Load<Texture2D>(FileManager.RemoveExtension(value), contentManagerName);
// Vic asks: Why did we have to set the name? This is redundant and gets
// rid of the standardized file name which causes caching to not work properly.
// texture.Name = FileManager.RemoveExtension(value);
return texture;
}
else
{
Texture2D texture =
FlatRedBallServices.Load<Texture2D>(value, contentManagerName);
// Vic asks: Why did we have to set the name? This is redundant and gets
// rid of the standardized file name which causes caching to not work properly.
// texture.Name = value;
return texture;
}
#else
return null;
#endif
}
#endregion
#region Matrix
else if (typeToConvertTo == typeof(Matrix))
{
if (string.IsNullOrEmpty(value))
{
return Matrix.Identity;
}
value = StripParenthesis(value);
// Split the string
string[] stringvalues = value.Split(new char[] { ',' });
if (stringvalues.Length != 16)
{
throw new ArgumentException("String to Matrix conversion requires 16 values, " +
"supplied string contains " + stringvalues.Length + " values", "value");
}
// Convert to floats
float[] values = new float[16];
for (int i = 0; i < values.Length; i++)
{
values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
}
#if FRB_XNA
// Parse to matrix
Matrix m = new Matrix(
values[0], values[1], values[2], values[3],
values[4], values[5], values[6], values[7],
values[8], values[9], values[10], values[11],
values[12], values[13], values[14], values[15]
);
#elif FRB_MDX
Matrix m = new Matrix();
m.M11 = values[0];
m.M12 = values[1];
m.M13 = values[2];
m.M14 = values[3];
m.M21 = values[4];
m.M22 = values[5];
m.M23 = values[6];
m.M24 = values[7];
m.M31 = values[8];
m.M32 = values[9];
m.M33 = values[10];
m.M34 = values[11];
m.M41 = values[12];
m.M42 = values[13];
m.M43 = values[14];
m.M44 = values[15];
#elif SILVERLIGHT || ZUNE
Matrix m = new Matrix();
#endif
return m;
}
#endregion
#region Vector2
else if (typeToConvertTo == typeof(Vector2))
{
if (string.IsNullOrEmpty(value))
{
return new Vector2(0, 0);
}
value = StripParenthesis(value);
// Split the string
string[] stringvalues = value.Split(new char[] { ',' });
if (stringvalues.Length != 2)
{
throw new ArgumentException("String to Vector2 conversion requires 2 values, " +
"supplied string contains " + stringvalues.Length + " values", "value");
}
// Convert to floats
float[] values = new float[2];
for (int i = 0; i < values.Length; i++)
{
values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
}
return new Vector2(values[0], values[1]);
}
#endregion
#region Vector3
else if (typeToConvertTo == typeof(Vector3))
{
if (string.IsNullOrEmpty(value))
{
return new Vector3(0, 0, 0);
}
value = StripParenthesis(value);
// Split the string
string[] stringvalues = value.Split(new char[] { ',' });
if (stringvalues.Length != 3)
{
throw new ArgumentException("String to Vector3 conversion requires 3 values, " +
"supplied string contains " + stringvalues.Length + " values", "value");
}
// Convert to floats
float[] values = new float[3];
for (int i = 0; i < values.Length; i++)
{
values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
}
return new Vector3(values[0], values[1], values[2]);
}
#endregion
#region Vector4
else if (typeToConvertTo == typeof(Vector4))
{
if (string.IsNullOrEmpty(value))
{
return new Vector4(0, 0, 0, 0);
}
value = StripParenthesis(value);
// Split the string
string[] stringvalues = value.Split(new char[] { ',' });
if (stringvalues.Length != 4)
{
throw new ArgumentException("String to Vector4 conversion requires 4 values, " +
"supplied string contains " + stringvalues.Length + " values", "value");
}
// Convert to floats
float[] values = new float[4];
for (int i = 0; i < values.Length; i++)
{
values[i] = float.Parse(stringvalues[i], CultureInfo.InvariantCulture);
}
return new Vector4(values[0], values[1], values[2], values[3]);
}
#endregion
#endif
#region enum
#if WINDOWS_8
else if (typeToConvertTo.IsEnum())
#else
else if (typeToConvertTo.IsEnum)
#endif
{
#if DEBUG
if (string.IsNullOrEmpty(value))
{
throw new InvalidOperationException("Error trying to create enum value for empty string. Enum type: " + typeToConvertTo);
}
#endif
bool ignoreCase = true; // 3rd arugment needed for 360
return Enum.Parse(typeToConvertTo, value, ignoreCase); // built-in .NET version
//return StringEnum.Parse(typeToConvertTo, value);
}
#endregion
#region List<T>
else if (IsGenericList(typeToConvertTo))
{
return CreateGenericListFrom(value, typeToConvertTo, contentManagerName);
}
#endregion
#endregion
// Why do we catch exceptions here? That seems baaaad
//catch (Exception)
//{
// //int m = 3;
//}
if (!handled)
{
throw new NotImplementedException("Cannot convert the value " + value + " to the type " +
typeToConvertTo.ToString());
}
}
return toReturn;
}
private static void TryHandleComplexType(string value, Type typeToConvertTo, out bool handled, out object toReturn)
{
handled = false;
toReturn = null;
if (value.StartsWith("new "))
{
string typeAfterNewString = value.Substring("new ".Length, value.IndexOf('(') - "new ".Length);
Type foundType = null;
if (mUnqualifiedTypeDictionary.ContainsKey(typeAfterNewString))
{
foundType = mUnqualifiedTypeDictionary[typeAfterNewString];
}
else
{
foundType = TryToGetTypeFromAssemblies(typeAfterNewString);
}
if (foundType != null)
{
int openingParen = value.IndexOf('(');
// Make sure to get the last parenthesis, in case one of the inner properties is a complex type
int closingParen = value.LastIndexOf(')');
// Make sure valid parenthesis were found
if (openingParen < 0 || closingParen < 0)
throw new InvalidOperationException("Type definition did not have a matching pair of opening and closing parenthesis");
if (openingParen > closingParen)
throw new InvalidOperationException("Type definition has parenthesis in the incorrect order");
string valueInsideParens = value.Substring(openingParen + 1, closingParen - (openingParen + 1));
toReturn = CreateInstanceFromNamedAssignment(foundType, valueInsideParens);
}
else
{
throw new InvalidOperationException("Could not find a type in the assemblies for " + foundType);
}
handled = true;
}
else if (value.Contains("="))
{
// They're using the "x=0,y=0,z=0" syntax
handled = true;
toReturn = CreateInstanceFromNamedAssignment(typeToConvertTo, value);
}
}
public static List<string> SplitProperties(string value)
{
var splitOnComma = value.Split(',');
List<string> toReturn = new List<string>();
// We may have a List declaration, or a string with commas in it, so we need to account for that
// For now I'm going to handle the list declaration because that's what I need for Baron, but will
// eventually return to this and make it more robust to handle strings with commas too.
int parenCount = 0;
int quoteCount = 0;
foreach (string entryInSplit in splitOnComma)
{
bool shouldCombine = parenCount != 0 || quoteCount != 0;
parenCount += entryInSplit.CountOf("(");
parenCount -= entryInSplit.CountOf(")");
quoteCount += entryInSplit.CountOf("\"");
quoteCount = (quoteCount % 2);
if (shouldCombine)
{
toReturn[toReturn.Count - 1] = toReturn[toReturn.Count - 1] + ',' + entryInSplit;
}
else
{
toReturn.Add(entryInSplit);
}
}
return toReturn;
}
private static object CreateGenericListFrom(string value, Type listType, string contentManagerName)
{
object newObject = Activator.CreateInstance(listType);
Type genericType = listType.GetGenericArguments()[0];
MethodInfo add = listType.GetMethod("Add");
int start = value.IndexOf("(") + 1;
int end = value.IndexOf(")");
if (end > 0)
{
string insideOfParens = value.Substring(start, end - start);
// Cheat for now, make it more robust later
var values = SplitProperties(insideOfParens);
object[] arguments = new object[1];
foreach (var itemInList in values)
{
object converted = ConvertStringToType(itemInList, genericType, contentManagerName, true);
arguments[0] = converted;
add.Invoke(newObject, arguments);
}
}
return newObject;
}
private static Type TryToGetTypeFromAssemblies(string typeAfterNewString)
{
Type foundType = null;
#if WINDOWS_8
foundType = TryToGetTypeFromAssembly(typeAfterNewString, FlatRedBallServices.Game.GetType().GetTypeInfo().Assembly);
if (foundType == null)
{
#if DEBUG
if (TopLevelAssembly == null)
{
throw new Exception("The TopLevelAssembly member must be set before it is used. It is currently null");
}
#endif
foundType = TryToGetTypeFromAssembly(typeAfterNewString, TopLevelAssembly);
}
if (foundType == null)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, typeof(Vector3).GetTypeInfo().Assembly);
}
#else
if (foundType == null)
{
foreach (var assembly in AdditionalAssemblies)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, assembly);
if (foundType != null)
{
break;
}
}
}
if(foundType == null)
{
foundType = TryToGetTypeFromAssembly(typeAfterNewString, Assembly.GetExecutingAssembly());
}
if (foundType == null)
{
#if WINDOWS
foundType = TryToGetTypeFromAssembly(typeAfterNewString, Assembly.GetEntryAssembly());
#endif
}
#endif
if (foundType == null)
{
throw new ArgumentException("Could not find the type for " + typeAfterNewString);
}
else
{
mUnqualifiedTypeDictionary.Add(typeAfterNewString, foundType);
}
return foundType;
}
private static Type TryToGetTypeFromAssembly(string typeAfterNewString, Assembly assembly)
{
Type foundType = null;
// Make sure the type isn't null, and the type string is trimmed to make the compare valid
if (typeAfterNewString == null)
return null;
typeAfterNewString = typeAfterNewString.Trim();
// Is this slow? Do we want to cache off the Type[]?
#if WINDOWS_8
IEnumerable<Type> types = assembly.ExportedTypes;
#else
IEnumerable<Type> types = assembly.GetTypes();
#endif
foreach (Type type in types)
{
if (type.Name == typeAfterNewString || type.FullName == typeAfterNewString)
{
foundType = type;
break;
}
}
return foundType;
}
private static object CreateInstanceFromNamedAssignment(Type type, string value)
{
object returnObject = null;
returnObject = Activator.CreateInstance(type);
if (!string.IsNullOrEmpty(value))
{
var split = SplitProperties(value);
foreach (string assignment in split)
{
int indexOfEqual = assignment.IndexOf('=');
// If the assignment is not in the proper Name=Value format, ignore it
if (indexOfEqual < 0)
continue;
// Make sure the = sign isn't the last character in the assignment
if (indexOfEqual >= assignment.Length - 1)
continue;
string variableName = assignment.Substring(0, indexOfEqual).Trim();
string whatToassignTo = assignment.Substring(indexOfEqual + 1, assignment.Length - (indexOfEqual + 1));
FieldInfo fieldInfo = type.GetField(variableName);
if (fieldInfo != null)
{
Type fieldType = fieldInfo.FieldType;
StripQuotesIfNecessary(ref whatToassignTo);
object assignValue = ConvertStringToType(whatToassignTo, fieldType);
fieldInfo.SetValue(returnObject, assignValue);
}
else
{
PropertyInfo propertyInfo = type.GetProperty(variableName);
#if DEBUG
if (propertyInfo == null)
{
throw new ArgumentException("Could not find the field/property " + variableName + " in the type " + type.Name);
}
#endif
Type propertyType = propertyInfo.PropertyType;
StripQuotesIfNecessary(ref whatToassignTo);
object assignValue = ConvertStringToType(whatToassignTo, propertyType);
propertyInfo.SetValue(returnObject, assignValue, null);
}
}
}
return returnObject;
}
public static bool IsGenericList(Type type)
{
bool isGenericList = false;
#if WINDOWS_8
// Not sure why we check the declaring type. I think declaring
// type is for when a class is inside of another class
//if (type.DeclaringType.IsGenericParameter && (type.GetGenericTypeDefinition() == typeof(List<>)))
if (type.GetGenericTypeDefinition() == typeof(List<>))
#else
if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>)))
#endif
{
isGenericList = true;
}
return isGenericList;
}
private static void StripQuotesIfNecessary(ref string whatToassignTo)
{
if (whatToassignTo != null)
{
string trimmed = whatToassignTo.Trim();
if (trimmed.StartsWith("\"") &&
trimmed.EndsWith("\"") && trimmed.Length > 1)
{
whatToassignTo = trimmed.Substring(1, trimmed.Length - 2);
}
}
}
//Remove any parenthesis at the start and end of the string.
private static string StripParenthesis(string value)
{
string result = value;
if (result.StartsWith("("))
{
int startIndex = 1;
int endIndex = result.Length - 1;
if (result.EndsWith(")"))
endIndex -= 1;
result = result.Substring(startIndex, endIndex);
}
return result;
}
public override string ToString()
{
return Property + " = " + Value;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class is a wrapper used to contain the data needed to execute a task. This class
/// is initially instantiated on the engine side by the scheduler and submitted to the node.
/// The node completes the class instantiating by providing the object with node side data.
/// This class is distinct from the task engine in that it (possibly) travels cross process
/// between the engine and the node carrying with it the data needed to instantiate the task
/// engine. The task engine can't subsume this class because the task engine is bound to the
/// node process and can't travel cross process.
/// </summary>
internal class TaskExecutionState
{
#region Constructors
/// <summary>
/// The constructor obtains the state information and the
/// callback delegate.
/// </summary>
internal TaskExecutionState
(
TaskExecutionMode howToExecuteTask,
Lookup lookupForInference,
Lookup lookupForExecution,
XmlElement taskXmlNode,
ITaskHost hostObject,
string projectFileOfTaskNode,
string parentProjectFullFileName,
string executionDirectory,
int handleId,
BuildEventContext buildEventContext
)
{
ErrorUtilities.VerifyThrow(taskXmlNode != null, "Must have task node");
this.howToExecuteTask = howToExecuteTask;
this.lookupForInference = lookupForInference;
this.lookupForExecution = lookupForExecution;
this.hostObject = hostObject;
this.projectFileOfTaskNode = projectFileOfTaskNode;
this.parentProjectFullFileName = parentProjectFullFileName;
this.executionDirectory = executionDirectory;
this.handleId = handleId;
this.buildEventContext = buildEventContext;
this.taskXmlNode = taskXmlNode;
}
#endregion
#region Properties
internal int HandleId
{
get
{
return this.handleId;
}
set
{
this.handleId = value;
}
}
internal EngineLoggingServices LoggingService
{
get
{
return this.loggingService;
}
set
{
this.loggingService = value;
}
}
internal TaskExecutionModule ParentModule
{
get
{
return this.parentModule;
}
set
{
this.parentModule = value;
}
}
internal string ExecutionDirectory
{
get
{
return this.executionDirectory;
}
}
internal bool ProfileExecution
{
get
{
return this.profileExecution;
}
set
{
this.profileExecution = value;
}
}
#endregion
#region Methods
/// <summary>
/// The thread procedure executes the tasks and calls callback once it is done
/// </summary>
virtual internal void ExecuteTask()
{
bool taskExecutedSuccessfully = true;
Exception thrownException = null;
bool dontPostOutputs = false;
if (profileExecution)
{
startTime = DateTime.Now.Ticks;
}
try
{
TaskEngine taskEngine = new TaskEngine(
taskXmlNode,
hostObject,
projectFileOfTaskNode,
parentProjectFullFileName,
loggingService,
handleId,
parentModule,
buildEventContext);
// Set the directory to the one appropriate for the task
if (FileUtilities.GetCurrentDirectoryStaticBuffer(currentDirectoryBuffer) != executionDirectory)
{
Directory.SetCurrentDirectory(executionDirectory);
}
// if we're skipping task execution because the target is up-to-date, we
// need to go ahead and infer all the outputs that would have been emitted;
// alternatively, if we're doing an incremental build, we need to infer the
// outputs that would have been produced if all the up-to-date items had
// been built by the task
if ((howToExecuteTask & TaskExecutionMode.InferOutputsOnly) != TaskExecutionMode.Invalid)
{
bool targetInferenceSuccessful = false;
targetInferenceSuccessful =
TaskEngineExecuteTask
( taskEngine,
TaskExecutionMode.InferOutputsOnly,
lookupForInference
);
ErrorUtilities.VerifyThrow(targetInferenceSuccessful, "A task engine should never fail to infer its task's up-to-date outputs.");
}
// execute the task using the items that need to be (re)built
if ((howToExecuteTask & TaskExecutionMode.ExecuteTaskAndGatherOutputs) != TaskExecutionMode.Invalid)
{
taskExecutedSuccessfully =
TaskEngineExecuteTask
( taskEngine,
TaskExecutionMode.ExecuteTaskAndGatherOutputs,
lookupForExecution
);
}
}
// We want to catch all exceptions and pass them on to the engine
catch (Exception e)
{
thrownException = e;
taskExecutedSuccessfully = false;
// In single threaded mode the exception can be thrown on the current thread
if (parentModule.RethrowTaskExceptions())
{
dontPostOutputs = true;
throw;
}
}
finally
{
if (!dontPostOutputs)
{
long executionTime = profileExecution ? DateTime.Now.Ticks - startTime : 0;
// Post the outputs to the engine
parentModule.PostTaskOutputs(handleId, taskExecutedSuccessfully, thrownException, executionTime);
}
}
}
/// <summary>
/// This method is called to adjust the execution time for the task by subtracting the time
/// spent waiting for results
/// </summary>
/// <param name="entryTime"></param>
internal void NotifyOfWait(long waitStartTime)
{
// Move the start time forward by the period of the wait
startTime += (DateTime.Now.Ticks - waitStartTime);
}
#region MethodsNeededForUnitTesting
/// <summary>
/// Since we could not derrive from TaskEngine and have no Interface, we need to overide the method in here and
/// replace the calls when testing the class because of the calls to TaskEngine. If at a future time we get a mock task
/// engine, Interface or a non sealed TaskEngine these methods can disappear.
/// </summary>
/// <returns></returns>
virtual internal bool TaskEngineExecuteTask(
TaskEngine taskEngine,
TaskExecutionMode howTaskShouldBeExecuted,
Lookup lookup
)
{
return taskEngine.ExecuteTask
(
howTaskShouldBeExecuted,
lookup
);
}
#endregion
#endregion
#region Fields set by the Engine thread
private TaskExecutionMode howToExecuteTask;
private Lookup lookupForInference;
private Lookup lookupForExecution;
private ITaskHost hostObject;
private string projectFileOfTaskNode;
private string parentProjectFullFileName;
private string executionDirectory;
private int handleId;
private BuildEventContext buildEventContext;
#endregion
#region Fields set by the Task thread
private TaskExecutionModule parentModule;
private EngineLoggingServices loggingService;
private XmlElement taskXmlNode;
private long startTime;
private bool profileExecution;
private static StringBuilder currentDirectoryBuffer = new StringBuilder(270);
#endregion
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Collections.Generic
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
[Serializable]
////[TypeDependencyAttribute( "System.Collections.Generic.GenericEqualityComparer`1" )]
[Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_EqualityComparer_of_T" )]
[Microsoft.Zelig.Internals.TypeDependency( typeof(System.Collections.Generic.GenericEqualityComparer<>) )]
public abstract class EqualityComparer<T> : IEqualityComparer, IEqualityComparer<T>
{
static EqualityComparer<T> defaultComparer;
public static EqualityComparer<T> Default
{
get
{
EqualityComparer<T> comparer = defaultComparer;
if(comparer == null)
{
comparer = CreateComparer();
defaultComparer = comparer;
}
return comparer;
}
}
[MethodImpl( MethodImplOptions.InternalCall )]
private static extern EqualityComparer<T> CreateComparer();
//// {
//// Type t = typeof( T );
////
//// // Specialize type byte for performance reasons
//// if(t == typeof( byte ))
//// {
//// return (EqualityComparer<T>)(object)(new ByteEqualityComparer());
//// }
////
//// // If T implements IEquatable<T> return a GenericEqualityComparer<T>
//// if(typeof( IEquatable<T> ).IsAssignableFrom( t ))
//// {
//// //return (EqualityComparer<T>)Activator.CreateInstance(typeof(GenericEqualityComparer<>).MakeGenericType(t));
//// return (EqualityComparer<T>)(typeof( GenericEqualityComparer<int> ).TypeHandle.CreateInstanceForAnotherGenericParameter( t ));
//// }
////
//// // If T is a Nullable<U> where U implements IEquatable<U> return a NullableEqualityComparer<U>
//// if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof( Nullable<> ))
//// {
//// Type u = t.GetGenericArguments()[0];
//// if(typeof( IEquatable<> ).MakeGenericType( u ).IsAssignableFrom( u ))
//// {
//// //return (EqualityComparer<T>)Activator.CreateInstance(typeof(NullableEqualityComparer<>).MakeGenericType(u));
//// return (EqualityComparer<T>)(typeof( NullableEqualityComparer<int> ).TypeHandle.CreateInstanceForAnotherGenericParameter( u ));
//// }
//// }
////
//// // Otherwise return an ObjectEqualityComparer<T>
//// return new ObjectEqualityComparer<T>();
//// }
public abstract bool Equals( T x, T y );
public abstract int GetHashCode( T obj );
internal virtual int IndexOf( T[] array, T value, int startIndex, int count )
{
int endIndex = startIndex + count;
for(int i = startIndex; i < endIndex; i++)
{
if(Equals( array[i], value )) return i;
}
return -1;
}
internal virtual int LastIndexOf( T[] array, T value, int startIndex, int count )
{
int endIndex = startIndex - count + 1;
for(int i = startIndex; i >= endIndex; i--)
{
if(Equals( array[i], value )) return i;
}
return -1;
}
int IEqualityComparer.GetHashCode( object obj )
{
if(obj == null) return 0;
if(obj is T) return GetHashCode( (T)obj );
ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArgumentForComparison );
return 0;
}
bool IEqualityComparer.Equals( object x, object y )
{
if(x == y) return true;
if(x == null || y == null) return false;
if((x is T) && (y is T)) return Equals( (T)x, (T)y );
ThrowHelper.ThrowArgumentException( ExceptionResource.Argument_InvalidArgumentForComparison );
return false;
}
}
// The methods in this class look identical to the inherited methods, but the calls
// to Equal bind to IEquatable<T>.Equals(T) instead of Object.Equals(Object)
[Serializable]
[Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_GenericEqualityComparer_of_T" )]
internal class GenericEqualityComparer<T> : EqualityComparer<T> where T : IEquatable<T>
{
public override bool Equals( T x, T y )
{
if(x != null)
{
if(y != null) return x.Equals( y );
return false;
}
if(y != null) return false;
return true;
}
public override int GetHashCode( T obj )
{
if(obj == null) return 0;
return obj.GetHashCode();
}
internal override int IndexOf( T[] array, T value, int startIndex, int count )
{
int endIndex = startIndex + count;
if(value == null)
{
for(int i = startIndex; i < endIndex; i++)
{
if(array[i] == null) return i;
}
}
else
{
for(int i = startIndex; i < endIndex; i++)
{
if(array[i] != null && array[i].Equals( value )) return i;
}
}
return -1;
}
internal override int LastIndexOf( T[] array, T value, int startIndex, int count )
{
int endIndex = startIndex - count + 1;
if(value == null)
{
for(int i = startIndex; i >= endIndex; i--)
{
if(array[i] == null) return i;
}
}
else
{
for(int i = startIndex; i >= endIndex; i--)
{
if(array[i] != null && array[i].Equals( value )) return i;
}
}
return -1;
}
// Equals method for the comparer itself.
public override bool Equals( Object obj )
{
GenericEqualityComparer<T> comparer = obj as GenericEqualityComparer<T>;
return comparer != null;
}
public override int GetHashCode()
{
return this.GetType().Name.GetHashCode();
}
}
[Serializable]
[Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_NullableEqualityComparer_of_T" )]
internal class NullableEqualityComparer<T> : EqualityComparer< Nullable<T> > where T : struct, IEquatable<T>
{
public override bool Equals( Nullable<T> x, Nullable<T> y )
{
if(x.HasValue)
{
if(y.HasValue) return x.value.Equals( y.value );
return false;
}
if(y.HasValue) return false;
return true;
}
public override int GetHashCode( Nullable<T> obj )
{
return obj.GetHashCode();
}
internal override int IndexOf( Nullable<T>[] array, Nullable<T> value, int startIndex, int count )
{
int endIndex = startIndex + count;
if(!value.HasValue)
{
for(int i = startIndex; i < endIndex; i++)
{
if(!array[i].HasValue) return i;
}
}
else
{
for(int i = startIndex; i < endIndex; i++)
{
if(array[i].HasValue && array[i].value.Equals( value.value )) return i;
}
}
return -1;
}
internal override int LastIndexOf( Nullable<T>[] array, Nullable<T> value, int startIndex, int count )
{
int endIndex = startIndex - count + 1;
if(!value.HasValue)
{
for(int i = startIndex; i >= endIndex; i--)
{
if(!array[i].HasValue) return i;
}
}
else
{
for(int i = startIndex; i >= endIndex; i--)
{
if(array[i].HasValue && array[i].value.Equals( value.value )) return i;
}
}
return -1;
}
// Equals method for the comparer itself.
public override bool Equals( Object obj )
{
NullableEqualityComparer<T> comparer = obj as NullableEqualityComparer<T>;
return comparer != null;
}
public override int GetHashCode()
{
return this.GetType().Name.GetHashCode();
}
}
[Serializable]
[Microsoft.Zelig.Internals.WellKnownType( "System_Collections_Generic_ObjectEqualityComparer_of_T" )]
internal class ObjectEqualityComparer<T> : EqualityComparer<T>
{
public override bool Equals( T x, T y )
{
if(x != null)
{
if(y != null) return x.Equals( y );
return false;
}
if(y != null) return false;
return true;
}
public override int GetHashCode( T obj )
{
if(obj == null) return 0;
return obj.GetHashCode();
}
internal override int IndexOf( T[] array, T value, int startIndex, int count )
{
int endIndex = startIndex + count;
if(value == null)
{
for(int i = startIndex; i < endIndex; i++)
{
if(array[i] == null) return i;
}
}
else
{
for(int i = startIndex; i < endIndex; i++)
{
if(array[i] != null && array[i].Equals( value )) return i;
}
}
return -1;
}
internal override int LastIndexOf( T[] array, T value, int startIndex, int count )
{
int endIndex = startIndex - count + 1;
if(value == null)
{
for(int i = startIndex; i >= endIndex; i--)
{
if(array[i] == null) return i;
}
}
else
{
for(int i = startIndex; i >= endIndex; i--)
{
if(array[i] != null && array[i].Equals( value )) return i;
}
}
return -1;
}
// Equals method for the comparer itself.
public override bool Equals( Object obj )
{
ObjectEqualityComparer<T> comparer = obj as ObjectEqualityComparer<T>;
return comparer != null;
}
public override int GetHashCode()
{
return this.GetType().Name.GetHashCode();
}
}
// Performance of IndexOf on byte array is very important for some scenarios.
// We will call the C runtime function memchr, which is optimized.
[Serializable]
internal class ByteEqualityComparer : EqualityComparer<byte>
{
public override bool Equals( byte x, byte y )
{
return x == y;
}
public override int GetHashCode( byte b )
{
return b.GetHashCode();
}
//// internal unsafe override int IndexOf( byte[] array, byte value, int startIndex, int count )
//// {
//// if(array == null)
//// {
//// throw new ArgumentNullException( "array" );
//// }
////
//// if(startIndex < 0)
//// {
//// throw new ArgumentOutOfRangeException( "startIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) );
//// }
////
//// if(count < 0)
//// {
//// throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_Count" ) );
//// }
////
//// if(count > array.Length - startIndex)
//// {
//// throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidOffLen" ) );
//// }
////
//// if(count == 0) return -1;
////
//// fixed(byte* pbytes = array)
//// {
//// return Buffer.IndexOfByte( pbytes, value, startIndex, count );
//// }
//// }
////
//// internal override int LastIndexOf( byte[] array, byte value, int startIndex, int count )
//// {
//// int endIndex = startIndex - count + 1;
//// for(int i = startIndex; i >= endIndex; i--)
//// {
//// if(array[i] == value) return i;
//// }
//// return -1;
//// }
////
//// // Equals method for the comparer itself.
//// public override bool Equals( Object obj )
//// {
//// ByteEqualityComparer comparer = obj as ByteEqualityComparer;
//// return comparer != null;
//// }
////
//// public override int GetHashCode()
//// {
//// return this.GetType().Name.GetHashCode();
//// }
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.CodeDom;
using Mono.VisualC.Interop;
using Mono.VisualC.Interop.ABI;
using Mono.VisualC.Interop.Util;
namespace Mono.VisualC.Code.Atoms {
public class Method : CodeContainer {
public Access Access { get; set; }
public bool IsVirtual { get; set; }
public bool IsStatic { get; set; }
public bool IsConst { get; set; }
public bool IsConstructor { get; set; }
public bool IsDestructor { get; set; }
public CppType RetType { get; set; }
public IList<NameTypePair<CppType>> Parameters { get; set; }
public Class Klass { get; set; }
private string formatted_name;
// for testing:
// FIXME: make this Nullable, auto implemented property and remove bool field once this won't cause gmcs to crash
public NameTypePair<Type> Mangled {
get {
if (!hasMangledInfo) throw new InvalidOperationException ("No mangle info present.");
return mangled;
}
set {
mangled = value;
hasMangledInfo = true;
}
}
private NameTypePair<Type> mangled;
private bool hasMangledInfo = false;
public Method (string name)
{
Name = name;
Parameters = new List<NameTypePair<CppType>> ();
}
internal protected override object InsideCodeTypeDeclaration (CodeTypeDeclaration decl)
{
if (decl.IsClass) {
var method = CreateWrapperMethod ();
if (method == null || CommentedOut)
return null;
if (Comment != null)
method.Comments.Add (new CodeCommentStatement (Comment));
decl.Members.Add (method);
return method;
} else if (decl.IsInterface) {
CodeTypeMember method = CreateInterfaceMethod ();
CodeTypeMember member;
if (CommentedOut) {
member = new CodeSnippetTypeMember ();
member.Comments.Add (new CodeCommentStatement (method.CommentOut (current_code_provider)));
} else
member = method;
if (Comment != null)
member.Comments.Insert (0, new CodeCommentStatement (Comment));
decl.Members.Add (member);
}
return null;
}
internal protected override object InsideCodeStatementCollection (CodeStatementCollection stmts)
{
List<CodeExpression> arguments = new List<CodeExpression> ();
var native = new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "Native");
var native_ptr = new CodeFieldReferenceExpression (new CodeThisReferenceExpression (), "native_ptr");
if (!IsStatic)
arguments.Add (native);
foreach (var param in Parameters) {
// FIXME: handle typenames better
if (param.Type.ElementType != CppTypes.Typename) {
Type managedType = param.Type.ToManagedType ();
if (managedType != null && managedType.IsByRef) {
arguments.Add (new CodeDirectionExpression (FieldDirection.Ref, new CodeArgumentReferenceExpression (param.Name)));
continue;
}
}
arguments.Add (new CodeArgumentReferenceExpression (param.Name));
}
// FIXME: Does just specifying the field name work for all code generators?
var impl = new CodeFieldReferenceExpression { FieldName = "impl" };
if (IsConstructor) {
var alloc = new CodeMethodInvokeExpression (impl, "Alloc", new CodeThisReferenceExpression ());
stmts.Add (new CodeAssignStatement (native_ptr, alloc));
}
var invoke = new CodeMethodInvokeExpression (impl, Name, arguments.ToArray ());
if (RetType.Equals (CppTypes.Void) || IsConstructor)
stmts.Add (invoke);
else
stmts.Add (new CodeMethodReturnStatement (invoke));
if (IsDestructor)
stmts.Add (new CodeMethodInvokeExpression (native, "Dispose"));
return null;
}
private CodeMemberMethod CreateInterfaceMethod ()
{
var returnType = ReturnTypeReference;
var method = new CodeMemberMethod {
Name = this.Name,
ReturnType = returnType
};
if (returnType == null) {
Comment = "FIXME: Unknown return type \"" + RetType.ToString () + "\" for method \"" + Name + "\"";;
CommentedOut = true;
method.ReturnType = new CodeTypeReference (typeof (void));
}
if (IsVirtual) method.CustomAttributes.Add (new CodeAttributeDeclaration (typeof (VirtualAttribute).Name));
if (IsConstructor) method.CustomAttributes.Add (new CodeAttributeDeclaration (typeof (ConstructorAttribute).Name));
if (IsDestructor) method.CustomAttributes.Add (new CodeAttributeDeclaration (typeof (DestructorAttribute).Name));
if (IsConst) method.CustomAttributes.Add (new CodeAttributeDeclaration (typeof (ConstAttribute).Name));
if (IsStatic)
method.CustomAttributes.Add (new CodeAttributeDeclaration (typeof (StaticAttribute).Name));
else
method.Parameters.Add (new CodeParameterDeclarationExpression (typeof (CppInstancePtr).Name, "this"));
if (hasMangledInfo)
method.CustomAttributes.Add (new CodeAttributeDeclaration (typeof (AbiTestAttribute).Name,
new CodeAttributeArgument (new CodePrimitiveExpression (Mangled.Name)),
new CodeAttributeArgument ("Abi", new CodeTypeOfExpression (Mangled.Type))));
for (int i = 0; i < Parameters.Count; i++) {
var param = GenerateParameterDeclaration (Parameters [i]);
string paramStr = Parameters [i].Type.ToString ();
if (param == null) {
Comment = "FIXME: Unknown parameter type \"" + paramStr + "\" to method \"" + Name + "\"";
CommentedOut = true;
method.Parameters.Add (new CodeParameterDeclarationExpression (paramStr, Parameters [i].Name));
continue;
}
// FIXME: Only add MangleAs attribute if the managed type chosen would mangle differently by default
if (!IsVirtual && !paramStr.Equals (string.Empty))
param.CustomAttributes.Add (new CodeAttributeDeclaration (typeof (MangleAsAttribute).Name, new CodeAttributeArgument (new CodePrimitiveExpression (paramStr))));
method.Parameters.Add (param);
}
return method;
}
private CodeMemberMethod CreateWrapperMethod ()
{
CodeMemberMethod method;
if (IsConstructor) {
var ctor = new CodeConstructor {
Name = FormattedName,
Attributes = MemberAttributes.Public
};
if (Klass.Bases.Count > 0) {
var typeInfo = new CodeFieldReferenceExpression (new CodeFieldReferenceExpression { FieldName = "impl" }, "TypeInfo");
ctor.BaseConstructorArgs.Add (typeInfo);
// The first public base class can use the subclass ctor as above, but for the rest, we do this to get the right CppTypeInfo
foreach (Class.BaseClass bc in Klass.Bases.Where (b => b.Access == Access.Public).Skip (1)) {
// FIXME: This won't work if one of the base classes ends up being generic
ctor.Statements.Add (new CodeObjectCreateExpression (bc.Name, typeInfo));
}
ctor.Statements.Add (new CodeMethodInvokeExpression (typeInfo, "CompleteType"));
}
method = ctor;
} else if (IsDestructor)
method = new CodeMemberMethod {
Name = "Dispose",
Attributes = MemberAttributes.Public
};
else
method = new CodeMemberMethod {
Name = FormattedName,
Attributes = MemberAttributes.Public,
ReturnType = ReturnTypeReference
};
if (IsStatic)
method.Attributes |= MemberAttributes.Static;
else if (!IsVirtual && !IsDestructor)
// I'm only making methods that are virtual in C++ virtual in managed code.
// I think it is the right thing to do because the consumer of the API might not
// get the intended effect if the managed method is overridden and the native method is not.
method.Attributes |= MemberAttributes.Final;
else if (IsVirtual && !IsDestructor)
method.CustomAttributes.Add (new CodeAttributeDeclaration (typeof (OverrideNativeAttribute).Name));
for (int i = 0; i < Parameters.Count; i++) {
var param = GenerateParameterDeclaration (Parameters [i]);
if (param == null)
return null;
method.Parameters.Add (param);
}
return method;
}
public CodeTypeReference ReturnTypeReference {
get {
CodeTypeReference returnType;
if (RetType.ElementType == CppTypes.Typename)
returnType = new CodeTypeReference (RetType.ElementTypeName, CodeTypeReferenceOptions.GenericTypeParameter);
else {
Type managedType = RetType.ToManagedType ();
if (managedType != null && managedType.IsByRef)
returnType = new CodeTypeReference (typeof (IntPtr));
else if (managedType != null && managedType != typeof (ICppObject))
returnType = new CodeTypeReference (managedType);
else
returnType = RetType.TypeReference ();
}
return returnType;
}
}
private CodeParameterDeclarationExpression GenerateParameterDeclaration (NameTypePair<CppType> param)
{
CodeParameterDeclarationExpression paramDecl;
if (param.Type.ElementType == CppTypes.Typename)
paramDecl = new CodeParameterDeclarationExpression (param.Type.ElementTypeName, param.Name);
else {
Type managedType = param.Type.ToManagedType ();
CodeTypeReference typeRef = param.Type.TypeReference ();
if (managedType != null && managedType.IsByRef)
paramDecl = new CodeParameterDeclarationExpression (managedType.GetElementType (), param.Name) { Direction = FieldDirection.Ref };
else if (managedType != null && managedType != typeof (ICppObject))
paramDecl = new CodeParameterDeclarationExpression (managedType, param.Name);
else if (typeRef != null)
paramDecl = new CodeParameterDeclarationExpression (typeRef, param.Name);
else
return null;
}
return paramDecl;
}
public string FormattedName {
get {
if (formatted_name == null) {
string upper = Name.ToUpper ();
StringBuilder sb = new StringBuilder (Name.Length);
for (int i = 0; i < Name.Length; i++) {
if (i == 0)
sb.Append (upper [0]);
else if (Name [i] == '_')
sb.Append (upper [++i]);
else
sb.Append (Name [i]);
}
formatted_name = sb.ToString ();
if (formatted_name == Klass.Name)
formatted_name += "1";
}
return formatted_name;
}
set {
formatted_name = value;
}
}
public override void Write (TextWriter writer)
{
throw new NotImplementedException ();
}
}
}
| |
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 ComicBookStoreAPI.Areas.HelpPage.ModelDescriptions;
using ComicBookStoreAPI.Areas.HelpPage.Models;
namespace ComicBookStoreAPI.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.UI;
using System.Collections;
namespace classes
{
//Instead of requing all sorts of SQL to return full country names, use this look-up table with the country code as key
public class tcCountryTable
{
private static Dictionary<string,string> mcCountryTable = null;
public static string CodeToFull(string apanCode)
{
string lpanFullName = null;
if (mcCountryTable == null)
{
mcCountryTable = InitializeTable();
}
try
{
lpanFullName = mcCountryTable[apanCode];
}
catch
{
//Do nothing
}
finally
{
if (lpanFullName == null)
{
lpanFullName = "";
}
}
return lpanFullName;
}
private static Dictionary<string,string> InitializeTable()
{
//Note capacity is set roughly 2x the number of entries, this reduces collision and increases look-up speed
Dictionary<string, string> lcReturn = new Dictionary<string, string>(500);
lcReturn.Add("A1", "Anonymous Proxy");
lcReturn.Add("A2", "Satellite Provider");
lcReturn.Add("AD", "Andorra");
lcReturn.Add("AE", "United Arab Emirates");
lcReturn.Add("AF", "Afghanistan");
lcReturn.Add("AG", "Antigua and Barbuda");
lcReturn.Add("AI", "Anguilla");
lcReturn.Add("AL", "Albania");
lcReturn.Add("AM", "Armenia");
lcReturn.Add("AN", "Netherlands Antilles");
lcReturn.Add("AO", "Angola");
lcReturn.Add("AP", "Asia/Pacific Region");
lcReturn.Add("AQ", "Antarctica");
lcReturn.Add("AR", "Argentina");
lcReturn.Add("AS", "American Samoa");
lcReturn.Add("AT", "Austria");
lcReturn.Add("AU", "Australia");
lcReturn.Add("AW", "Aruba");
lcReturn.Add("AX", "Aland Islands");
lcReturn.Add("AZ", "Azerbaijan");
lcReturn.Add("BA", "Bosnia and Herzegovina");
lcReturn.Add("BB", "Barbados");
lcReturn.Add("BD", "Bangladesh");
lcReturn.Add("BE", "Belgium");
lcReturn.Add("BF", "Burkina Faso");
lcReturn.Add("BG", "Bulgaria");
lcReturn.Add("BH", "Bahrain");
lcReturn.Add("BI", "Burundi");
lcReturn.Add("BJ", "Benin");
lcReturn.Add("BM", "Bermuda");
lcReturn.Add("BN", "Brunei Darussalam");
lcReturn.Add("BO", "Bolivia");
lcReturn.Add("BR", "Brazil");
lcReturn.Add("BS", "Bahamas");
lcReturn.Add("BT", "Bhutan");
lcReturn.Add("BV", "Bouvet Island");
lcReturn.Add("BW", "Botswana");
lcReturn.Add("BY", "Belarus");
lcReturn.Add("BZ", "Belize");
lcReturn.Add("CA", "Canada");
lcReturn.Add("CC", "Cocos (Keeling) Islands");
lcReturn.Add("CD", "Congo, The Democratic Republic of the");
lcReturn.Add("CF", "Central African Republic");
lcReturn.Add("CG", "Congo");
lcReturn.Add("CH", "Switzerland");
lcReturn.Add("CI", "Cote D'Ivoire");
lcReturn.Add("CK", "Cook Islands");
lcReturn.Add("CL", "Chile");
lcReturn.Add("CM", "Cameroon");
lcReturn.Add("CN", "China");
lcReturn.Add("CO", "Colombia");
lcReturn.Add("CR", "Costa Rica");
lcReturn.Add("CU", "Cuba");
lcReturn.Add("CV", "Cape Verde");
lcReturn.Add("CX", "Christmas Island");
lcReturn.Add("CY", "Cyprus");
lcReturn.Add("CZ", "Czech Republic");
lcReturn.Add("DE", "Germany");
lcReturn.Add("DJ", "Djibouti");
lcReturn.Add("DK", "Denmark");
lcReturn.Add("DM", "Dominica");
lcReturn.Add("DO", "Dominican Republic");
lcReturn.Add("DZ", "Algeria");
lcReturn.Add("EC", "Ecuador");
lcReturn.Add("EE", "Estonia");
lcReturn.Add("EG", "Egypt");
lcReturn.Add("EH", "Western Sahara");
lcReturn.Add("ER", "Eritrea");
lcReturn.Add("ES", "Spain");
lcReturn.Add("ET", "Ethiopia");
lcReturn.Add("EU", "Europe");
lcReturn.Add("FI", "Finland");
lcReturn.Add("FJ", "Fiji");
lcReturn.Add("FK", "Falkland Islands (Malvinas)");
lcReturn.Add("FM", "Micronesia, Federated States of");
lcReturn.Add("FO", "Faroe Islands");
lcReturn.Add("FR", "France");
lcReturn.Add("GA", "Gabon");
lcReturn.Add("GB", "United Kingdom");
lcReturn.Add("GD", "Grenada");
lcReturn.Add("GE", "Georgia");
lcReturn.Add("GF", "French Guiana");
lcReturn.Add("GG", "Guernsey");
lcReturn.Add("GH", "Ghana");
lcReturn.Add("GI", "Gibraltar");
lcReturn.Add("GL", "Greenland");
lcReturn.Add("GM", "Gambia");
lcReturn.Add("GN", "Guinea");
lcReturn.Add("GP", "Guadeloupe");
lcReturn.Add("GQ", "Equatorial Guinea");
lcReturn.Add("GR", "Greece");
lcReturn.Add("GS", "South Georgia and the South Sandwich Islands");
lcReturn.Add("GT", "Guatemala");
lcReturn.Add("GU", "Guam");
lcReturn.Add("GW", "Guinea-Bissau");
lcReturn.Add("GY", "Guyana");
lcReturn.Add("HK", "Hong Kong");
lcReturn.Add("HN", "Honduras");
lcReturn.Add("HR", "Croatia");
lcReturn.Add("HT", "Haiti");
lcReturn.Add("HU", "Hungary");
lcReturn.Add("ID", "Indonesia");
lcReturn.Add("IE", "Ireland");
lcReturn.Add("IL", "Israel");
lcReturn.Add("IM", "Isle of Man");
lcReturn.Add("IN", "India");
lcReturn.Add("IO", "British Indian Ocean Territory");
lcReturn.Add("IQ", "Iraq");
lcReturn.Add("IR", "Iran, Islamic Republic of");
lcReturn.Add("IS", "Iceland");
lcReturn.Add("IT", "Italy");
lcReturn.Add("JE", "Jersey");
lcReturn.Add("JM", "Jamaica");
lcReturn.Add("JO", "Jordan");
lcReturn.Add("JP", "Japan");
lcReturn.Add("KE", "Kenya");
lcReturn.Add("KG", "Kyrgyzstan");
lcReturn.Add("KH", "Cambodia");
lcReturn.Add("KI", "Kiribati");
lcReturn.Add("KM", "Comoros");
lcReturn.Add("KN", "Saint Kitts and Nevis");
lcReturn.Add("KP", "Korea, Democratic People's Republic of");
lcReturn.Add("KR", "Korea, Republic of");
lcReturn.Add("KW", "Kuwait");
lcReturn.Add("KY", "Cayman Islands");
lcReturn.Add("KZ", "Kazakhstan");
lcReturn.Add("LA", "Lao People's Democratic Republic");
lcReturn.Add("LB", "Lebanon");
lcReturn.Add("LC", "Saint Lucia");
lcReturn.Add("LI", "Liechtenstein");
lcReturn.Add("LK", "Sri Lanka");
lcReturn.Add("LR", "Liberia");
lcReturn.Add("LS", "Lesotho");
lcReturn.Add("LT", "Lithuania");
lcReturn.Add("LU", "Luxembourg");
lcReturn.Add("LV", "Latvia");
lcReturn.Add("LY", "Libyan Arab Jamahiriya");
lcReturn.Add("MA", "Morocco");
lcReturn.Add("MC", "Monaco");
lcReturn.Add("MD", "Moldova, Republic of");
lcReturn.Add("ME", "Montenegro");
lcReturn.Add("MG", "Madagascar");
lcReturn.Add("MH", "Marshall Islands");
lcReturn.Add("MK", "Macedonia");
lcReturn.Add("ML", "Mali");
lcReturn.Add("MM", "Myanmar");
lcReturn.Add("MN", "Mongolia");
lcReturn.Add("MO", "Macau");
lcReturn.Add("MP", "Northern Mariana Islands");
lcReturn.Add("MQ", "Martinique");
lcReturn.Add("MR", "Mauritania");
lcReturn.Add("MS", "Montserrat");
lcReturn.Add("MT", "Malta");
lcReturn.Add("MU", "Mauritius");
lcReturn.Add("MV", "Maldives");
lcReturn.Add("MW", "Malawi");
lcReturn.Add("MX", "Mexico");
lcReturn.Add("MY", "Malaysia");
lcReturn.Add("MZ", "Mozambique");
lcReturn.Add("NA", "Namibia");
lcReturn.Add("NC", "New Caledonia");
lcReturn.Add("NE", "Niger");
lcReturn.Add("NF", "Norfolk Island");
lcReturn.Add("NG", "Nigeria");
lcReturn.Add("NI", "Nicaragua");
lcReturn.Add("NL", "Netherlands");
lcReturn.Add("NO", "Norway");
lcReturn.Add("NP", "Nepal");
lcReturn.Add("NR", "Nauru");
lcReturn.Add("NU", "Niue");
lcReturn.Add("NZ", "New Zealand");
lcReturn.Add("OM", "Oman");
lcReturn.Add("PA", "Panama");
lcReturn.Add("PE", "Peru");
lcReturn.Add("PF", "French Polynesia");
lcReturn.Add("PG", "Papua New Guinea");
lcReturn.Add("PH", "Philippines");
lcReturn.Add("PK", "Pakistan");
lcReturn.Add("PL", "Poland");
lcReturn.Add("PM", "Saint Pierre and Miquelon");
lcReturn.Add("PR", "Puerto Rico");
lcReturn.Add("PS", "Palestinian Territory, Occupied");
lcReturn.Add("PT", "Portugal");
lcReturn.Add("PW", "Palau");
lcReturn.Add("PY", "Paraguay");
lcReturn.Add("QA", "Qatar");
lcReturn.Add("RE", "Reunion");
lcReturn.Add("RO", "Romania");
lcReturn.Add("RS", "Serbia");
lcReturn.Add("RU", "Russian Federation");
lcReturn.Add("RW", "Rwanda");
lcReturn.Add("SA", "Saudi Arabia");
lcReturn.Add("SB", "Solomon Islands");
lcReturn.Add("SC", "Seychelles");
lcReturn.Add("SD", "Sudan");
lcReturn.Add("SE", "Sweden");
lcReturn.Add("SG", "Singapore");
lcReturn.Add("SH", "Saint Helena");
lcReturn.Add("SI", "Slovenia");
lcReturn.Add("SJ", "Svalbard and Jan Mayen");
lcReturn.Add("SK", "Slovakia");
lcReturn.Add("SL", "Sierra Leone");
lcReturn.Add("SM", "San Marino");
lcReturn.Add("SN", "Senegal");
lcReturn.Add("SO", "Somalia");
lcReturn.Add("SR", "Suriname");
lcReturn.Add("ST", "Sao Tome and Principe");
lcReturn.Add("SV", "El Salvador");
lcReturn.Add("SY", "Syrian Arab Republic");
lcReturn.Add("SZ", "Swaziland");
lcReturn.Add("TC", "Turks and Caicos Islands");
lcReturn.Add("TD", "Chad");
lcReturn.Add("TF", "French Southern Territories");
lcReturn.Add("TG", "Togo");
lcReturn.Add("TH", "Thailand");
lcReturn.Add("TJ", "Tajikistan");
lcReturn.Add("TK", "Tokelau");
lcReturn.Add("TL", "Timor-Leste");
lcReturn.Add("TM", "Turkmenistan");
lcReturn.Add("TN", "Tunisia");
lcReturn.Add("TO", "Tonga");
lcReturn.Add("TR", "Turkey");
lcReturn.Add("TT", "Trinidad and Tobago");
lcReturn.Add("TV", "Tuvalu");
lcReturn.Add("TW", "Taiwan");
lcReturn.Add("TZ", "Tanzania, United Republic of");
lcReturn.Add("UA", "Ukraine");
lcReturn.Add("UG", "Uganda");
lcReturn.Add("UM", "United States Minor Outlying Islands");
lcReturn.Add("US", "United States");
lcReturn.Add("UY", "Uruguay");
lcReturn.Add("UZ", "Uzbekistan");
lcReturn.Add("VA", "Holy See (Vatican City State)");
lcReturn.Add("VC", "Saint Vincent and the Grenadines");
lcReturn.Add("VE", "Venezuela");
lcReturn.Add("VG", "Virgin Islands, British");
lcReturn.Add("VI", "Virgin Islands, U.S.");
lcReturn.Add("VN", "Vietnam");
lcReturn.Add("VU", "Vanuatu");
lcReturn.Add("WF", "Wallis and Futuna");
lcReturn.Add("WS", "Samoa");
lcReturn.Add("YE", "Yemen");
lcReturn.Add("YT", "Mayotte");
lcReturn.Add("ZA", "South Africa");
lcReturn.Add("ZM", "Zambia");
lcReturn.Add("ZW", "Zimbabwe");
return lcReturn;
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
namespace WebsitePanel.Ecommerce.EnterpriseServer
{
public class TCOProvider : SystemPluginBase, IInteractivePaymentGatewayProvider
{
#region Error Messages
public const string CURRENCY_NOT_MATCH_MSG = "Invoice currency doesn't conform with the 2CheckOut plug-in settings. Please check that your storefront base currency matches with the 2CO plug-in currency";
public const string KEY_VALIDATION_FAILED_MSG = "Key validation failed. Original response has been either corrupted or modified.";
public const string CC_PROCESSED_ERROR_MSG = "2CheckOut is unable to process your credit card";
#endregion
public const string PAYMENT_ROUTINE = "https://www.2checkout.com/2co/buyer/purchase";
public const string ErrorPrefix = "2Checkout.";
public const string CREDIT_CARD_PROCESSED = "credit_card_processed";
public const string DEMO_MODE = "demo";
public const string KEY = "key";
public const string OUTSIDE_US_CA = "Outside US and Canada";
public override string[] SecureSettings
{
get
{
return new string[] { ToCheckoutSettings.SECRET_WORD };
}
}
/// <summary>
/// Gets whether 2CO plug-in running in demo mode
/// </summary>
public bool LiveMode
{
get
{
return Convert.ToBoolean(PluginSettings[ToCheckoutSettings.LIVE_MODE]);
}
}
/// <summary>
/// Gets whether 2CO plug-in should disable quantity field
/// </summary>
public bool FixedCart
{
get
{
return Convert.ToBoolean(PluginSettings[ToCheckoutSettings.FIXED_CART]);
}
}
/// <summary>
/// Gets plug-in secret word
/// </summary>
public string SecretWord
{
get { return PluginSettings[ToCheckoutSettings.SECRET_WORD]; }
}
/// <summary>
/// Gets 2CO account sid
/// </summary>
public string AccountSID
{
get { return PluginSettings[ToCheckoutSettings.ACCOUNT_SID]; }
}
/// <summary>
/// Gets 2CO currency
/// </summary>
public string TCO_Currency
{
get { return PluginSettings[ToCheckoutSettings.CURRENCY]; }
}
/// <summary>
/// Gets 2CO continue shopping button url
/// </summary>
public string ContinueShoppingUrl
{
get { return PluginSettings[ToCheckoutSettings.CONTINUE_SHOPPING_URL]; }
}
public TCOProvider()
{
}
#region IPaymentGatewayProvider Members
public CheckoutFormParams GetCheckoutFormParams(FormParameters inputParams, InvoiceItem[] invoiceLines)
{
// check invoice currency against 2CO settings
if (!CI_ValuesEqual(TCO_Currency, inputParams[FormParameters.CURRENCY]))
throw new Exception(CURRENCY_NOT_MATCH_MSG);
// fill checkout params
CheckoutFormParams outputParams = new CheckoutFormParams();
// sets serviced props
outputParams.Action = PAYMENT_ROUTINE;
outputParams.Method = CheckoutFormParams.POST_METHOD;
// copy target_site variable
outputParams["target_site"] = inputParams["target_site"];
// copy invoice amount
outputParams["sid"] = AccountSID;
// copy contract number
outputParams["contract_id"] = inputParams[FormParameters.CONTRACT];
// copy invoice number
outputParams["merchant_order_id"] = inputParams[FormParameters.INVOICE];
// copy invoice currency
outputParams["tco_currency"] = inputParams[FormParameters.CURRENCY];
// copy continue shopping button url
// outputParams["return_url"] = ContinueShoppingUrl + "&ContractId=" + inputParams[FormParameters.CONTRACT];
// copy fixed cart option
if (FixedCart)
outputParams["fixed"] = "Y";
// copy pay method (credit card)
outputParams["pay_method"] = "CC";
// copy live mode flag
if (!LiveMode)
outputParams["demo"] = "Y";
// copy card holder name
outputParams["card_holder_name"] = inputParams[FormParameters.FIRST_NAME] + " " + inputParams[FormParameters.LAST_NAME];
// copy email
outputParams["email"] = inputParams[FormParameters.EMAIL];
// copy street address
outputParams["street_address"] = inputParams[FormParameters.ADDRESS];
// copy country
outputParams["country"] = inputParams[FormParameters.COUNTRY];
// copy city
outputParams["city"] = inputParams[FormParameters.CITY];
// copy state & phone
if (!CI_ValuesEqual(inputParams[FormParameters.COUNTRY], "US") &&
!CI_ValuesEqual(inputParams[FormParameters.COUNTRY], "CA"))
{
// state is outside US & CA
outputParams["state"] = OUTSIDE_US_CA;
// copy outside US phone as is
outputParams["phone"] = inputParams[FormParameters.PHONE];
}
else
{
// copy state
outputParams["state"] = inputParams[FormParameters.STATE];
// convert phone to US format
outputParams["phone"] = ConvertPhone2US(inputParams[FormParameters.PHONE]);
}
// copy zip
outputParams["zip"] = inputParams[FormParameters.ZIP];
// copy invoice amount
outputParams["total"] = inputParams[FormParameters.AMOUNT];
// copy invoice number
outputParams["cart_order_id"] = inputParams[FormParameters.INVOICE];
return outputParams;
}
public TransactionResult SubmitPaymentTransaction(CheckoutDetails details)
{
TransactionResult result = new TransactionResult();
// build raw response for 2CO
string[] keys = details.GetAllKeys();
List<string> bunch = new List<string>();
// copy checkout details
foreach (string key in keys)
{
bunch.Add(String.Concat(key, "=", details[key]));
}
// build raw 2CO response
result.RawResponse = String.Join("|", bunch.ToArray());
// recognize credit card status
switch(details[CREDIT_CARD_PROCESSED])
{
case "Y":
result.TransactionStatus = TransactionStatus.Approved;
break;
case "K":
result.TransactionStatus = TransactionStatus.Pending;
break;
default:
throw new Exception(CC_PROCESSED_ERROR_MSG);
}
// read order number
string order_number = details["order_number"];
// check demo mode: set order number to 1
// according to 2Checkout documentation for demo transactions
bool valid = false;
// validate TCO key
if (LiveMode) // do live validation
valid = ValidateKey(SecretWord, AccountSID, order_number, details[CheckoutKeys.Amount], details[KEY]);
else // do demo validation
valid = ValidateKey(SecretWord, AccountSID, "1", details[CheckoutKeys.Amount], details[KEY]);
// key validation failed
if (!valid)
throw new ArgumentException(KEY_VALIDATION_FAILED_MSG);
// we are succeed copy order number
result.TransactionId = order_number;
//
result.Succeed = true;
// return result
return result;
}
#endregion
private bool ValidateKey(string secretWord, string vendorNumber, string tcoOrderNumber, string tcoTotal, string tcoKey)
{
string rawString = String.Concat(secretWord, vendorNumber, tcoOrderNumber, tcoTotal);
System.Text.Encoding encoding = System.Text.Encoding.ASCII;
byte[] bufferIn = encoding.GetBytes(rawString);
MD5CryptoServiceProvider cryptoProv = new MD5CryptoServiceProvider();
byte[] bufferOut = cryptoProv.ComputeHash(bufferIn);
string hashString = String.Empty;
for (int i = 0; i < bufferOut.Length; i++)
{
hashString += Convert.ToString(bufferOut[i], 16).PadLeft(2, '0');
}
hashString = hashString.PadLeft(32, '0').ToUpper();
return (String.Compare(hashString, tcoKey, true) == 0);
}
private string ConvertPhone2US(string phone)
{
string result = "";
// loop for each digit in phone
foreach (char c in phone.ToCharArray())
{
// exit from loop if phone length is exceeded
if (result.Length == 12)
break;
// check character
if (Char.IsDigit(c))
{
// append delimiter
if (result.Length == 3 || result.Length == 6)
result += "-";
// build phone number
result += c.ToString();
}
}
// return result formatted string
return result;
}
private bool CI_ValuesEqual(string strA, string strB)
{
return String.Equals(strA, strB, StringComparison.InvariantCultureIgnoreCase);
}
}
}
| |
using AutoMapper.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace AutoMapper.Configuration
{
using static AutoMapper.Execution.ExpressionBuilder;
public interface IPropertyMapConfiguration
{
void Configure(TypeMap typeMap);
MemberInfo DestinationMember { get; }
LambdaExpression SourceExpression { get; }
LambdaExpression GetDestinationExpression();
IPropertyMapConfiguration Reverse();
}
public class MemberConfigurationExpression<TSource, TDestination, TMember> : IMemberConfigurationExpression<TSource, TDestination, TMember>, IPropertyMapConfiguration
{
private MemberInfo[] _sourceMembers;
private readonly Type _sourceType;
protected List<Action<PropertyMap>> PropertyMapActions { get; } = new List<Action<PropertyMap>>();
public MemberConfigurationExpression(MemberInfo destinationMember, Type sourceType)
{
DestinationMember = destinationMember;
_sourceType = sourceType;
}
public MemberInfo DestinationMember { get; }
public void MapAtRuntime()
{
PropertyMapActions.Add(pm => pm.Inline = false);
}
public void NullSubstitute(object nullSubstitute)
{
PropertyMapActions.Add(pm => pm.NullSubstitute = nullSubstitute);
}
public void MapFrom<TValueResolver>()
where TValueResolver : IValueResolver<TSource, TDestination, TMember>
{
var config = new ValueResolverConfiguration(typeof(TValueResolver), typeof(IValueResolver<TSource, TDestination, TMember>));
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void MapFrom<TValueResolver, TSourceMember>(Expression<Func<TSource, TSourceMember>> sourceMember)
where TValueResolver : IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>
{
var config = new ValueResolverConfiguration(typeof(TValueResolver), typeof(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>))
{
SourceMember = sourceMember
};
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void MapFrom<TValueResolver, TSourceMember>(string sourceMemberName)
where TValueResolver : IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>
{
var config = new ValueResolverConfiguration(typeof(TValueResolver), typeof(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>))
{
SourceMemberName = sourceMemberName
};
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void MapFrom(IValueResolver<TSource, TDestination, TMember> valueResolver)
{
var config = new ValueResolverConfiguration(valueResolver, typeof(IValueResolver<TSource, TDestination, TMember>));
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void MapFrom<TSourceMember>(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember> valueResolver, Expression<Func<TSource, TSourceMember>> sourceMember)
{
var config = new ValueResolverConfiguration(valueResolver, typeof(IMemberValueResolver<TSource, TDestination, TSourceMember, TMember>))
{
SourceMember = sourceMember
};
PropertyMapActions.Add(pm => pm.ValueResolverConfig = config);
}
public void MapFrom<TResult>(Func<TSource, TDestination, TResult> mappingFunction)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, ResolutionContext, TResult>> expr = (src, dest, destMember, ctxt) => mappingFunction(src, dest);
pm.CustomMapFunction = expr;
});
}
public void MapFrom<TResult>(Func<TSource, TDestination, TMember, TResult> mappingFunction)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, ResolutionContext, TResult>> expr = (src, dest, destMember, ctxt) => mappingFunction(src, dest, destMember);
pm.CustomMapFunction = expr;
});
}
public void MapFrom<TResult>(Func<TSource, TDestination, TMember, ResolutionContext, TResult> mappingFunction)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, ResolutionContext, TResult>> expr = (src, dest, destMember, ctxt) => mappingFunction(src, dest, destMember, ctxt);
pm.CustomMapFunction = expr;
});
}
public void MapFrom<TSourceMember>(Expression<Func<TSource, TSourceMember>> mapExpression)
{
MapFromUntyped(mapExpression);
}
internal void MapFromUntyped(LambdaExpression sourceExpression)
{
SourceExpression = sourceExpression;
PropertyMapActions.Add(pm => pm.MapFrom(sourceExpression));
}
public void MapFrom(string sourceMembersPath)
{
_sourceMembers = ReflectionHelper.GetMemberPath(_sourceType, sourceMembersPath);
PropertyMapActions.Add(pm => pm.MapFrom(sourceMembersPath));
}
public void Condition(Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr =
(src, dest, srcMember, destMember, ctxt) => condition(src, dest, srcMember, destMember, ctxt);
pm.Condition = expr;
});
}
public void Condition(Func<TSource, TDestination, TMember, TMember, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr =
(src, dest, srcMember, destMember, ctxt) => condition(src, dest, srcMember, destMember);
pm.Condition = expr;
});
}
public void Condition(Func<TSource, TDestination, TMember, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr =
(src, dest, srcMember, destMember, ctxt) => condition(src, dest, srcMember);
pm.Condition = expr;
});
}
public void Condition(Func<TSource, TDestination, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr =
(src, dest, srcMember, destMember, ctxt) => condition(src, dest);
pm.Condition = expr;
});
}
public void Condition(Func<TSource, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, TMember, TMember, ResolutionContext, bool>> expr =
(src, dest, srcMember, destMember, ctxt) => condition(src);
pm.Condition = expr;
});
}
public void PreCondition(Func<TSource, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, bool>> expr =
(src, dest, ctxt) => condition(src);
pm.PreCondition = expr;
});
}
public void PreCondition(Func<ResolutionContext, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, bool>> expr =
(src, dest, ctxt) => condition(ctxt);
pm.PreCondition = expr;
});
}
public void PreCondition(Func<TSource, ResolutionContext, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, bool>> expr =
(src, dest, ctxt) => condition(src, ctxt);
pm.PreCondition = expr;
});
}
public void PreCondition(Func<TSource, TDestination, ResolutionContext, bool> condition)
{
PropertyMapActions.Add(pm =>
{
Expression<Func<TSource, TDestination, ResolutionContext, bool>> expr =
(src, dest, ctxt) => condition(src, dest, ctxt);
pm.PreCondition = expr;
});
}
public void AddTransform(Expression<Func<TMember, TMember>> transformer) =>
PropertyMapActions.Add(pm => pm.AddValueTransformation(new ValueTransformerConfiguration(pm.DestinationType, transformer)));
public void ExplicitExpansion()
{
PropertyMapActions.Add(pm => pm.ExplicitExpansion = true);
}
public void Ignore() => Ignore(ignorePaths: true);
public void Ignore(bool ignorePaths) =>
PropertyMapActions.Add(pm =>
{
pm.Ignored = true;
if(ignorePaths && pm.TypeMap.PathMaps.Count > 0)
{
pm.TypeMap.IgnorePaths(DestinationMember);
}
});
public void AllowNull() => SetAllowNull(true);
public void DoNotAllowNull() => SetAllowNull(false);
private void SetAllowNull(bool value) => PropertyMapActions.Add(pm => pm.AllowNull = value);
public void UseDestinationValue() => SetUseDestinationValue(true);
private void SetUseDestinationValue(bool value) => PropertyMapActions.Add(pm => pm.UseDestinationValue = value);
public void SetMappingOrder(int mappingOrder)
{
PropertyMapActions.Add(pm => pm.MappingOrder = mappingOrder);
}
public void ConvertUsing<TValueConverter, TSourceMember>()
where TValueConverter : IValueConverter<TSourceMember, TMember>
=> PropertyMapActions.Add(pm => ConvertUsing<TValueConverter, TSourceMember>(pm));
public void ConvertUsing<TValueConverter, TSourceMember>(Expression<Func<TSource, TSourceMember>> sourceMember)
where TValueConverter : IValueConverter<TSourceMember, TMember>
=> PropertyMapActions.Add(pm => ConvertUsing<TValueConverter, TSourceMember>(pm, sourceMember));
public void ConvertUsing<TValueConverter, TSourceMember>(string sourceMemberName)
where TValueConverter : IValueConverter<TSourceMember, TMember>
=> PropertyMapActions.Add(pm => ConvertUsing<TValueConverter, TSourceMember>(pm, sourceMemberName: sourceMemberName));
public void ConvertUsing<TSourceMember>(IValueConverter<TSourceMember, TMember> valueConverter)
=> PropertyMapActions.Add(pm => ConvertUsing(pm, valueConverter));
public void ConvertUsing<TSourceMember>(IValueConverter<TSourceMember, TMember> valueConverter, Expression<Func<TSource, TSourceMember>> sourceMember)
=> PropertyMapActions.Add(pm => ConvertUsing(pm, valueConverter, sourceMember));
public void ConvertUsing<TSourceMember>(IValueConverter<TSourceMember, TMember> valueConverter, string sourceMemberName)
=> PropertyMapActions.Add(pm => ConvertUsing(pm, valueConverter, sourceMemberName: sourceMemberName));
private static void ConvertUsing<TValueConverter, TSourceMember>(PropertyMap propertyMap,
Expression<Func<TSource, TSourceMember>> sourceMember = null,
string sourceMemberName = null)
{
var config = new ValueResolverConfiguration(typeof(TValueConverter),
typeof(IValueConverter<TSourceMember, TMember>))
{
SourceMember = sourceMember,
SourceMemberName = sourceMemberName
};
propertyMap.ValueConverterConfig = config;
}
private static void ConvertUsing<TSourceMember>(PropertyMap propertyMap, IValueConverter<TSourceMember, TMember> valueConverter,
Expression<Func<TSource, TSourceMember>> sourceMember = null, string sourceMemberName = null)
{
var config = new ValueResolverConfiguration(valueConverter,
typeof(IValueConverter<TSourceMember, TMember>))
{
SourceMember = sourceMember,
SourceMemberName = sourceMemberName
};
propertyMap.ValueConverterConfig = config;
}
public void Configure(TypeMap typeMap)
{
var destMember = DestinationMember;
if(destMember.DeclaringType.ContainsGenericParameters)
{
destMember = typeMap.DestinationSetters.Single(m => m.Name == destMember.Name);
}
var propertyMap = typeMap.FindOrCreatePropertyMapFor(destMember, typeof(TMember) == typeof(object) ? destMember.GetMemberType() : typeof(TMember));
Apply(propertyMap);
}
private void Apply(PropertyMap propertyMap)
{
foreach(var action in PropertyMapActions)
{
action(propertyMap);
}
}
public LambdaExpression SourceExpression { get; private set; }
public LambdaExpression GetDestinationExpression() => DestinationMember.Lambda();
public IPropertyMapConfiguration Reverse()
{
var destinationType = DestinationMember.DeclaringType;
if (_sourceMembers != null)
{
if (_sourceMembers.Length > 1)
{
return null;
}
var reversedMemberConfiguration = new MemberConfigurationExpression<TDestination, TSource, object>(_sourceMembers[0], destinationType);
reversedMemberConfiguration.MapFrom(DestinationMember.Name);
return reversedMemberConfiguration;
}
if (destinationType.IsGenericTypeDefinition) // .ForMember("InnerSource", o => o.MapFrom(s => s))
{
return null;
}
return PathConfigurationExpression<TDestination, TSource, object>.Create(SourceExpression, GetDestinationExpression());
}
public void DoNotUseDestinationValue() => SetUseDestinationValue(false);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.Engine
{
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.DocAsCode.MarkdownLite;
using Microsoft.DocAsCode.Plugins;
using Microsoft.DocAsCode.Common;
using HtmlAgilityPack;
[Serializable]
public sealed class XRefDetails
{
/// <summary>
/// TODO: completely move into template
/// Must be consistent with template input.replace(/\W/g, '_');
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private static Regex HtmlEncodeRegex = new Regex(@"\W", RegexOptions.Compiled);
public string Uid { get; private set; }
public string Anchor { get; private set; }
public string Title { get; private set; }
public string Href { get; private set; }
public string Raw { get; private set; }
public string RawSource { get; private set; }
public string DisplayProperty { get; private set; }
public string AltProperty { get; private set; }
public string InnerHtml { get; private set; }
public string Text { get; private set; }
public string Alt { get; private set; }
public XRefSpec Spec { get; private set; }
public bool ThrowIfNotResolved { get; private set; }
public string SourceFile { get; private set; }
public int SourceStartLineNumber { get; private set; }
public int SourceEndLineNumber { get; private set; }
public string TemplatePath { get; private set; }
private XRefDetails() { }
public static XRefDetails From(HtmlNode node)
{
if (node.Name != "xref") throw new NotSupportedException("Only xref node is supported!");
var xref = new XRefDetails();
var uid = node.GetAttributeValue("uid", null);
var rawHref = node.GetAttributeValue("href", null);
NameValueCollection queryString = null;
if (!string.IsNullOrEmpty(rawHref))
{
if (!string.IsNullOrEmpty(uid))
{
Logger.LogWarning($"Both href and uid attribute are defined for {node.OuterHtml}, use href instead of uid.");
}
string others;
var anchorIndex = rawHref.IndexOf("#");
if (anchorIndex == -1)
{
xref.Anchor = string.Empty;
others = rawHref;
}
else
{
xref.Anchor = rawHref.Substring(anchorIndex);
others = rawHref.Remove(anchorIndex);
}
var queryIndex = others.IndexOf("?");
if (queryIndex == -1)
{
xref.Uid = HttpUtility.UrlDecode(others);
}
else
{
xref.Uid = HttpUtility.UrlDecode(others.Remove(queryIndex));
queryString = HttpUtility.ParseQueryString(others.Substring(queryIndex));
}
}
else
{
xref.Uid = uid;
}
xref.InnerHtml = node.InnerHtml;
xref.DisplayProperty = node.GetAttributeValue("displayProperty", queryString?.Get("displayProperty") ?? XRefSpec.NameKey);
xref.AltProperty = node.GetAttributeValue("altProperty", queryString?.Get("altProperty") ?? "fullName");
xref.Text = node.GetAttributeValue("text", node.GetAttributeValue("name", StringHelper.HtmlEncode(queryString?.Get("text"))));
xref.Alt = node.GetAttributeValue("alt", node.GetAttributeValue("fullname", StringHelper.HtmlEncode(queryString?.Get("alt"))));
xref.Title = node.GetAttributeValue("title", queryString?.Get("title"));
xref.SourceFile = node.GetAttributeValue("sourceFile", null);
xref.SourceStartLineNumber = node.GetAttributeValue("sourceStartLineNumber", 0);
xref.SourceEndLineNumber = node.GetAttributeValue("sourceEndLineNumber", 0);
// Both `data-raw-html` and `data-raw-source` are html encoded. Use `data-raw-html` with higher priority.
// `data-raw-html` will be decoded then displayed, while `data-raw-source` will be displayed directly.
xref.RawSource = node.GetAttributeValue("data-raw-source", null);
var raw = node.GetAttributeValue("data-raw-html", null);
if (!string.IsNullOrEmpty(raw))
{
xref.Raw = StringHelper.HtmlDecode(raw);
}
else
{
xref.Raw = xref.RawSource;
}
xref.ThrowIfNotResolved = node.GetAttributeValue("data-throw-if-not-resolved", false);
var templatePath = node.GetAttributeValue("template", null);
if (templatePath != null)
{
xref.TemplatePath = StringHelper.HtmlDecode(templatePath);
}
return xref;
}
public void ApplyXrefSpec(XRefSpec spec)
{
if (spec == null)
{
return;
}
// TODO: What if href is not html?
if (!string.IsNullOrEmpty(spec.Href))
{
Href = UriUtility.GetNonFragment(spec.Href);
if (string.IsNullOrEmpty(Anchor))
{
Anchor = UriUtility.GetFragment(spec.Href);
}
}
Spec = spec;
}
/// <summary>
/// TODO: multi-lang support
/// </summary>
/// <returns></returns>
public HtmlNode ConvertToHtmlNode(string language, ITemplateRenderer renderer)
{
if (!string.IsNullOrEmpty(TemplatePath) && renderer != null && Spec != null)
{
if (Spec != null)
{
var converted = renderer.Render(Spec);
if (string.IsNullOrWhiteSpace(converted))
{
Logger.LogWarning($"{Spec.Uid} is rendered to empty with template {TemplatePath} for {Raw ?? RawSource}.");
}
var node = new HtmlDocument();
node.LoadHtml(converted);
return node.DocumentNode;
}
else
{
Logger.LogWarning($"Invalid xref definition \"{Raw}\", XrefSpec is not defined.");
}
}
// If href exists, return anchor else return text
if (!string.IsNullOrEmpty(Href))
{
if (!string.IsNullOrEmpty(InnerHtml))
{
return GetAnchorNode(Href, Anchor, Title, InnerHtml, RawSource, SourceFile, SourceStartLineNumber, SourceEndLineNumber);
}
if (!string.IsNullOrEmpty(Text))
{
return GetAnchorNode(Href, Anchor, Title, Text, RawSource, SourceFile, SourceStartLineNumber, SourceEndLineNumber);
}
if (Spec != null)
{
var value = StringHelper.HtmlEncode(GetLanguageSpecificAttribute(Spec, language, DisplayProperty, "name"));
if (!string.IsNullOrEmpty(value))
{
return GetAnchorNode(Href, Anchor, Title, value, RawSource, SourceFile, SourceStartLineNumber, SourceEndLineNumber);
}
}
return GetAnchorNode(Href, Anchor, Title, Uid, RawSource, SourceFile, SourceStartLineNumber, SourceEndLineNumber);
}
else
{
if (!string.IsNullOrEmpty(Raw))
{
return HtmlNode.CreateNode(Raw);
}
if (!string.IsNullOrEmpty(InnerHtml))
{
return GetDefaultPlainTextNode(InnerHtml);
}
if (!string.IsNullOrEmpty(Alt))
{
return GetDefaultPlainTextNode(Alt);
}
if (Spec != null)
{
var value = StringHelper.HtmlEncode(GetLanguageSpecificAttribute(Spec, language, AltProperty, "name"));
if (!string.IsNullOrEmpty(value))
{
return GetDefaultPlainTextNode(value);
}
}
return GetDefaultPlainTextNode(Uid);
}
}
private static HtmlNode GetAnchorNode(string href, string anchor, string title, string value, string rawSource, string sourceFile, int sourceStartLineNumber, int sourceEndLineNumber)
{
var anchorNode = $"<a class=\"xref\" href=\"{href}\"";
if (!string.IsNullOrEmpty(anchor))
{
anchorNode += $" anchor=\"{anchor}\"";
}
if (!string.IsNullOrEmpty(title))
{
anchorNode += $" title=\"{title}\"";
}
if (!string.IsNullOrEmpty(rawSource))
{
anchorNode += $" data-raw-source=\"{rawSource}\"";
}
if (!string.IsNullOrEmpty(sourceFile))
{
anchorNode += $" sourceFile=\"{sourceFile}\"";
}
if (sourceStartLineNumber != 0)
{
anchorNode += $" sourceStartLineNumber={sourceStartLineNumber}";
}
if (sourceEndLineNumber != 0)
{
anchorNode += $" sourceEndLineNumber={sourceEndLineNumber}";
}
anchorNode += $">{value}</a>";
return HtmlNode.CreateNode(anchorNode);
}
private static HtmlNode GetDefaultPlainTextNode(string value)
{
var spanNode = $"<span class=\"xref\">{value}</span>";
return HtmlNode.CreateNode(spanNode);
}
private static string GetLanguageSpecificAttribute(XRefSpec spec, string language, params string[] keyInFallbackOrder)
{
if (keyInFallbackOrder == null || keyInFallbackOrder.Length == 0)
{
throw new ArgumentException("key must be provided!", nameof(keyInFallbackOrder));
}
string suffix = string.Empty;
if (!string.IsNullOrEmpty(language))
{
suffix = "." + language;
}
foreach (var key in keyInFallbackOrder)
{
var keyWithSuffix = key + suffix;
if (spec.TryGetValue(keyWithSuffix, out string value))
{
return value;
}
if (spec.TryGetValue(key, out value))
{
return value;
}
}
return null;
}
public static HtmlNode ConvertXrefLinkNodeToXrefNode(HtmlNode node)
{
var href = node.GetAttributeValue("href", null);
if (node.Name != "a" || string.IsNullOrEmpty(href) || !href.StartsWith("xref:"))
{
throw new NotSupportedException("Only anchor node with href started with \"xref:\" is supported!");
}
href = href.Substring("xref:".Length);
var raw = StringHelper.HtmlEncode(node.OuterHtml);
var xrefNode = $"<xref href=\"{href}\" data-throw-if-not-resolved=\"True\" data-raw-html=\"{raw}\"";
foreach (var attr in node.Attributes ?? Enumerable.Empty<HtmlAttribute>())
{
if (attr.Name == "href" || attr.Name == "data-throw-if-not-resolved" || attr.Name == "data-raw-html")
{
continue;
}
xrefNode += $" {attr.Name}=\"{attr.Value}\"";
}
xrefNode += $">{node.InnerHtml}</xref>";
return HtmlNode.CreateNode(xrefNode);
}
}
}
| |
//! \file ArcFPK.cs
//! \date Mon May 25 10:01:24 2015
//! \brief FPK resource archives implementation.
//
// Copyright (C) 2015-2016 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using GameRes.Utility;
namespace GameRes.Formats.CandySoft
{
[Export(typeof(ArchiveFormat))]
public class FpkOpener : ArchiveFormat
{
public override string Tag { get { return "FPK"; } }
public override string Description { get { return "Interheart/Candy Soft resource archive"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public FpkOpener ()
{
Signatures = new uint[] { 0, 1 };
ContainedFormats = new[] { "BMP", "KG", "OGG", "SCR", "TXT" };
}
public override ArcFile TryOpen (ArcView file)
{
if (file.MaxOffset < 0x10)
return null;
int count = file.View.ReadInt32 (0);
List<Entry> dir = null;
if (count < 0)
{
count &= 0x7FFFFFFF;
if (!IsSaneCount (count))
return null;
dir = ReadEncryptedIndex (file, count);
}
else
{
if (!IsSaneCount (count))
return null;
try
{
dir = ReadIndex (file, count, 0x10);
}
catch { /* read failed, try another filename length */ }
if (null == dir)
dir = ReadIndex (file, count, 0x18);
}
if (null == dir)
return null;
return new ArcFile (file, this, dir);
}
private List<Entry> ReadIndex (ArcView file, int count, int name_size)
{
long index_offset = 4;
uint index_size = (uint)((8 + name_size) * count);
if (index_size > file.View.Reserve (index_offset, index_size))
return null;
uint data_offset = 4 + index_size;
var dir = new List<Entry> (count);
for (int i = 0; i < count; ++i)
{
string name = file.View.ReadString (index_offset+8, (uint)name_size);
if (string.IsNullOrWhiteSpace (name))
return null;
var entry = Create<Entry> (name);
entry.Offset = file.View.ReadUInt32 (index_offset);
entry.Size = file.View.ReadUInt32 (index_offset+4);
if (entry.Offset < data_offset || !entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
index_offset += 8 + name_size;
}
return dir;
}
private List<Entry> ReadEncryptedIndex (ArcView file, int count)
{
uint index_offset = file.View.ReadUInt32 (file.MaxOffset-4);
if (index_offset < 4 || index_offset >= file.MaxOffset-8)
return null;
var key = file.View.ReadBytes (file.MaxOffset-8, 4);
int name_size = 0x18;
int index_size = count * (12 + name_size);
var index = file.View.ReadBytes (index_offset, (uint)index_size);
if (index.Length != index_size)
return null;
for (int i = 0; i < index.Length; ++i)
index[i] ^= key[i & 3];
int index_pos = 0;
var dir = new List<Entry> (count);
for (int i = 0; i < count; ++i)
{
string name = Binary.GetCString (index, index_pos+8, name_size);
if (string.IsNullOrWhiteSpace (name))
return null;
var entry = Create<Entry> (name);
entry.Offset = LittleEndian.ToUInt32 (index, index_pos);
entry.Size = LittleEndian.ToUInt32 (index, index_pos+4);
if (!entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
index_pos += 12 + name_size;
}
return dir;
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
var input = arc.File.CreateStream (entry.Offset, entry.Size);
if (entry.Size <= 8)
return input;
var sign = input.Signature;
if (0x32434c5a != sign) // 'ZLC2'
return input;
using (input)
using (var reader = new Zlc2Reader (input, (int)entry.Size))
{
reader.Unpack();
return new BinMemoryStream (reader.Data, entry.Name);
}
}
}
internal class Zlc2Reader : IDisposable
{
IBinaryStream m_input;
byte[] m_output;
int m_size;
public byte[] Data { get { return m_output; } }
public Zlc2Reader (IBinaryStream input, int input_length)
{
input.Position = 4;
m_input = input;
uint output_length = m_input.ReadUInt32();
m_output = new byte[output_length];
m_size = input_length - 8;
}
public void Unpack ()
{
int remaining = m_size;
int dst = 0;
while (remaining > 0 && dst < m_output.Length)
{
int ctl = m_input.ReadUInt8();
remaining--;
for (int mask = 0x80; mask != 0 && remaining > 0 && dst < m_output.Length; mask >>= 1)
{
if (0 != (ctl & mask))
{
if (remaining < 2)
return;
int offset = m_input.ReadUInt8();
int count = m_input.ReadUInt8();
remaining -= 2;
offset |= (count & 0xF0) << 4;
count = (count & 0x0F) + 3;
if (0 == offset)
offset = 4096;
if (dst + count > m_output.Length)
count = m_output.Length - dst;
Binary.CopyOverlapped (m_output, dst-offset, dst, count);
dst += count;
}
else
{
m_output[dst++] = m_input.ReadUInt8();
remaining--;
}
}
}
}
#region IDisposable Members
public void Dispose ()
{
}
#endregion
}
[Export(typeof(ResourceAlias))]
[ExportMetadata("Extension", "SPT")]
[ExportMetadata("Target", "SCR")]
public class SptFormat : ResourceAlias { }
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System;
using System.Text;
using System.IO;
using NPOI.Util;
using NPOI.SS.Formula.PTG;
using System.Globalization;
/**
* A sub-record within the OBJ record which stores a reference to an object
* stored in a Separate entry within the OLE2 compound file.
*
* @author Daniel Noll
*/
public class EmbeddedObjectRefSubRecord
: SubRecord, ICloneable
{
private static POILogger logger = POILogFactory.GetLogger(typeof(EmbeddedObjectRefSubRecord));
public const short sid = 0x9;
private static byte[] EMPTY_BYTE_ARRAY = { };
private int field_1_unknown_int; // Unknown stuff at the front. TODO: Confirm that it's a short[]
/** either an area or a cell ref */
private Ptg field_2_refPtg;
private byte[] field_2_unknownFormulaData;
// TODO: Consider making a utility class for these. I've discovered the same field ordering
// in FormatRecord and StringRecord, it may be elsewhere too.
public bool field_3_unicode_flag; // Flags whether the string is Unicode.
private String field_4_ole_classname; // Classname of the embedded OLE document (e.g. Word.Document.8)
/** Formulas often have a single non-zero trailing byte.
* This is in a similar position to he pre-streamId padding
* It is unknown if the value is important (it seems to mirror a value a few bytes earlier)
* */
private Byte? field_4_unknownByte;
private int? field_5_stream_id; // ID of the OLE stream containing the actual data.
private byte[] field_6_unknown;
public EmbeddedObjectRefSubRecord()
{
field_2_unknownFormulaData = new byte[] { 0x02, 0x6C, 0x6A, 0x16, 0x01, }; // just some sample data. These values vary a lot
field_6_unknown = EMPTY_BYTE_ARRAY;
field_4_ole_classname = null;
field_4_unknownByte = null;
}
/**
* Constructs an EmbeddedObjectRef record and Sets its fields appropriately.
*
* @param in the record input stream.
*/
public EmbeddedObjectRefSubRecord(ILittleEndianInput in1, int size)
{
// Much guess-work going on here due to lack of any documentation.
// See similar source code in OOO:
// http://lxr.go-oo.org/source/sc/sc/source/filter/excel/xiescher.cxx
// 1223 void XclImpOleObj::ReadPictFmla( XclImpStream& rStrm, sal_uInt16 nRecSize )
int streamIdOffset = in1.ReadShort(); // OOO calls this 'nFmlaLen'
int remaining = size - LittleEndianConsts.SHORT_SIZE;
int dataLenAfterFormula = remaining - streamIdOffset;
int formulaSize = in1.ReadUShort();
remaining -= LittleEndianConsts.SHORT_SIZE;
field_1_unknown_int = in1.ReadInt();
remaining -= LittleEndianConsts.INT_SIZE;
byte[] formulaRawBytes = ReadRawData(in1, formulaSize);
remaining -= formulaSize;
field_2_refPtg = ReadRefPtg(formulaRawBytes);
if (field_2_refPtg == null)
{
// common case
// field_2_n16 seems to be 5 here
// The formula almost looks like tTbl but the row/column values seem like garbage.
field_2_unknownFormulaData = formulaRawBytes;
}
else
{
field_2_unknownFormulaData = null;
}
int stringByteCount;
if (remaining >= dataLenAfterFormula + 3)
{
int tag = in1.ReadByte();
stringByteCount = LittleEndianConsts.BYTE_SIZE;
if (tag != 0x03)
{
throw new RecordFormatException("Expected byte 0x03 here");
}
int nChars = in1.ReadUShort();
stringByteCount += LittleEndianConsts.SHORT_SIZE;
if (nChars > 0)
{
// OOO: the 4th way Xcl stores a unicode string: not even a Grbit byte present if Length 0
field_3_unicode_flag = (in1.ReadByte() & 0x01) != 0;
stringByteCount += LittleEndianConsts.BYTE_SIZE;
if (field_3_unicode_flag)
{
field_4_ole_classname = StringUtil.ReadUnicodeLE(in1,nChars);
stringByteCount += nChars * 2;
}
else
{
field_4_ole_classname = StringUtil.ReadCompressedUnicode(in1,nChars);
stringByteCount += nChars;
}
}
else
{
field_4_ole_classname = "";
}
}
else
{
field_4_ole_classname = null;
stringByteCount = 0;
}
remaining -= stringByteCount;
// Pad to next 2-byte boundary
if (((stringByteCount + formulaSize) % 2) != 0)
{
int b = in1.ReadByte();
remaining -= LittleEndianConsts.BYTE_SIZE;
if (field_2_refPtg != null && field_4_ole_classname == null)
{
field_4_unknownByte = (byte)b;
}
}
int nUnexpectedPadding = remaining - dataLenAfterFormula;
if (nUnexpectedPadding > 0)
{
logger.Log(POILogger.ERROR, "Discarding " + nUnexpectedPadding + " unexpected padding bytes ");
ReadRawData(in1, nUnexpectedPadding);
remaining -= nUnexpectedPadding;
}
// Fetch the stream ID
if (dataLenAfterFormula >= 4)
{
field_5_stream_id = in1.ReadInt();
remaining -= LittleEndianConsts.INT_SIZE;
}
else
{
field_5_stream_id = null;
}
field_6_unknown = ReadRawData(in1, remaining);
}
public override short Sid
{
get { return sid; }
}
private static Ptg ReadRefPtg(byte[] formulaRawBytes)
{
using (MemoryStream ms = new MemoryStream(formulaRawBytes))
{
ILittleEndianInput in1 = new LittleEndianInputStream(ms);
byte ptgSid = (byte)in1.ReadByte();
switch (ptgSid)
{
case AreaPtg.sid: return new AreaPtg(in1);
case Area3DPtg.sid: return new Area3DPtg(in1);
case RefPtg.sid: return new RefPtg(in1);
case Ref3DPtg.sid: return new Ref3DPtg(in1);
}
return null;
}
}
private static byte[] ReadRawData(ILittleEndianInput in1, int size)
{
if (size < 0)
{
throw new ArgumentException("Negative size (" + size + ")");
}
if (size == 0)
{
return EMPTY_BYTE_ARRAY;
}
byte[] result = new byte[size];
in1.ReadFully(result);
return result;
}
private int GetStreamIDOffset(int formulaSize)
{
int result = 2 + 4; // formulaSize + f2unknown_int
result += formulaSize;
int stringLen;
if (field_4_ole_classname == null)
{
// don't write 0x03, stringLen, flag, text
stringLen = 0;
}
else
{
result += 1 + 2; // 0x03, stringLen, flag
stringLen = field_4_ole_classname.Length;
if (stringLen > 0)
{
result += 1; // flag
if (field_3_unicode_flag)
{
result += stringLen * 2;
}
else
{
result += stringLen;
}
}
}
// pad to next 2 byte boundary
if ((result % 2) != 0)
{
result++;
}
return result;
}
private int GetDataSize(int idOffset)
{
int result = 2 + idOffset; // 2 for idOffset short field itself
if (field_5_stream_id != null)
{
result += 4;
}
return result + field_6_unknown.Length;
}
public override int DataSize
{
get
{
int formulaSize = field_2_refPtg == null ? field_2_unknownFormulaData.Length : field_2_refPtg.Size;
int idOffset = GetStreamIDOffset(formulaSize);
return GetDataSize(idOffset);
}
}
public override void Serialize(ILittleEndianOutput out1)
{
int formulaSize = field_2_refPtg == null ? field_2_unknownFormulaData.Length : field_2_refPtg.Size;
int idOffset = GetStreamIDOffset(formulaSize);
int dataSize = GetDataSize(idOffset);
out1.WriteShort(sid);
out1.WriteShort(dataSize);
out1.WriteShort(idOffset);
out1.WriteShort(formulaSize);
out1.WriteInt(field_1_unknown_int);
int pos = 12;
if (field_2_refPtg == null)
{
out1.Write(field_2_unknownFormulaData);
}
else
{
field_2_refPtg.Write(out1);
}
pos += formulaSize;
int stringLen;
if (field_4_ole_classname == null)
{
// don't write 0x03, stringLen, flag, text
stringLen = 0;
}
else
{
out1.WriteByte(0x03);
pos += 1;
stringLen = field_4_ole_classname.Length;
out1.WriteShort(stringLen);
pos += 2;
if (stringLen > 0)
{
out1.WriteByte(field_3_unicode_flag ? 0x01 : 0x00);
pos += 1;
if (field_3_unicode_flag)
{
StringUtil.PutUnicodeLE(field_4_ole_classname, out1);
pos += stringLen * 2;
}
else
{
StringUtil.PutCompressedUnicode(field_4_ole_classname, out1);
pos += stringLen;
}
}
}
// pad to next 2-byte boundary (requires 0 or 1 bytes)
switch (idOffset - (pos - 6 ))
{ // 6 for 3 shorts: sid, dataSize, idOffset
case 1:
out1.WriteByte(field_4_unknownByte == null ? 0x00 : (int)Convert.ToByte(field_4_unknownByte, CultureInfo.InvariantCulture));
pos++;
break;
case 0:
break;
default:
throw new InvalidOperationException("Bad padding calculation (" + idOffset + ", " + pos + ")");
}
if (field_5_stream_id != null)
{
out1.WriteInt(Convert.ToInt32(field_5_stream_id, CultureInfo.InvariantCulture));
pos += 4;
}
out1.Write(field_6_unknown);
}
/**
* Gets the stream ID containing the actual data. The data itself
* can be found under a top-level directory entry in the OLE2 filesystem
* under the name "MBD<var>xxxxxxxx</var>" where <var>xxxxxxxx</var> is
* this ID converted into hex (in big endian order, funnily enough.)
*
* @return the data stream ID. Possibly <c>null</c>
*/
public int? StreamId
{
get
{
return field_5_stream_id;
}
}
public String OLEClassName
{
get
{
return field_4_ole_classname;
}
set { field_4_ole_classname = value; }
}
public byte[] ObjectData
{
get
{
return field_6_unknown;
}
set
{
field_6_unknown = value;
}
}
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("[ftPictFmla]\n");
sb.Append(" .f2unknown = ").Append(HexDump.IntToHex(field_1_unknown_int)).Append("\n");
if (field_2_refPtg == null)
{
sb.Append(" .f3unknown = ").Append(HexDump.ToHex(field_2_unknownFormulaData)).Append("\n");
}
else
{
sb.Append(" .formula = ").Append(field_2_refPtg.ToString()).Append("\n");
}
if (field_4_ole_classname != null)
{
sb.Append(" .unicodeFlag = ").Append(field_3_unicode_flag).Append("\n");
sb.Append(" .oleClassname = ").Append(field_4_ole_classname).Append("\n");
}
if (field_4_unknownByte != null)
{
sb.Append(" .f4unknown = ").Append(HexDump.ByteToHex(Convert.ToByte(field_4_unknownByte, CultureInfo.InvariantCulture))).Append("\n");
}
if (field_5_stream_id != null)
{
sb.Append(" .streamId = ").Append(HexDump.IntToHex(Convert.ToInt32(field_5_stream_id, CultureInfo.InvariantCulture))).Append("\n");
}
if (field_6_unknown.Length > 0)
{
sb.Append(" .f7unknown = ").Append(HexDump.ToHex(field_6_unknown)).Append("\n");
}
sb.Append("[/ftPictFmla]");
return sb.ToString();
}
public override Object Clone()
{
return this; // TODO proper clone
}
public void SetUnknownFormulaData(byte[] formularData)
{
field_2_unknownFormulaData = formularData;
}
public void SetStorageId(int storageId)
{
field_5_stream_id = storageId;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Security;
public sealed class LocalServiceSecuritySettings
{
bool detectReplays;
int replayCacheSize;
TimeSpan replayWindow;
TimeSpan maxClockSkew;
TimeSpan issuedCookieLifetime;
int maxStatefulNegotiations;
TimeSpan negotiationTimeout;
int maxCachedCookies;
int maxPendingSessions;
TimeSpan inactivityTimeout;
TimeSpan sessionKeyRenewalInterval;
TimeSpan sessionKeyRolloverInterval;
bool reconnectTransportOnFailure;
TimeSpan timestampValidityDuration;
NonceCache nonceCache = null;
LocalServiceSecuritySettings(LocalServiceSecuritySettings other)
{
this.detectReplays = other.detectReplays;
this.replayCacheSize = other.replayCacheSize;
this.replayWindow = other.replayWindow;
this.maxClockSkew = other.maxClockSkew;
this.issuedCookieLifetime = other.issuedCookieLifetime;
this.maxStatefulNegotiations = other.maxStatefulNegotiations;
this.negotiationTimeout = other.negotiationTimeout;
this.maxPendingSessions = other.maxPendingSessions;
this.inactivityTimeout = other.inactivityTimeout;
this.sessionKeyRenewalInterval = other.sessionKeyRenewalInterval;
this.sessionKeyRolloverInterval = other.sessionKeyRolloverInterval;
this.reconnectTransportOnFailure = other.reconnectTransportOnFailure;
this.timestampValidityDuration = other.timestampValidityDuration;
this.maxCachedCookies = other.maxCachedCookies;
this.nonceCache = other.nonceCache;
}
public bool DetectReplays
{
get
{
return this.detectReplays;
}
set
{
this.detectReplays = value;
}
}
public int ReplayCacheSize
{
get
{
return this.replayCacheSize;
}
set
{
if (value < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.ValueMustBeNonNegative)));
}
this.replayCacheSize = value;
}
}
public TimeSpan ReplayWindow
{
get
{
return this.replayWindow;
}
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.replayWindow = value;
}
}
public TimeSpan MaxClockSkew
{
get
{
return this.maxClockSkew;
}
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.maxClockSkew = value;
}
}
public NonceCache NonceCache
{
get
{
return this.nonceCache;
}
set
{
this.nonceCache = value;
}
}
public TimeSpan IssuedCookieLifetime
{
get
{
return this.issuedCookieLifetime;
}
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.issuedCookieLifetime = value;
}
}
public int MaxStatefulNegotiations
{
get
{
return this.maxStatefulNegotiations;
}
set
{
if (value < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.ValueMustBeNonNegative)));
}
this.maxStatefulNegotiations = value;
}
}
public TimeSpan NegotiationTimeout
{
get
{
return this.negotiationTimeout;
}
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.negotiationTimeout = value;
}
}
public int MaxPendingSessions
{
get
{
return this.maxPendingSessions;
}
set
{
if (value < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.ValueMustBeNonNegative)));
}
this.maxPendingSessions = value;
}
}
public TimeSpan InactivityTimeout
{
get
{
return this.inactivityTimeout;
}
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.inactivityTimeout = value;
}
}
public TimeSpan SessionKeyRenewalInterval
{
get
{
return this.sessionKeyRenewalInterval;
}
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.sessionKeyRenewalInterval = value;
}
}
public TimeSpan SessionKeyRolloverInterval
{
get
{
return this.sessionKeyRolloverInterval;
}
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.sessionKeyRolloverInterval = value;
}
}
public bool ReconnectTransportOnFailure
{
get
{
return this.reconnectTransportOnFailure;
}
set
{
this.reconnectTransportOnFailure = value;
}
}
public TimeSpan TimestampValidityDuration
{
get
{
return this.timestampValidityDuration;
}
set
{
if (value < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRange0)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.timestampValidityDuration = value;
}
}
public int MaxCachedCookies
{
get
{
return this.maxCachedCookies;
}
set
{
if (value < 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.ValueMustBeNonNegative)));
}
this.maxCachedCookies = value;
}
}
public LocalServiceSecuritySettings()
{
this.DetectReplays = SecurityProtocolFactory.defaultDetectReplays;
this.ReplayCacheSize = SecurityProtocolFactory.defaultMaxCachedNonces;
this.ReplayWindow = SecurityProtocolFactory.defaultReplayWindow;
this.MaxClockSkew = SecurityProtocolFactory.defaultMaxClockSkew;
this.IssuedCookieLifetime = NegotiationTokenAuthenticator<NegotiationTokenAuthenticatorState>.defaultServerIssuedTokenLifetime;
this.MaxStatefulNegotiations = NegotiationTokenAuthenticator<NegotiationTokenAuthenticatorState>.defaultServerMaxActiveNegotiations;
this.NegotiationTimeout = NegotiationTokenAuthenticator<NegotiationTokenAuthenticatorState>.defaultServerMaxNegotiationLifetime;
this.maxPendingSessions = SecuritySessionServerSettings.defaultMaximumPendingSessions;
this.inactivityTimeout = SecuritySessionServerSettings.defaultInactivityTimeout;
this.sessionKeyRenewalInterval = SecuritySessionServerSettings.defaultKeyRenewalInterval;
this.sessionKeyRolloverInterval = SecuritySessionServerSettings.defaultKeyRolloverInterval;
this.reconnectTransportOnFailure = SecuritySessionServerSettings.defaultTolerateTransportFailures;
this.TimestampValidityDuration = SecurityProtocolFactory.defaultTimestampValidityDuration;
this.maxCachedCookies = NegotiationTokenAuthenticator<NegotiationTokenAuthenticatorState>.defaultServerMaxCachedTokens;
this.nonceCache = null;
}
public LocalServiceSecuritySettings Clone()
{
return new LocalServiceSecuritySettings(this);
}
}
}
| |
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System.Collections.Generic;
using System.Windows.Forms;
using XenAdmin.Actions;
using XenAdmin.Controls;
using XenAdmin.Dialogs;
using XenAPI;
using System.Linq;
using System.IO;
using XenAdmin.Alerts;
namespace XenAdmin.Wizards.PatchingWizard
{
/// <summary>
/// Remember that equals for patches dont work across connections because
/// we are not allow to override equals. YOU SHOULD NOT USE ANY OPERATION THAT IMPLIES CALL EQUALS OF Pool_path or Host_patch
/// You should do it manually or use delegates.
/// </summary>
public partial class PatchingWizard : XenWizardBase
{
private readonly PatchingWizard_PatchingPage PatchingWizard_PatchingPage;
private readonly PatchingWizard_SelectPatchPage PatchingWizard_SelectPatchPage;
private readonly PatchingWizard_ModePage PatchingWizard_ModePage;
private readonly PatchingWizard_SelectServers PatchingWizard_SelectServers;
private readonly PatchingWizard_UploadPage PatchingWizard_UploadPage;
private readonly PatchingWizard_PrecheckPage PatchingWizard_PrecheckPage;
private readonly PatchingWizard_FirstPage PatchingWizard_FirstPage;
public PatchingWizard()
{
InitializeComponent();
PatchingWizard_PatchingPage = new PatchingWizard_PatchingPage();
PatchingWizard_SelectPatchPage = new PatchingWizard_SelectPatchPage();
PatchingWizard_ModePage = new PatchingWizard_ModePage();
PatchingWizard_SelectServers = new PatchingWizard_SelectServers();
PatchingWizard_UploadPage = new PatchingWizard_UploadPage();
PatchingWizard_PrecheckPage = new PatchingWizard_PrecheckPage();
PatchingWizard_FirstPage = new PatchingWizard_FirstPage();
AddPage(PatchingWizard_FirstPage);
AddPage(PatchingWizard_SelectPatchPage);
AddPage(PatchingWizard_SelectServers);
AddPage(PatchingWizard_UploadPage);
// This gets enabled/disabled in the select patch step depending on if it is an OEM patch or not
AddPage(PatchingWizard_PrecheckPage);
AddPage(PatchingWizard_ModePage);
AddPage(PatchingWizard_PatchingPage);
}
public void AddAlert(XenServerPatchAlert alert)
{
PatchingWizard_SelectPatchPage.SelectDownloadAlert(alert);
PatchingWizard_SelectPatchPage.SelectedUpdateAlert = alert;
PatchingWizard_SelectServers.SelectedUpdateAlert = alert;
PatchingWizard_UploadPage.SelectedUpdateAlert = alert;
}
public void AddFile(string path)
{
PatchingWizard_SelectPatchPage.AddFile(path);
}
public void SelectServers(List<Host> selectedServers)
{
PatchingWizard_SelectServers.SelectServers(selectedServers);
PatchingWizard_SelectServers.DisableUnselectedServers();
}
protected override void UpdateWizardContent(XenTabPage senderPage)
{
var prevPageType = senderPage.GetType();
if (prevPageType == typeof(PatchingWizard_SelectPatchPage))
{
var updateType = PatchingWizard_SelectPatchPage.SelectedUpdateType;
var newPatch = PatchingWizard_SelectPatchPage.SelectedNewPatch;
var existPatch = PatchingWizard_SelectPatchPage.SelectedExistingPatch;
var alertPatch = PatchingWizard_SelectPatchPage.SelectedUpdateAlert;
var fileFromDiskAlertPatch = PatchingWizard_SelectPatchPage.FileFromDiskAlert;
DisablePage(PatchingWizard_PrecheckPage, updateType == UpdateType.NewOem);
DisablePage(PatchingWizard_UploadPage, updateType == UpdateType.NewOem);
PatchingWizard_SelectServers.SelectedUpdateType = updateType;
PatchingWizard_SelectServers.Patch = existPatch;
PatchingWizard_SelectServers.SelectedUpdateAlert = alertPatch;
PatchingWizard_SelectServers.FileFromDiskAlert = fileFromDiskAlertPatch;
PatchingWizard_UploadPage.SelectedUpdateType = updateType;
PatchingWizard_UploadPage.SelectedExistingPatch = existPatch;
PatchingWizard_UploadPage.SelectedNewPatchPath = newPatch;
PatchingWizard_UploadPage.SelectedUpdateAlert = alertPatch;
PatchingWizard_ModePage.Patch = existPatch;
PatchingWizard_ModePage.SelectedUpdateAlert = alertPatch;
PatchingWizard_PrecheckPage.Patch = existPatch;
PatchingWizard_PatchingPage.Patch = existPatch;
PatchingWizard_PrecheckPage.SelectedUpdateType = updateType;
PatchingWizard_ModePage.SelectedUpdateType = updateType;
PatchingWizard_PatchingPage.SelectedUpdateType = updateType;
PatchingWizard_PatchingPage.SelectedNewPatch = newPatch;
}
else if (prevPageType == typeof(PatchingWizard_SelectServers))
{
var selectedServers = PatchingWizard_SelectServers.SelectedServers;
PatchingWizard_PrecheckPage.SelectedServers = selectedServers;
PatchingWizard_ModePage.SelectedServers = selectedServers;
PatchingWizard_PatchingPage.SelectedMasters = PatchingWizard_SelectServers.SelectedMasters;
PatchingWizard_PatchingPage.SelectedServers = selectedServers;
PatchingWizard_PatchingPage.SelectedPools = PatchingWizard_SelectServers.SelectedPools;
PatchingWizard_UploadPage.SelectedMasters = PatchingWizard_SelectServers.SelectedMasters;
PatchingWizard_UploadPage.SelectedServers = selectedServers;
}
else if (prevPageType == typeof(PatchingWizard_UploadPage))
{
if (PatchingWizard_SelectPatchPage.SelectedUpdateType == UpdateType.NewRetail)
{
PatchingWizard_SelectPatchPage.SelectedUpdateType = UpdateType.Existing;
PatchingWizard_SelectPatchPage.SelectedExistingPatch = PatchingWizard_UploadPage.Patch;
PatchingWizard_SelectServers.SelectedUpdateType = UpdateType.Existing;
PatchingWizard_SelectServers.Patch = PatchingWizard_UploadPage.Patch;
PatchingWizard_PrecheckPage.Patch = PatchingWizard_UploadPage.Patch;
PatchingWizard_ModePage.Patch = PatchingWizard_UploadPage.Patch;
PatchingWizard_PatchingPage.Patch = PatchingWizard_UploadPage.Patch;
}
PatchingWizard_PatchingPage.SuppPackVdis = PatchingWizard_UploadPage.SuppPackVdis;
}
else if (prevPageType == typeof(PatchingWizard_ModePage))
{
PatchingWizard_PatchingPage.ManualTextInstructions = PatchingWizard_ModePage.ManualTextInstructions;
PatchingWizard_PatchingPage.IsAutomaticMode = PatchingWizard_ModePage.IsAutomaticMode;
PatchingWizard_PatchingPage.RemoveUpdateFile = PatchingWizard_ModePage.RemoveUpdateFile;
}
else if (prevPageType == typeof(PatchingWizard_PrecheckPage))
{
PatchingWizard_PatchingPage.ProblemsResolvedPreCheck = PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck;
}
}
private delegate List<AsyncAction> GetActionsDelegate();
private List<AsyncAction> BuildSubActions(params GetActionsDelegate[] getActionsDelegate)
{
List<AsyncAction> result = new List<AsyncAction>();
foreach (GetActionsDelegate getActionDelegate in getActionsDelegate)
{
var list = getActionDelegate();
if (list != null && list.Count > 0)
result.AddRange(list);
}
return result;
}
private List<AsyncAction> GetUnwindChangesActions()
{
if (PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck == null)
return null;
var actionList = (from problem in PatchingWizard_PrecheckPage.ProblemsResolvedPreCheck
where problem.SolutionActionCompleted
select problem.UnwindChanges());
return actionList.Where(action => action != null &&
action.Connection != null &&
action.Connection.IsConnected).ToList();
}
private List<AsyncAction> GetRemovePatchActions(List<Pool_patch> patchesToRemove)
{
if (patchesToRemove == null)
return null;
List<AsyncAction> list = new List<AsyncAction>();
foreach (Pool_patch patch in patchesToRemove)
{
if (patch.Connection != null && patch.Connection.IsConnected)
{
if (patch.HostsAppliedTo().Count == 0)
{
list.Add(new RemovePatchAction(patch));
}
else
{
list.Add(new DelegatedAsyncAction(patch.Connection, Messages.REMOVE_PATCH, "", "", session => Pool_patch.async_pool_clean(session, patch.opaque_ref)));
}
}
}
return list;
}
private List<AsyncAction> GetRemovePatchActions()
{
return GetRemovePatchActions(PatchingWizard_UploadPage.NewUploadedPatches.Keys.ToList());
}
private List<AsyncAction> GetRemoveVdiActions(List<VDI> vdisToRemove)
{
if (vdisToRemove == null)
return null;
var list = (from vdi in vdisToRemove
where vdi.Connection != null && vdi.Connection.IsConnected
select new DestroyDiskAction(vdi));
return list.OfType<AsyncAction>().ToList();
}
private List<AsyncAction> GetRemoveVdiActions()
{
return GetRemoveVdiActions(PatchingWizard_UploadPage.AllCreatedSuppPackVdis); ;
}
private void RunMultipleActions(string title, string startDescription, string endDescription,
List<AsyncAction> subActions)
{
if (subActions.Count > 0)
{
using (MultipleAction multipleAction = new MultipleAction(xenConnection, title, startDescription,
endDescription, subActions, false, true))
{
ActionProgressDialog dialog = new ActionProgressDialog(multipleAction, ProgressBarStyle.Blocks);
dialog.ShowDialog(Program.MainWindow);
}
}
}
protected override void OnCancel()
{
base.OnCancel();
List<AsyncAction> subActions = BuildSubActions(GetUnwindChangesActions, GetRemovePatchActions, GetRemoveVdiActions);
RunMultipleActions(Messages.REVERT_WIZARD_CHANGES, Messages.REVERTING_WIZARD_CHANGES,
Messages.REVERTED_WIZARD_CHANGES, subActions);
RemoveDownloadedPatches();
}
private void RemoveUnwantedPatches(List<Pool_patch> patchesToRemove)
{
List<AsyncAction> subActions = GetRemovePatchActions(patchesToRemove);
RunMultipleActions(Messages.REMOVE_UPDATES, Messages.REMOVING_UPDATES, Messages.REMOVED_UPDATES, subActions);
}
private void RemoveTemporaryVdis()
{
List<AsyncAction> subActions = GetRemoveVdiActions();
RunMultipleActions(Messages.REMOVE_UPDATES, Messages.REMOVING_UPDATES, Messages.REMOVED_UPDATES, subActions);
}
private void RemoveDownloadedPatches()
{
foreach (string downloadedPatch in PatchingWizard_UploadPage.AllDownloadedPatches.Values)
{
try
{
if (File.Exists(downloadedPatch))
{
File.Delete(downloadedPatch);
}
}
catch
{
log.DebugFormat("Could not remove downloaded patch {0} ", downloadedPatch);
}
}
}
protected override void FinishWizard()
{
if (PatchingWizard_UploadPage.NewUploadedPatches != null)
{
List<Pool_patch> patchesToRemove =
PatchingWizard_UploadPage.NewUploadedPatches.Keys.ToList().Where(
patch => patch.uuid != PatchingWizard_UploadPage.Patch.uuid).ToList();
RemoveUnwantedPatches(patchesToRemove);
}
if (PatchingWizard_UploadPage.AllCreatedSuppPackVdis != null)
RemoveTemporaryVdis();
RemoveDownloadedPatches();
base.FinishWizard();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
using System.Text;
using System.Threading;
using Couchbase.Lite;
using Couchbase.Lite.Auth;
using Newtonsoft.Json.Linq;
using TaskManager.Common;
namespace TaskManager.Shared
{
public class TaskProxy : ObjectProxy<Task>
{
public Document Document { get; }
public TaskProxy(Task task, Document document) : base(task)
{
Document = document;
}
protected override void OnMethodCall(MethodBase method)
{
}
}
public class TaskBase : ObjectDatabase<Task>
{
public override ICollection<Task> Objects
{
get
{
if (tasks == null)
Load();
return tasks;
}
}
private Database database;
private Uri uri;
private IAuthenticator authenticator;
private List<Task> tasks;
private List<Tuple<Task, Document>> taskDocuments = new List<Tuple<Task, Document>>();
public TaskBase(string address, string username, string password)
{
Manager manager = Manager.SharedInstance;
database = manager.GetDatabase("tasks");
uri = new Uri(address);
authenticator = AuthenticatorFactory.CreateBasicAuthenticator(username, password);
}
public override void Load()
{
/*
System.Data.SQLite.SQLiteConnection connection = new System.Data.SQLite.SQLiteConnection(@"Data Source=D:\Projets\C#\TaskManager\Samples\Tasks.db");
connection.Open();
//Clear();
TaskDatabase db = new TaskDatabase(connection);
tasks = db.Tasks;
return;
/**/
tasks = new List<Task>();
// Force sync to sevrer
Replication replication = database.CreatePullReplication(uri);
replication.Authenticator = authenticator;
replication.Run();
Query query = database.CreateAllDocumentsQuery();
Document[] documents = query.Run().Select(r => r.Document).ToArray();
Dictionary<string, Tag> tags = new Dictionary<string, Tag>();
// First pass to create task objects
foreach (Document document in documents)
{
Task task = new Task();
task.Name = document.GetProperty<string>("name");
task.Description = document.GetProperty<string>("description");
task.Date = document.GetProperty<DateTime?>("date");
// Tags
JArray tagNames = document.GetProperty("tags") as JArray;
if (tagNames != null)
{
foreach (JToken tagName in tagNames)
{
string name = tagName.Value<string>();
Tag tag;
if (!tags.TryGetValue(name, out tag))
tags.Add(name, tag = new Tag(name, TagColor.Black));
task.Tags.Add(tag);
}
}
// Attachements
foreach (Couchbase.Lite.Attachment dbAttachment in document.CurrentRevision.Attachments)
{
Common.Attachment attachment = new Common.Attachment();
attachment.Name = dbAttachment.Name;
attachment.Type = AttachmentType.Binary;
attachment.Data = dbAttachment.ContentStream.ReadBytes();
task.Attachements.Add(attachment);
}
// Metadata
JObject metadata = document.GetProperty("metadata") as JObject;
if (metadata != null)
{
foreach (var pair in metadata)
task.Metadata.Add(pair.Key, pair.Value);
}
taskDocuments.Add(Tuple.Create(task, document));
tasks.Add(task);
}
// Second pass to link them
foreach (Document document in documents)
{
Task task = taskDocuments.First(p => p.Item2 == document).Item1;
JArray children = document.GetProperty("children") as JArray;
if (children != null)
{
foreach (JObject childDocument in children)
{
string childDocumentId = childDocument["_id"].Value<string>();
Task childTask = taskDocuments.FirstOrDefault(p => p.Item2.Id == childDocumentId)?.Item1;
if (childTask == null)
continue;
task.Children.Add(childTask);
childTask.Parents.Add(task);
}
}
}
}
public override void Save()
{
// Save everything
database.RunInTransaction(new RunInTransactionDelegate(() =>
{
// Delete unused documents
Task[] oldTasks = taskDocuments.Select(p => p.Item1).Except(tasks).ToArray();
foreach (Task oldTask in oldTasks)
taskDocuments.First(p => p.Item1 == oldTask).Item2.Delete();
// Create new documents
Task[] newTasks = tasks.Except(taskDocuments.Select(p => p.Item1)).ToArray();
foreach (Task newTask in newTasks)
taskDocuments.Add(Tuple.Create(newTask, database.CreateDocument()));
// Update everything
foreach (var pair in taskDocuments)
{
Task task = pair.Item1;
if (oldTasks.Contains(task))
continue;
pair.Item2.Update(r =>
{
IDictionary<string, object> properties = r.Properties;
properties["name"] = task.Name;
properties["description"] = task.Description;
properties["date"] = task.Date;
properties["tags"] = new JArray(task.Tags.Select(t => t.Name));
properties["metadata"] = new JObject(task.Metadata.Select(m => new JProperty(m.Key, m.Value)));
properties["children"] = new JArray(task.Children.Select(c => new JObject(new JProperty("_id", taskDocuments.First(p => p.Item1 == c).Item2.Id))));
return true;
});
}
return true;
}));
// Then force sync to sevrer
Replication replication = database.CreatePushReplication(uri);
replication.Authenticator = authenticator;
replication.Run();
}
public void Clear()
{
// Remove every documents
database.RunInTransaction(new RunInTransactionDelegate(() =>
{
Query query = database.CreateAllDocumentsQuery();
foreach (QueryRow row in query.Run())
row.Document.Delete();
return true;
}));
// Then force sync to sevrer
Replication replication = database.CreatePushReplication(uri);
replication.Authenticator = authenticator;
replication.Run();
}
}
internal static class ReplicationExtensions
{
internal static void Run(this Replication me)
{
if (me.Continuous)
throw new NotSupportedException();
ManualResetEvent resetEvent = new ManualResetEvent(false);
EventHandler<ReplicationChangeEventArgs> handler = (s, e) =>
{
if (e.Status == ReplicationStatus.Stopped)
resetEvent.Set();
};
me.Changed += handler;
me.Start();
resetEvent.WaitOne();
me.Changed -= handler;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using NUnit.Framework;
using ServiceStack.Common.Extensions;
using ServiceStack.Common.Tests.Models;
using ServiceStack.Text;
using ServiceStack.DataAnnotations;
using System.ComponentModel.DataAnnotations;
namespace ServiceStack.OrmLite.Tests
{
[TestFixture]
public class OrmLiteGetScalarTests:OrmLiteTestBase
{
[Test]
public void Can_get_scalar_value(){
List<Author> authors = new List<Author>();
authors.Add(new Author() { Name = "Demis Bellot", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 99.9m, Comments = "CSharp books", Rate = 10, City = "London", FloatProperty=10.25f, DoubleProperty=3.23 });
authors.Add(new Author() { Name = "Angel Colmenares", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 50.0m, Comments = "CSharp books", Rate = 5, City = "Bogota",FloatProperty=7.59f,DoubleProperty=4.23 });
authors.Add(new Author() { Name = "Adam Witco", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 80.0m, Comments = "Math Books", Rate = 9, City = "London",FloatProperty=15.5f,DoubleProperty=5.42 });
authors.Add(new Author() { Name = "Claudia Espinel", Birthday = DateTime.Today.AddYears(-23), Active = true, Earnings = 60.0m, Comments = "Cooking books", Rate = 10, City = "Bogota",FloatProperty=0.57f, DoubleProperty=8.76});
authors.Add(new Author() { Name = "Libardo Pajaro", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 80.0m, Comments = "CSharp books", Rate = 9, City = "Bogota", FloatProperty=8.43f, DoubleProperty=7.35});
authors.Add(new Author() { Name = "Jorge Garzon", Birthday = DateTime.Today.AddYears(-28), Active = true, Earnings = 70.0m, Comments = "CSharp books", Rate = 9, City = "Bogota", FloatProperty=1.25f, DoubleProperty=0.3652});
authors.Add(new Author() { Name = "Alejandro Isaza", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 70.0m, Comments = "Java books", Rate = 0, City = "Bogota", FloatProperty=1.5f, DoubleProperty=100.563});
authors.Add(new Author() { Name = "Wilmer Agamez", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 30.0m, Comments = "Java books", Rate = 0, City = "Cartagena", FloatProperty=3.5f,DoubleProperty=7.23 });
authors.Add(new Author() { Name = "Rodger Contreras", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 90.0m, Comments = "CSharp books", Rate = 8, City = "Cartagena", FloatProperty=0.25f,DoubleProperty=9.23 });
authors.Add(new Author() { Name = "Chuck Benedict", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "CSharp books", Rate = 8, City = "London", FloatProperty=9.95f,DoubleProperty=4.91 });
authors.Add(new Author() { Name = "James Benedict II", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "Java books", Rate = 5, City = "Berlin",FloatProperty=4.44f,DoubleProperty=6.41 });
authors.Add(new Author() { Name = "Ethan Brown", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 45.0m, Comments = "CSharp books", Rate = 5, City = "Madrid", FloatProperty=6.67f, DoubleProperty=8.05 });
authors.Add(new Author() { Name = "Xavi Garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 75.0m, Comments = "CSharp books", Rate = 9, City = "Madrid", FloatProperty=1.25f, DoubleProperty=3.99});
authors.Add(new Author() { Name = "Luis garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.0m, Comments = "CSharp books", Rate = 10,
City = "Mexico",
LastActivity= DateTime.Today,
NRate=5,
FloatProperty=1.25f,
NFloatProperty=3.15f,
DoubleProperty= 1.25,
NDoubleProperty= 8.25
});
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<Author>(true);
dbCmd.DeleteAll<Author>();
dbCmd.InsertAll(authors);
var expectedDate = authors.Max(e=>e.Birthday);
var r1 = dbCmd.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday) );
Assert.That(expectedDate, Is.EqualTo(r1));
expectedDate = authors.Where(e=>e.City=="London").Max(e=>e.Birthday);
r1 = dbCmd.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday), e=>e.City=="London" );
Assert.That(expectedDate, Is.EqualTo(r1));
r1 = dbCmd.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday), e=>e.City=="SinCity" );
Assert.That( default(DateTime), Is.EqualTo(r1));
var expectedNullableDate= authors.Max(e=>e.LastActivity);
DateTime? r2 = dbCmd.GetScalar<Author,DateTime?>(e=> Sql.Max(e.LastActivity));
Assert.That(expectedNullableDate, Is.EqualTo(r2));
expectedNullableDate= authors.Where(e=> e.City=="Bogota").Max(e=>e.LastActivity);
r2 = dbCmd.GetScalar<Author,DateTime?>(
e=> Sql.Max(e.LastActivity),
e=> e.City=="Bogota" );
Assert.That(expectedNullableDate, Is.EqualTo(r2));
r2 = dbCmd.GetScalar<Author, DateTime?>( e => Sql.Max(e.LastActivity), e=>e.City=="SinCity" );
Assert.That( default(DateTime?), Is.EqualTo(r2));
var expectedDecimal= authors.Max(e=>e.Earnings);
decimal r3 = dbCmd.GetScalar<Author,decimal>(e=> Sql.Max(e.Earnings));
Assert.That(expectedDecimal, Is.EqualTo(r3));
expectedDecimal= authors.Where(e=>e.City=="London").Max(e=>e.Earnings);
r3 = dbCmd.GetScalar<Author,decimal>(e=> Sql.Max(e.Earnings), e=>e.City=="London");
Assert.That(expectedDecimal, Is.EqualTo(r3));
r3 = dbCmd.GetScalar<Author,decimal>(e=> Sql.Max(e.Earnings), e=>e.City=="SinCity");
Assert.That( default(decimal), Is.EqualTo(r3));
var expectedNullableDecimal= authors.Max(e=>e.NEarnings);
decimal? r4 = dbCmd.GetScalar<Author,decimal?>(e=> Sql.Max(e.NEarnings));
Assert.That(expectedNullableDecimal, Is.EqualTo(r4));
expectedNullableDecimal= authors.Where(e=>e.City=="London").Max(e=>e.NEarnings);
r4 = dbCmd.GetScalar<Author,decimal?>(e=> Sql.Max(e.NEarnings), e=>e.City=="London");
Assert.That(expectedNullableDecimal, Is.EqualTo(r4));
r4 = dbCmd.GetScalar<Author,decimal?>(e=> Sql.Max(e.NEarnings), e=>e.City=="SinCity");
Assert.That( default(decimal?), Is.EqualTo(r4));
var expectedDouble =authors.Max(e=>e.DoubleProperty);
double r5 = dbCmd.GetScalar<Author,double>(e=> Sql.Max(e.DoubleProperty));
Assert.That(expectedDouble, Is.EqualTo(r5));
expectedDouble =authors.Where(e=>e.City=="London").Max(e=>e.DoubleProperty);
r5 = dbCmd.GetScalar<Author,double>(e=> Sql.Max(e.DoubleProperty), e=>e.City=="London");
Assert.That(expectedDouble, Is.EqualTo(r5));
r5 = dbCmd.GetScalar<Author,double>(e=> Sql.Max(e.DoubleProperty), e=>e.City=="SinCity");
Assert.That(default(double),Is.EqualTo(r5));
var expectedNullableDouble =authors.Max(e=>e.NDoubleProperty);
double? r6 = dbCmd.GetScalar<Author,double?>(e=> Sql.Max(e.NDoubleProperty));
Assert.That(expectedNullableDouble, Is.EqualTo(r6));
expectedNullableDouble =authors.Where(e=>e.City=="London").Max(e=>e.NDoubleProperty);
r6 = dbCmd.GetScalar<Author,double?>(e=> Sql.Max(e.NDoubleProperty), e=>e.City=="London");
Assert.That(expectedNullableDouble, Is.EqualTo(r6));
r6 = dbCmd.GetScalar<Author,double?>(e=> Sql.Max(e.NDoubleProperty), e=>e.City=="SinCity");
Assert.That(default(double?),Is.EqualTo(r6));
var expectedFloat =authors.Max(e=>e.FloatProperty);
var r7 = dbCmd.GetScalar<Author,float>(e=> Sql.Max(e.FloatProperty));
Assert.That(expectedFloat, Is.EqualTo(r7));
expectedFloat =authors.Where(e=>e.City=="London").Max(e=>e.FloatProperty);
r7 = dbCmd.GetScalar<Author,float>(e=> Sql.Max(e.FloatProperty), e=>e.City=="London");
Assert.That(expectedFloat, Is.EqualTo(r7));
r7 = dbCmd.GetScalar<Author,float>(e=> Sql.Max(e.FloatProperty), e=>e.City=="SinCity");
Assert.That(default(float),Is.EqualTo(r7));
var expectedNullableFloat =authors.Max(e=>e.NFloatProperty);
var r8 = dbCmd.GetScalar<Author,float?>(e=> Sql.Max(e.NFloatProperty));
Assert.That(expectedNullableFloat, Is.EqualTo(r8));
expectedNullableFloat =authors.Where(e=>e.City=="London").Max(e=>e.NFloatProperty);
r8 = dbCmd.GetScalar<Author,float?>(e=> Sql.Max(e.NFloatProperty), e=>e.City=="London");
Assert.That(expectedNullableFloat, Is.EqualTo(r8));
r8 = dbCmd.GetScalar<Author,float?>(e=> Sql.Max(e.NFloatProperty), e=>e.City=="SinCity");
Assert.That(default(float?),Is.EqualTo(r8));
var expectedString=authors.Min(e=>e.Name);
var r9 = dbCmd.GetScalar<Author,string>(e=> Sql.Min(e.Name));
Assert.That(expectedString, Is.EqualTo(r9));
expectedString=authors.Where(e=>e.City=="London").Min(e=>e.Name);
r9 = dbCmd.GetScalar<Author,string>(e=> Sql.Min(e.Name), e=>e.City=="London");
Assert.That(expectedString, Is.EqualTo(r9));
r9 = dbCmd.GetScalar<Author,string>(e=> Sql.Max(e.Name), e=>e.City=="SinCity");
Assert.IsNullOrEmpty(r9);
//var expectedBool=authors.Min(e=>e.Active);
//var r10 = dbCmd.GetScalar<Author,bool>(e=> Sql.Min(e.Active));
//Assert.That(expectedBool, Is.EqualTo(r10));
//expectedBool=authors.Max(e=>e.Active);
//r10 = dbCmd.GetScalar<Author,bool>(e=> Sql.Max(e.Active));
//Assert.That(expectedBool, Is.EqualTo(r10));
//r10 = dbCmd.GetScalar<Author,bool>(e=> Sql.Max(e.Active), e=>e.City=="SinCity");
//Assert.IsFalse(r10);
var expectedShort =authors.Max(e=>e.Rate);
var r11 = dbCmd.GetScalar<Author,short>(e=> Sql.Max(e.Rate));
Assert.That(expectedShort, Is.EqualTo(r11));
expectedShort =authors.Where(e=>e.City=="London").Max(e=>e.Rate);
r11 = dbCmd.GetScalar<Author,short>(e=> Sql.Max(e.Rate), e=>e.City=="London");
Assert.That(expectedShort, Is.EqualTo(r11));
r11 = dbCmd.GetScalar<Author,short>(e=> Sql.Max(e.Rate), e=>e.City=="SinCity");
Assert.That(default(short),Is.EqualTo(r7));
var expectedNullableShort =authors.Max(e=>e.NRate);
var r12 = dbCmd.GetScalar<Author,short?>(e=> Sql.Max(e.NRate));
Assert.That(expectedNullableShort, Is.EqualTo(r12));
expectedNullableShort =authors.Where(e=>e.City=="London").Max(e=>e.NRate);
r12 = dbCmd.GetScalar<Author,short?>(e=> Sql.Max(e.NRate), e=>e.City=="London");
Assert.That(expectedNullableShort, Is.EqualTo(r12));
r12 = dbCmd.GetScalar<Author,short?>(e=> Sql.Max(e.NRate), e=>e.City=="SinCity");
Assert.That(default(short?),Is.EqualTo(r12));
}
}
}
public class Author
{
public Author(){}
[AutoIncrement]
[Alias("AuthorID")]
public Int32 Id { get; set;}
[Index(Unique = true)]
[StringLength(40)]
public string Name { get; set;}
public DateTime Birthday { get; set;}
public DateTime? LastActivity { get; set;}
public decimal Earnings { get; set;}
public decimal? NEarnings { get; set;}
public bool Active { get; set; }
[StringLength(80)]
[Alias("JobCity")]
public string City { get; set;}
[StringLength(80)]
[Alias("Comment")]
public string Comments { get; set;}
public short Rate{ get; set;}
public short? NRate{ get; set;}
public float FloatProperty { get; set;}
public float? NFloatProperty { get; set;}
public double DoubleProperty { get; set;}
public double? NDoubleProperty { get; set;}
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TextStructureNavigation
{
internal partial class AbstractTextStructureNavigatorProvider
{
private class TextStructureNavigator : ITextStructureNavigator
{
private readonly ITextBuffer _subjectBuffer;
private readonly ITextStructureNavigator _naturalLanguageNavigator;
private readonly AbstractTextStructureNavigatorProvider _provider;
private readonly IWaitIndicator _waitIndicator;
internal TextStructureNavigator(
ITextBuffer subjectBuffer,
ITextStructureNavigator naturalLanguageNavigator,
AbstractTextStructureNavigatorProvider provider,
IWaitIndicator waitIndicator)
{
Contract.ThrowIfNull(subjectBuffer);
Contract.ThrowIfNull(naturalLanguageNavigator);
Contract.ThrowIfNull(provider);
_subjectBuffer = subjectBuffer;
_naturalLanguageNavigator = naturalLanguageNavigator;
_provider = provider;
_waitIndicator = waitIndicator;
}
public IContentType ContentType
{
get { return _subjectBuffer.ContentType; }
}
public TextExtent GetExtentOfWord(SnapshotPoint currentPosition)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetExtentOfWord, CancellationToken.None))
{
var result = default(TextExtent);
_waitIndicator.Wait(
title: EditorFeaturesResources.TextNavigation,
message: EditorFeaturesResources.FindingWordExtent,
allowCancel: true,
action: waitContext =>
{
result = GetExtentOfWordWorker(currentPosition, waitContext.CancellationToken);
});
return result;
}
}
private TextExtent GetExtentOfWordWorker(SnapshotPoint position, CancellationToken cancellationToken)
{
var textLength = position.Snapshot.Length;
if (textLength == 0)
{
return _naturalLanguageNavigator.GetExtentOfWord(position);
}
// If at the end of the file, go back one character so stuff works
if (position == textLength && position > 0)
{
position = position - 1;
}
// If we're at the EOL position, return the line break's extent
var line = position.Snapshot.GetLineFromPosition(position);
if (position >= line.End && position < line.EndIncludingLineBreak)
{
return new TextExtent(new SnapshotSpan(line.End, line.EndIncludingLineBreak - line.End), isSignificant: false);
}
var document = GetDocument(position, cancellationToken);
if (document != null)
{
var root = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetRoot(cancellationToken);
var trivia = root.FindTrivia(position, findInsideTrivia: true);
if (trivia != default(SyntaxTrivia))
{
if (trivia.Span.Start == position && _provider.ShouldSelectEntireTriviaFromStart(trivia))
{
// We want to select the entire comment
return new TextExtent(trivia.Span.ToSnapshotSpan(position.Snapshot), isSignificant: true);
}
}
var token = root.FindToken(position, findInsideTrivia: true);
// If end of file, go back a token
if (token.Span.Length == 0 && token.Span.Start == textLength)
{
token = token.GetPreviousToken();
}
if (token.Span.Length > 0 && token.Span.Contains(position) && !_provider.IsWithinNaturalLanguage(token, position))
{
// Cursor position is in our domain - handle it.
return _provider.GetExtentOfWordFromToken(token, position);
}
}
// Fall back to natural language navigator do its thing.
return _naturalLanguageNavigator.GetExtentOfWord(position);
}
public SnapshotSpan GetSpanOfEnclosing(SnapshotSpan activeSpan)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfEnclosing, CancellationToken.None))
{
var span = default(SnapshotSpan);
var result = _waitIndicator.Wait(
title: EditorFeaturesResources.TextNavigation,
message: EditorFeaturesResources.FindingEnclosingSpan,
allowCancel: true,
action: waitContext =>
{
span = GetSpanOfEnclosingWorker(activeSpan, waitContext.CancellationToken);
});
return result == WaitIndicatorResult.Completed ? span : activeSpan;
}
}
private SnapshotSpan GetSpanOfEnclosingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken)
{
// Find node that covers the entire span.
var node = FindLeafNode(activeSpan, cancellationToken);
if (node != null && activeSpan.Length == node.Value.Span.Length)
{
// Go one level up so the span widens.
node = GetEnclosingNode(node.Value);
}
return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot);
}
public SnapshotSpan GetSpanOfFirstChild(SnapshotSpan activeSpan)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfFirstChild, CancellationToken.None))
{
var span = default(SnapshotSpan);
var result = _waitIndicator.Wait(
title: EditorFeaturesResources.TextNavigation,
message: EditorFeaturesResources.FindingEnclosingSpan,
allowCancel: true,
action: waitContext =>
{
span = GetSpanOfFirstChildWorker(activeSpan, waitContext.CancellationToken);
});
return result == WaitIndicatorResult.Completed ? span : activeSpan;
}
}
private SnapshotSpan GetSpanOfFirstChildWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken)
{
// Find node that covers the entire span.
var node = FindLeafNode(activeSpan, cancellationToken);
if (node != null)
{
// Take first child if possible, otherwise default to node itself.
var firstChild = node.Value.ChildNodesAndTokens().FirstOrNullable();
if (firstChild.HasValue)
{
node = firstChild.Value;
}
}
return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot);
}
public SnapshotSpan GetSpanOfNextSibling(SnapshotSpan activeSpan)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfNextSibling, CancellationToken.None))
{
var span = default(SnapshotSpan);
var result = _waitIndicator.Wait(
title: EditorFeaturesResources.TextNavigation,
message: EditorFeaturesResources.FindingSpanOfNextSibling,
allowCancel: true,
action: waitContext =>
{
span = GetSpanOfNextSiblingWorker(activeSpan, waitContext.CancellationToken);
});
return result == WaitIndicatorResult.Completed ? span : activeSpan;
}
}
private SnapshotSpan GetSpanOfNextSiblingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken)
{
// Find node that covers the entire span.
var node = FindLeafNode(activeSpan, cancellationToken);
if (node != null)
{
// Get ancestor with a wider span.
var parent = GetEnclosingNode(node.Value);
if (parent != null)
{
// Find node immediately after the current in the children collection.
SyntaxNodeOrToken? nodeOrToken = parent.Value
.ChildNodesAndTokens()
.SkipWhile(child => child != node)
.Skip(1)
.FirstOrNullable();
if (nodeOrToken.HasValue)
{
node = nodeOrToken.Value;
}
else
{
// If this is the last node, move to the parent so that the user can continue
// navigation at the higher level.
node = parent.Value;
}
}
}
return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot);
}
public SnapshotSpan GetSpanOfPreviousSibling(SnapshotSpan activeSpan)
{
using (Logger.LogBlock(FunctionId.TextStructureNavigator_GetSpanOfPreviousSibling, CancellationToken.None))
{
var span = default(SnapshotSpan);
var result = _waitIndicator.Wait(
title: EditorFeaturesResources.TextNavigation,
message: EditorFeaturesResources.FindingSpanOfPreviousSibling,
allowCancel: true,
action: waitContext =>
{
span = GetSpanOfPreviousSiblingWorker(activeSpan, waitContext.CancellationToken);
});
return result == WaitIndicatorResult.Completed ? span : activeSpan;
}
}
private SnapshotSpan GetSpanOfPreviousSiblingWorker(SnapshotSpan activeSpan, CancellationToken cancellationToken)
{
// Find node that covers the entire span.
var node = FindLeafNode(activeSpan, cancellationToken);
if (node != null)
{
// Get ancestor with a wider span.
var parent = GetEnclosingNode(node.Value);
if (parent != null)
{
// Find node immediately before the current in the children collection.
SyntaxNodeOrToken? nodeOrToken = parent.Value
.ChildNodesAndTokens()
.Reverse()
.SkipWhile(child => child != node)
.Skip(1)
.FirstOrNullable();
if (nodeOrToken.HasValue)
{
node = nodeOrToken.Value;
}
else
{
// If this is the first node, move to the parent so that the user can continue
// navigation at the higher level.
node = parent.Value;
}
}
}
return node == null ? activeSpan : node.Value.Span.ToSnapshotSpan(activeSpan.Snapshot);
}
private Document GetDocument(SnapshotPoint point, CancellationToken cancellationToken)
{
var textLength = point.Snapshot.Length;
if (textLength == 0)
{
return null;
}
return point.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
}
/// <summary>
/// Finds deepest node that covers given <see cref="SnapshotSpan"/>.
/// </summary>
private SyntaxNodeOrToken? FindLeafNode(SnapshotSpan span, CancellationToken cancellationToken)
{
SyntaxToken token;
if (!TryFindLeafToken(span.Start, out token, cancellationToken))
{
return null;
}
SyntaxNodeOrToken? node = token;
while (node != null && (span.End.Position > node.Value.Span.End))
{
node = GetEnclosingNode(node.Value);
}
return node;
}
/// <summary>
/// Given position in a text buffer returns the leaf syntax node it belongs to.
/// </summary>
private bool TryFindLeafToken(SnapshotPoint point, out SyntaxToken token, CancellationToken cancellationToken)
{
var syntaxTree = GetDocument(point, cancellationToken).GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);
if (syntaxTree != null)
{
token = syntaxTree.GetRoot(cancellationToken).FindToken(point, true);
return true;
}
token = default(SyntaxToken);
return false;
}
/// <summary>
/// Returns first ancestor of the node which has a span wider than node's span.
/// If none exist, returns the last available ancestor.
/// </summary>
private SyntaxNodeOrToken SkipSameSpanParents(SyntaxNodeOrToken node)
{
while (node.Parent != null && node.Parent.Span == node.Span)
{
node = node.Parent;
}
return node;
}
/// <summary>
/// Finds node enclosing current from navigation point of view (that is, some immediate ancestors
/// may be skipped during this process).
/// </summary>
private SyntaxNodeOrToken? GetEnclosingNode(SyntaxNodeOrToken node)
{
var parent = SkipSameSpanParents(node).Parent;
if (parent != null)
{
return parent;
}
else
{
return null;
}
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Xml;
using System.Xml.Schema;
class EndpointAddressProcessor
{
internal static readonly QNameKeyComparer QNameComparer = new QNameKeyComparer();
// QName Attributes
internal static readonly string XsiNs = XmlSchema.InstanceNamespace;
internal const string SerNs = "http://schemas.microsoft.com/2003/10/Serialization/";
internal const string TypeLN = "type";
internal const string ItemTypeLN = "ItemType";
internal const string FactoryTypeLN = "FactoryType";
// Pooling
internal EndpointAddressProcessor next;
StringBuilder builder;
byte[] resultData;
internal EndpointAddressProcessor(int length)
{
this.builder = new StringBuilder();
this.resultData = new byte[length];
}
internal EndpointAddressProcessor Next
{
get
{
return this.next;
}
set
{
this.next = value;
}
}
internal static string GetComparableForm(StringBuilder builder, XmlReader reader)
{
List<Attr> attrSet = new List<Attr>();
int valueLength = -1;
while (!reader.EOF)
{
XmlNodeType type = reader.MoveToContent();
switch (type)
{
case XmlNodeType.Element:
CompleteValue(builder, valueLength);
valueLength = -1;
builder.Append("<");
AppendString(builder, reader.LocalName);
builder.Append(":");
AppendString(builder, reader.NamespaceURI);
builder.Append(" ");
// Scan attributes
attrSet.Clear();
if (reader.MoveToFirstAttribute())
{
do
{
// Ignore namespaces
if (reader.Prefix == "xmlns" || reader.Name == "xmlns")
{
continue;
}
if (reader.LocalName == AddressingStrings.IsReferenceParameter && reader.NamespaceURI == Addressing10Strings.Namespace)
{
continue; // ignore IsReferenceParameter
}
string val = reader.Value;
if ((reader.LocalName == TypeLN && reader.NamespaceURI == XsiNs) ||
(reader.NamespaceURI == SerNs && (reader.LocalName == ItemTypeLN || reader.LocalName == FactoryTypeLN)))
{
string local, ns;
XmlUtil.ParseQName(reader, val, out local, out ns);
val = local + "^" + local.Length.ToString(CultureInfo.InvariantCulture) + ":" + ns + "^" + ns.Length.ToString(CultureInfo.InvariantCulture);
}
else if (reader.LocalName == XD.UtilityDictionary.IdAttribute.Value && reader.NamespaceURI == XD.UtilityDictionary.Namespace.Value)
{
// ignore wsu:Id attributes added by security to sign the header
continue;
}
attrSet.Add(new Attr(reader.LocalName, reader.NamespaceURI, val));
} while (reader.MoveToNextAttribute());
}
reader.MoveToElement();
if (attrSet.Count > 0)
{
attrSet.Sort();
for (int i = 0; i < attrSet.Count; ++i)
{
Attr a = attrSet[i];
AppendString(builder, a.local);
builder.Append(":");
AppendString(builder, a.ns);
builder.Append("=\"");
AppendString(builder, a.val);
builder.Append("\" ");
}
}
if (reader.IsEmptyElement)
builder.Append("></>"); // Should be the same as an empty tag.
else
builder.Append(">");
break;
case XmlNodeType.EndElement:
CompleteValue(builder, valueLength);
valueLength = -1;
builder.Append("</>");
break;
// Need to escape CDATA values
case XmlNodeType.CDATA:
CompleteValue(builder, valueLength);
valueLength = -1;
builder.Append("<![CDATA[");
AppendString(builder, reader.Value);
builder.Append("]]>");
break;
case XmlNodeType.SignificantWhitespace:
case XmlNodeType.Text:
if (valueLength < 0)
valueLength = builder.Length;
builder.Append(reader.Value);
break;
default:
// Do nothing
break;
}
reader.Read();
}
return builder.ToString();
}
static void AppendString(StringBuilder builder, string s)
{
builder.Append(s);
builder.Append("^");
builder.Append(s.Length.ToString(CultureInfo.InvariantCulture));
}
static void CompleteValue(StringBuilder builder, int startLength)
{
if (startLength < 0)
return;
int len = builder.Length - startLength;
builder.Append("^");
builder.Append(len.ToString(CultureInfo.InvariantCulture));
}
internal void Clear(int length)
{
if (this.resultData.Length == length)
{
Array.Clear(this.resultData, 0, this.resultData.Length);
}
else
{
this.resultData = new byte[length];
}
}
internal void ProcessHeaders(Message msg, Dictionary<QName, int> qnameLookup, Dictionary<string, HeaderBit[]> headerLookup)
{
string key;
HeaderBit[] bits;
QName qname;
MessageHeaders headers = msg.Headers;
for (int j = 0; j < headers.Count; ++j)
{
qname.name = headers[j].Name;
qname.ns = headers[j].Namespace;
if (headers.MessageVersion.Addressing == AddressingVersion.WSAddressing10
&& !headers[j].IsReferenceParameter)
{
continue;
}
if (qnameLookup.ContainsKey(qname))
{
builder.Remove(0, builder.Length);
XmlReader reader = headers.GetReaderAtHeader(j).ReadSubtree();
reader.Read(); // Needed after call to ReadSubtree
key = GetComparableForm(builder, reader);
if (headerLookup.TryGetValue(key, out bits))
{
SetBit(bits);
}
}
}
}
internal void SetBit(HeaderBit[] bits)
{
if (bits.Length == 1)
{
this.resultData[bits[0].index] |= bits[0].mask;
}
else
{
byte[] results = this.resultData;
for (int i = 0; i < bits.Length; ++i)
{
if ((results[bits[i].index] & bits[i].mask) == 0)
{
results[bits[i].index] |= bits[i].mask;
break;
}
}
}
}
internal bool TestExact(byte[] exact)
{
Fx.Assert(this.resultData.Length == exact.Length, "");
byte[] results = this.resultData;
for (int i = 0; i < exact.Length; ++i)
{
if (results[i] != exact[i])
{
return false;
}
}
return true;
}
internal bool TestMask(byte[] mask)
{
if (mask == null)
{
return true;
}
byte[] results = this.resultData;
for (int i = 0; i < mask.Length; ++i)
{
if ((results[i] & mask[i]) != mask[i])
{
return false;
}
}
return true;
}
internal struct QName
{
internal string name;
internal string ns;
}
internal class QNameKeyComparer : IComparer<QName>, IEqualityComparer<QName>
{
internal QNameKeyComparer()
{
}
public int Compare(QName x, QName y)
{
int i = string.CompareOrdinal(x.name, y.name);
if (i != 0)
return i;
return string.CompareOrdinal(x.ns, y.ns);
}
public bool Equals(QName x, QName y)
{
int i = string.CompareOrdinal(x.name, y.name);
if (i != 0)
return false;
return string.CompareOrdinal(x.ns, y.ns) == 0;
}
public int GetHashCode(QName obj)
{
return obj.name.GetHashCode() ^ obj.ns.GetHashCode();
}
}
internal struct HeaderBit
{
internal int index;
internal byte mask;
internal HeaderBit(int bitNum)
{
this.index = bitNum / 8;
this.mask = (byte)(1 << (bitNum % 8));
}
internal void AddToMask(ref byte[] mask)
{
if (mask == null)
{
mask = new byte[this.index + 1];
}
else if (mask.Length <= this.index)
{
Array.Resize(ref mask, this.index + 1);
}
mask[this.index] |= this.mask;
}
}
class Attr : IComparable<Attr>
{
internal string local;
internal string ns;
internal string val;
string key;
internal Attr(string l, string ns, string v)
{
this.local = l;
this.ns = ns;
this.val = v;
this.key = ns + ":" + l;
}
public int CompareTo(Attr a)
{
return string.Compare(this.key, a.key, StringComparison.Ordinal);
}
}
}
}
| |
// 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.Globalization;
using System.Text;
namespace System.Xml.Xsl.Runtime
{
internal class DecimalFormat
{
public NumberFormatInfo info;
public char digit;
public char zeroDigit;
public char patternSeparator;
internal DecimalFormat(NumberFormatInfo info, char digit, char zeroDigit, char patternSeparator)
{
this.info = info;
this.digit = digit;
this.zeroDigit = zeroDigit;
this.patternSeparator = patternSeparator;
}
}
internal class DecimalFormatter
{
private NumberFormatInfo _posFormatInfo;
private NumberFormatInfo _negFormatInfo;
private string _posFormat;
private string _negFormat;
private char _zeroDigit;
// These characters have special meaning for CLR and must be escaped
// <spec>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcustomnumericformatstrings.asp</spec>
private const string ClrSpecialChars = "0#.,%\u2030Ee\\'\";";
// This character is used to escape literal (passive) digits '0'..'9'
private const char EscChar = '\a';
public DecimalFormatter(string formatPicture, DecimalFormat decimalFormat)
{
Debug.Assert(formatPicture != null && decimalFormat != null);
if (formatPicture.Length == 0)
{
throw XsltException.Create(SR.Xslt_InvalidFormat);
}
_zeroDigit = decimalFormat.zeroDigit;
_posFormatInfo = (NumberFormatInfo)decimalFormat.info.Clone();
StringBuilder temp = new StringBuilder();
bool integer = true;
bool sawPattern = false, sawZeroDigit = false, sawDigit = false, sawDecimalSeparator = false;
bool digitOrZeroDigit = false;
char decimalSeparator = _posFormatInfo.NumberDecimalSeparator[0];
char groupSeparator = _posFormatInfo.NumberGroupSeparator[0];
char percentSymbol = _posFormatInfo.PercentSymbol[0];
char perMilleSymbol = _posFormatInfo.PerMilleSymbol[0];
int commaIndex = 0;
int groupingSize = 0;
int decimalIndex = -1;
int lastDigitIndex = -1;
for (int i = 0; i < formatPicture.Length; i++)
{
char ch = formatPicture[i];
if (ch == decimalFormat.digit)
{
if (sawZeroDigit && integer)
{
throw XsltException.Create(SR.Xslt_InvalidFormat1, formatPicture);
}
lastDigitIndex = temp.Length;
sawDigit = digitOrZeroDigit = true;
temp.Append('#');
continue;
}
if (ch == decimalFormat.zeroDigit)
{
if (sawDigit && !integer)
{
throw XsltException.Create(SR.Xslt_InvalidFormat2, formatPicture);
}
lastDigitIndex = temp.Length;
sawZeroDigit = digitOrZeroDigit = true;
temp.Append('0');
continue;
}
if (ch == decimalFormat.patternSeparator)
{
if (!digitOrZeroDigit)
{
throw XsltException.Create(SR.Xslt_InvalidFormat8);
}
if (sawPattern)
{
throw XsltException.Create(SR.Xslt_InvalidFormat3, formatPicture);
}
sawPattern = true;
if (decimalIndex < 0)
{
decimalIndex = lastDigitIndex + 1;
}
groupingSize = RemoveTrailingComma(temp, commaIndex, decimalIndex);
if (groupingSize > 9)
{
groupingSize = 0;
}
_posFormatInfo.NumberGroupSizes = new int[] { groupingSize };
if (!sawDecimalSeparator)
{
_posFormatInfo.NumberDecimalDigits = 0;
}
_posFormat = temp.ToString();
temp.Length = 0;
decimalIndex = -1;
lastDigitIndex = -1;
commaIndex = 0;
sawDigit = sawZeroDigit = digitOrZeroDigit = false;
sawDecimalSeparator = false;
integer = true;
_negFormatInfo = (NumberFormatInfo)decimalFormat.info.Clone();
_negFormatInfo.NegativeSign = string.Empty;
continue;
}
if (ch == decimalSeparator)
{
if (sawDecimalSeparator)
{
throw XsltException.Create(SR.Xslt_InvalidFormat5, formatPicture);
}
decimalIndex = temp.Length;
sawDecimalSeparator = true;
sawDigit = sawZeroDigit = integer = false;
temp.Append('.');
continue;
}
if (ch == groupSeparator)
{
commaIndex = temp.Length;
lastDigitIndex = commaIndex;
temp.Append(',');
continue;
}
if (ch == percentSymbol)
{
temp.Append('%');
continue;
}
if (ch == perMilleSymbol)
{
temp.Append('\u2030');
continue;
}
if (ch == '\'')
{
int pos = formatPicture.IndexOf('\'', i + 1);
if (pos < 0)
{
pos = formatPicture.Length - 1;
}
temp.Append(formatPicture, i, pos - i + 1);
i = pos;
continue;
}
// Escape literal digits with EscChar, double literal EscChar
if ('0' <= ch && ch <= '9' || ch == EscChar)
{
if (decimalFormat.zeroDigit != '0')
{
temp.Append(EscChar);
}
}
// Escape characters having special meaning for CLR
if (ClrSpecialChars.IndexOf(ch) >= 0)
{
temp.Append('\\');
}
temp.Append(ch);
}
if (!digitOrZeroDigit)
{
throw XsltException.Create(SR.Xslt_InvalidFormat8);
}
NumberFormatInfo formatInfo = sawPattern ? _negFormatInfo : _posFormatInfo;
if (decimalIndex < 0)
{
decimalIndex = lastDigitIndex + 1;
}
groupingSize = RemoveTrailingComma(temp, commaIndex, decimalIndex);
if (groupingSize > 9)
{
groupingSize = 0;
}
formatInfo.NumberGroupSizes = new int[] { groupingSize };
if (!sawDecimalSeparator)
{
formatInfo.NumberDecimalDigits = 0;
}
if (sawPattern)
{
_negFormat = temp.ToString();
}
else
{
_posFormat = temp.ToString();
}
}
private static int RemoveTrailingComma(StringBuilder builder, int commaIndex, int decimalIndex)
{
if (commaIndex > 0 && commaIndex == (decimalIndex - 1))
{
builder.Remove(decimalIndex - 1, 1);
}
else if (decimalIndex > commaIndex)
{
return decimalIndex - commaIndex - 1;
}
return 0;
}
public string Format(double value)
{
NumberFormatInfo formatInfo;
string subPicture;
if (value < 0 && _negFormatInfo != null)
{
formatInfo = _negFormatInfo;
subPicture = _negFormat;
}
else
{
formatInfo = _posFormatInfo;
subPicture = _posFormat;
}
string result = value.ToString(subPicture, formatInfo);
if (_zeroDigit != '0')
{
StringBuilder builder = new StringBuilder(result.Length);
int shift = _zeroDigit - '0';
for (int i = 0; i < result.Length; i++)
{
char ch = result[i];
if ((uint)(ch - '0') <= 9)
{
ch += (char)shift;
}
else if (ch == EscChar)
{
// This is an escaped literal digit or EscChar, thus unescape it. We make use
// of the fact that no extra EscChar could be inserted by value.ToString().
Debug.Assert(i + 1 < result.Length);
ch = result[++i];
Debug.Assert('0' <= ch && ch <= '9' || ch == EscChar);
}
builder.Append(ch);
}
result = builder.ToString();
}
return result;
}
public static string Format(double value, string formatPicture, DecimalFormat decimalFormat)
{
return new DecimalFormatter(formatPicture, decimalFormat).Format(value);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
namespace ImageProcessing2014
{
partial class Util
{
public class Math
{
/// <summary>
/// angle of prev-now-next in radians(?)
/// </summary>
/// <param name="prev"></param>
/// <param name="now"></param>
/// <param name="next"></param>
/// <returns>the angle prev-now-next</returns>
public static double GetAngle(Point prev, Point now, Point next)
{
double sinAngle = GetSinAngle (prev, now, next);
double cosAngle = GetCosAngle (prev, now, next);
if (sinAngle < 0) {
return 2 * System.Math.PI - System.Math.Acos (cosAngle);
}
return System.Math.Acos(cosAngle);
}
/// <summary>
/// returns the cosine of the angle prev-now-next
/// </summary>
/// <param name="prev"></param>
/// <param name="now"></param>
/// <param name="next"></param>
/// <returns>the cosine of the angle prev-now-next</returns>
public static double GetCosAngle(Point prev, Point now, Point next)
{
return Dot(prev, now, next) / (GetDistance(prev, now) * GetDistance(now, next));
}
/// <summary>
/// returns the cosine of the angle between vector1 and vector2
/// </summary>
/// <param name="vector1"></param>
/// <param name="vector2"></param>
/// <returns>the cosine of the angle between vector1 and vector2</returns>
public static double GetCosAngle(Point vector1, Point vector2)
{
//cos theta = (a dot b) / (magnitude a * magnitude b)
return System.Math.Acos((Dot(vector1, vector2) / (GetMagnitude(vector1) * GetMagnitude(vector2))));
}
/// <summary>
/// returns the sine of the angle between vector1 and vector2
/// </summary>
/// <param name="vector1"></param>
/// <param name="vector2"></param>
/// <returns>the sine of the angle between vector1 and vector2</returns>
public static double GetSinAngle(Point vector1, Point vector2)
{
return Cross(vector1, vector2) / (GetMagnitude(vector1) * GetMagnitude(vector2));
}
public static double GetSinAngle(Point prev, Point now, Point next)
{
return Cross(prev, now, next) / (GetDistance(prev, now) * GetDistance(now, next));
}
/// <summary>
/// returns the tangent of the angle between vector1 and vector2
/// </summary>
/// <param name="vector1"></param>
/// <param name="vector2"></param>
/// <returns>the tangent of the angle between vector1 and vector2</returns>
public static double GetTanAngle(Point vector1, Point vector2)
{
return (GetSinAngle(vector1, vector2) / GetCosAngle(vector1, vector2));
}
/// <summary>
/// returns the cross of vector1 and vector2
/// </summary>
/// <param name="vector1"></param>
/// <param name="vector2"></param>
/// <returns>the cross of vector1 and vector2</returns>
private static double Cross(Point vector1, Point vector2)
{
return vector1.X * vector2.Y - vector1.Y * vector2.X;
}
private static double Cross(Point prev, Point now, Point next)
{
var v1 = new Point(now.X - prev.X, now.Y - prev.Y);
var v2 = new Point(next.X - now.X, next.Y - now.Y);
return v1.X * v2.Y - v1.Y * v2.X;
}
/// <summary>
/// returns the dot of prev-now and now-next
/// </summary>
/// <param name="prev"></param>
/// <param name="now"></param>
/// <param name="next"></param>
/// <returns>the dot of prev-now and now-next</returns>
private static double Dot(Point prev, Point now, Point next)
{
var v1 = new Point(prev.X - now.X, prev.Y - now.Y);
var v2 = new Point(next.X - now.X, next.Y - now.Y);
return v1.X * v2.X + v1.Y * v2.Y;
}
/// <summary>
/// returns the dot two vectors, v1 and v2
/// </summary>
/// <param name="v1"></param>
/// <param name="v2"></param>
/// <returns>the dot of v1 and v2</returns>
private static double Dot(Point v1, Point v2)
{
return v1.X * v2.X + v1.Y * v2.Y;
}
/// <summary>
/// returns the distance between the two points
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns>the distance between the two points</returns>
public static double GetDistance(Point first, Point second)
{
var diff = new Point(first.X - second.X, first.Y - second.Y);
return System.Math.Sqrt(diff.X * diff.X + diff.Y * diff.Y);
}
/// <summary>
/// returns the distance between the two double points
/// </summary>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns>the distance between the two points</returns>
public static double GetDistance(DoublePoint first, DoublePoint second)
{
var diff = new DoublePoint(first.X - second.X, first.Y - second.Y);
return System.Math.Sqrt(diff.X * diff.X + diff.Y * diff.Y);
}
/// <summary>
/// returns the magnitude of the vector
/// </summary>
/// <param name="vector"></param>
/// <returns>the magnitude of the vector</returns>
public static double GetMagnitude(Point vector)
{
return System.Math.Sqrt(vector.X * vector.X + vector.Y * vector.Y);
}
/// <summary>
/// returns the horizontal distance across the image at a given distance from the camera in inches
/// </summary>
/// <param name="dist">the distance from the camera</param>
/// <param name="w">the width of the image in pixels</param>
/// <returns>the horizontal distance across the image (inches)</returns>
private static double GetInchesPerPixels(double dist, int w)
{
return VisionConstants.Camera.H_FOV_INCHES * dist / w;
}
/// <summary>
/// convert rectangular point to polar point
/// </summary>
/// <param name="x">x coordinate</param>
/// <param name="y">y coordinate</param>
/// <returns>returns polar coordinates</returns>
public static DoublePoint RectangularToPolar(Point p)
{
// the center of the image has coordinates 320, 240
double x = p.X - 320;
double y = p.Y - 240;
double r = System.Math.Sqrt (System.Math.Pow (x, 2) + System.Math.Pow (y, 2));
double theta = System.Math.Atan2(y,x);
return new DoublePoint(r, theta);
}
/// <summary>
/// convert polar point to rectangular point
/// </summary>
/// <param name="r">r</param>
/// <param name="theta">theta</param>
/// <returns>returns rectangular coordinates</returns>
public static DoublePoint PolarToRectangular(double r, double theta)
{
double x = r * System.Math.Cos (theta);
double y = r * System.Math.Sin (theta);
// the center of the image has coordinates 320, 240
x = x + 320;
y = y + 240;
return new DoublePoint(x, y);
}
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Tests
{
public class LastTests : EnumerableTests
{
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
Assert.Equal(q.Last(), q.Last());
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x;
Assert.Equal(q.Last(), q.Last());
}
public void TestEmptyIList<T>()
{
T[] source = { };
Assert.NotNull(source as IList<T>);
Assert.Throws<InvalidOperationException>(() => source.RunOnce().Last());
}
[Fact]
public void EmptyIListT()
{
TestEmptyIList<int>();
TestEmptyIList<string>();
TestEmptyIList<DateTime>();
TestEmptyIList<LastTests>();
}
[Fact]
public void IListTOneElement()
{
int[] source = { 5 };
int expected = 5;
Assert.NotNull(source as IList<int>);
Assert.Equal(expected, source.Last());
}
[Fact]
public void IListTManyElementsLastIsDefault()
{
int?[] source = { -10, 2, 4, 3, 0, 2, null };
int? expected = null;
Assert.IsAssignableFrom<IList<int?>>(source);
Assert.Equal(expected, source.Last());
}
[Fact]
public void IListTManyElementsLastIsNotDefault()
{
int?[] source = { -10, 2, 4, 3, 0, 2, null, 19 };
int? expected = 19;
Assert.IsAssignableFrom<IList<int?>>(source);
Assert.Equal(expected, source.Last());
}
private static IEnumerable<T> EmptySource<T>()
{
yield break;
}
private static void TestEmptyNotIList<T>()
{
var source = EmptySource<T>();
Assert.Null(source as IList<T>);
Assert.Throws<InvalidOperationException>(() => source.RunOnce().Last());
}
[Fact]
public void EmptyNotIListT()
{
TestEmptyNotIList<int>();
TestEmptyNotIList<string>();
TestEmptyNotIList<DateTime>();
TestEmptyNotIList<LastTests>();
}
[Fact]
public void OneElementNotIListT()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-5, 1);
int expected = -5;
Assert.Null(source as IList<int>);
Assert.Equal(expected, source.Last());
}
[Fact]
public void ManyElementsNotIListT()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(3, 10);
int expected = 12;
Assert.Null(source as IList<int>);
Assert.Equal(expected, source.Last());
}
[Fact]
public void IListEmptySourcePredicate()
{
int[] source = { };
Assert.Throws<InvalidOperationException>(() => source.Last(x => true));
Assert.Throws<InvalidOperationException>(() => source.Last(x => false));
}
[Fact]
public void OneElementIListTruePredicate()
{
int[] source = { 4 };
Func<int, bool> predicate = IsEven;
int expected = 4;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void ManyElementsIListPredicateFalseForAll()
{
int[] source = { 9, 5, 1, 3, 17, 21 };
Func<int, bool> predicate = IsEven;
Assert.Throws<InvalidOperationException>(() => source.Last(predicate));
}
[Fact]
public void IListPredicateTrueOnlyForLast()
{
int[] source = { 9, 5, 1, 3, 17, 21, 50 };
Func<int, bool> predicate = IsEven;
int expected = 50;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void IListPredicateTrueForSome()
{
int[] source = { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 };
Func<int, bool> predicate = IsEven;
int expected = 18;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void IListPredicateTrueForSomeRunOnce()
{
int[] source = { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 };
Func<int, bool> predicate = IsEven;
int expected = 18;
Assert.Equal(expected, source.RunOnce().Last(predicate));
}
[Fact]
public void NotIListIListEmptySourcePredicate()
{
IEnumerable<int> source = Enumerable.Range(1, 0);
Assert.Throws<InvalidOperationException>(() => source.Last(x => true));
Assert.Throws<InvalidOperationException>(() => source.Last(x => false));
}
[Fact]
public void OneElementNotIListTruePredicate()
{
IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(4, 1);
Func<int, bool> predicate = IsEven;
int expected = 4;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void ManyElementsNotIListPredicateFalseForAll()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 9, 5, 1, 3, 17, 21 });
Func<int, bool> predicate = IsEven;
Assert.Throws<InvalidOperationException>(() => source.Last(predicate));
}
[Fact]
public void NotIListPredicateTrueOnlyForLast()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 9, 5, 1, 3, 17, 21, 50 });
Func<int, bool> predicate = IsEven;
int expected = 50;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void NotIListPredicateTrueForSome()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 });
Func<int, bool> predicate = IsEven;
int expected = 18;
Assert.Equal(expected, source.Last(predicate));
}
[Fact]
public void NotIListPredicateTrueForSomeRunOnce()
{
IEnumerable<int> source = ForceNotCollection(new int[] { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 });
Func<int, bool> predicate = IsEven;
int expected = 18;
Assert.Equal(expected, source.RunOnce().Last(predicate));
}
[Fact]
public void NullSource()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Last());
}
[Fact]
public void NullSourcePredicateUsed()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).Last(i => i != 2));
}
[Fact]
public void NullPredicate()
{
Func<int, bool> predicate = null;
AssertExtensions.Throws<ArgumentNullException>("predicate", () => Enumerable.Range(0, 3).Last(predicate));
}
}
}
| |
using System.Net;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.RestrictedControllers;
public sealed class ReadOnlyControllerTests : IClassFixture<IntegrationTestContext<TestableStartup<RestrictionDbContext>, RestrictionDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<RestrictionDbContext>, RestrictionDbContext> _testContext;
private readonly RestrictionFakers _fakers = new();
public ReadOnlyControllerTests(IntegrationTestContext<TestableStartup<RestrictionDbContext>, RestrictionDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<BedsController>();
}
[Fact]
public async Task Can_get_resources()
{
// Arrange
const string route = "/beds";
// Act
(HttpResponseMessage httpResponse, _) = await _testContext.ExecuteGetAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
}
[Fact]
public async Task Can_get_resource()
{
// Arrange
Bed bed = _fakers.Bed.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Beds.Add(bed);
await dbContext.SaveChangesAsync();
});
string route = $"/beds/{bed.StringId}";
// Act
(HttpResponseMessage httpResponse, _) = await _testContext.ExecuteGetAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
}
[Fact]
public async Task Can_get_secondary_resources()
{
// Arrange
Bed bed = _fakers.Bed.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Beds.Add(bed);
await dbContext.SaveChangesAsync();
});
string route = $"/beds/{bed.StringId}/pillows";
// Act
(HttpResponseMessage httpResponse, _) = await _testContext.ExecuteGetAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
}
[Fact]
public async Task Can_get_secondary_resource()
{
// Arrange
Bed bed = _fakers.Bed.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Beds.Add(bed);
await dbContext.SaveChangesAsync();
});
string route = $"/beds/{bed.StringId}/room";
// Act
(HttpResponseMessage httpResponse, _) = await _testContext.ExecuteGetAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
}
[Fact]
public async Task Can_get_relationship()
{
// Arrange
Bed bed = _fakers.Bed.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Beds.Add(bed);
await dbContext.SaveChangesAsync();
});
string route = $"/beds/{bed.StringId}/relationships/pillows";
// Act
(HttpResponseMessage httpResponse, _) = await _testContext.ExecuteGetAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
}
[Fact]
public async Task Cannot_create_resource()
{
// Arrange
var requestBody = new
{
data = new
{
type = "beds",
attributes = new
{
}
}
};
const string route = "/beds?include=pillows";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Forbidden);
error.Title.Should().Be("The requested endpoint is not accessible.");
error.Detail.Should().Be("Endpoint '/beds' is not accessible for POST requests.");
}
[Fact]
public async Task Cannot_update_resource()
{
// Arrange
Bed existingBed = _fakers.Bed.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Beds.Add(existingBed);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "beds",
id = existingBed.StringId,
attributes = new
{
}
}
};
string route = $"/beds/{existingBed.StringId}";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Forbidden);
error.Title.Should().Be("The requested endpoint is not accessible.");
error.Detail.Should().Be($"Endpoint '{route}' is not accessible for PATCH requests.");
}
[Fact]
public async Task Cannot_delete_resource()
{
// Arrange
Bed existingBed = _fakers.Bed.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Beds.Add(existingBed);
await dbContext.SaveChangesAsync();
});
string route = $"/beds/{existingBed.StringId}";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Forbidden);
error.Title.Should().Be("The requested endpoint is not accessible.");
error.Detail.Should().Be($"Endpoint '{route}' is not accessible for DELETE requests.");
}
[Fact]
public async Task Cannot_update_relationship()
{
// Arrange
Bed existingBed = _fakers.Bed.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Beds.Add(existingBed);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = (object?)null
};
string route = $"/beds/{existingBed.StringId}/relationships/room";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Forbidden);
error.Title.Should().Be("The requested endpoint is not accessible.");
error.Detail.Should().Be($"Endpoint '{route}' is not accessible for PATCH requests.");
}
[Fact]
public async Task Cannot_add_to_ToMany_relationship()
{
// Arrange
Bed existingBed = _fakers.Bed.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Beds.Add(existingBed);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = Array.Empty<object>()
};
string route = $"/beds/{existingBed.StringId}/relationships/pillows";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Forbidden);
error.Title.Should().Be("The requested endpoint is not accessible.");
error.Detail.Should().Be($"Endpoint '{route}' is not accessible for POST requests.");
}
[Fact]
public async Task Cannot_remove_from_ToMany_relationship()
{
// Arrange
Bed existingBed = _fakers.Bed.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Beds.Add(existingBed);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = Array.Empty<object>()
};
string route = $"/beds/{existingBed.StringId}/relationships/pillows";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Forbidden);
responseDocument.Errors.ShouldHaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.Forbidden);
error.Title.Should().Be("The requested endpoint is not accessible.");
error.Detail.Should().Be($"Endpoint '{route}' is not accessible for DELETE requests.");
}
}
| |
using XPT.Games.Generic.Constants;
using XPT.Games.Generic.Maps;
using XPT.Games.Twinion.Entities;
namespace XPT.Games.Twinion.Maps {
class TwMap13 : TwMap {
public override int MapIndex => 13;
public override int MapID => 0x0503;
protected override int RandomEncounterChance => 0;
protected override int RandomEncounterExtraCount => 2;
private const int GRAVE_ZAP = 1;
private const int RANDOMMONST = 1;
protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 6, 1, 132, Direction.North);
ShowText(player, type, doMsgs, "To Carriage House");
}
protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
}
protected override void FnEvent03(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Darkness envelops you as you enter the Graveyard. You can barely read the sign which says, 'NorthEast Gate.'");
}
protected override void FnEvent04(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 7, 2, 75, Direction.West);
ShowText(player, type, doMsgs, "All that you can see on the door ahead is Sn k P t.");
}
protected override void FnEvent05(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, DWARFWIZARD);
ShowText(player, type, doMsgs, "You meet Xanith the Cartographer, who is trying to map the cemetery.");
ShowText(player, type, doMsgs, "'Ah, more adventurers on the way to my shop! Have you mastered the dungeon thus far?");
ShowText(player, type, doMsgs, "I hope you've found the secret clues that equal the number of Snicker's brothers.");
ShowText(player, type, doMsgs, "If you have not, my assistants' payments will be of no value to you.'");
}
protected override void FnEvent06(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasUsedSkill(player, type, ref doMsgs, DETECT_SKILL) >= 6 || HasUsedSpell(player, type, ref doMsgs, TRUE_SEEING_SPELL) >= 1 || UsedItem(player, type, ref doMsgs, HELMOFWISDOM, HELMOFWISDOM) || UsedItem(player, type, ref doMsgs, VALKYRIESHELM, VALKYRIESHELM) || UsedItem(player, type, ref doMsgs, RINGOFTHIEVES, RINGOFTHIEVES) || UsedItem(player, type, ref doMsgs, CRYSTALBALL, CRYSTALBALL)) {
ShowText(player, type, doMsgs, "The tomb door opens.");
DoorHere(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
else {
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent07(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "You see the NorthEast Gate to the East.");
}
protected override void FnEvent08(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, ORCRANGER);
ShowText(player, type, doMsgs, "A Gravedigger appears and wags a bony finger at you.");
ShowText(player, type, doMsgs, "'All tombs do not contain treasure, you know. Some harbor grave rewards.'");
}
protected override void FnEvent09(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Disturbed graveyard spirits attack you.");
if (HasItem(player, type, doMsgs, TRACKERSMASK)) {
SetTreasure(player, type, doMsgs, ELIXIROFHEALTH, HALOSCROLL, 0, 0, 0, 1500);
}
else {
SetTreasure(player, type, doMsgs, TRACKERSMASK, MANAELIXIR, ELIXIROFHEALTH, 0, 0, 3000);
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 3);
AddEncounter(player, type, doMsgs, 05, 34);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 25);
AddEncounter(player, type, doMsgs, 02, 27);
AddEncounter(player, type, doMsgs, 03, 27);
}
else {
AddEncounter(player, type, doMsgs, 01, 28);
AddEncounter(player, type, doMsgs, 02, 11);
AddEncounter(player, type, doMsgs, 03, 27);
AddEncounter(player, type, doMsgs, 04, 8);
}
}
protected override void FnEvent0A(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowPortrait(player, type, doMsgs, FOUNTAIN);
ModifyHealth(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
ModifyMana(player, type, doMsgs, 10000);
ShowText(player, type, doMsgs, "Angel Fountain replenishes your Health and Mana.");
}
protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
TeleportParty(player, type, doMsgs, 5, 3, 28, Direction.North);
ShowText(player, type, doMsgs, "The shadows of death that clutch at you evaporate as you are spirited to safety.");
}
protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasUsedSkill(player, type, ref doMsgs, DETECT_SKILL) >= 6 || HasUsedSpell(player, type, ref doMsgs, TRUE_SEEING_SPELL) >= 1 || UsedItem(player, type, ref doMsgs, HELMOFWISDOM, HELMOFWISDOM) || UsedItem(player, type, ref doMsgs, VALKYRIESHELM, VALKYRIESHELM) || UsedItem(player, type, ref doMsgs, RINGOFTHIEVES, RINGOFTHIEVES) || UsedItem(player, type, ref doMsgs, CRYSTALBALL, CRYSTALBALL)) {
ShowText(player, type, doMsgs, "You discover a long forgotten door.");
DoorHere(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
else {
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You disturb the souls of the entombed.");
if (HasItem(player, type, doMsgs, LIGHTNINGROD) || HasItem(player, type, doMsgs, JADEDRING)) {
SetTreasure(player, type, doMsgs, BINDINGTALISMAN, ICESHIELD, 0, 0, 0, 1000);
}
else {
SetTreasure(player, type, doMsgs, JADEDRING, LIGHTNINGROD, LIFEGIVER, 0, 0, 3000);
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 6);
AddEncounter(player, type, doMsgs, 02, 34);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 2);
AddEncounter(player, type, doMsgs, 02, 5);
AddEncounter(player, type, doMsgs, 03, 28);
}
else {
AddEncounter(player, type, doMsgs, 01, 2);
AddEncounter(player, type, doMsgs, 02, 3);
AddEncounter(player, type, doMsgs, 03, 25);
AddEncounter(player, type, doMsgs, 05, 26);
AddEncounter(player, type, doMsgs, 06, 28);
}
}
protected override void FnEvent0E(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
if ((GetFlag(player, type, doMsgs, FlagTypeTile, GRAVE_ZAP) == 0)) {
DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) / 4);
ShowText(player, type, doMsgs, "A clumsy fall into an open grave injures you.");
SetFlag(player, type, doMsgs, FlagTypeTile, GRAVE_ZAP, 1);
}
}
protected override void FnEvent0F(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "Scattered bones are all that's left of looted tombs.");
}
protected override void FnEvent10(TwPlayerServer player, MapEventType type, bool doMsgs) {
WallClear(player, type, doMsgs);
}
protected override void FnEvent11(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (UsedItem(player, type, ref doMsgs, BLUELOCKPICK, BLUELOCKPICK) || UsedItem(player, type, ref doMsgs, HELMOFGUILE, HELMOFGUILE) || HasUsedSkill(player, type, ref doMsgs, LOCKPICK_SKILL) >= 11) {
ShowText(player, type, doMsgs, "You have successfully unlocked the tomb door.");
DoorHere(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
else {
WallBlock(player, type, doMsgs);
DoorHere(player, type, doMsgs);
ShowText(player, type, doMsgs, "The door to the old tomb is locked.");
}
}
protected override void FnEvent12(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowPortrait(player, type, doMsgs, FOUNTAIN);
if (GetGuild(player, type, doMsgs) == BARBARIAN || GetGuild(player, type, doMsgs) == KNIGHT || GetGuild(player, type, doMsgs) == THIEF) {
if ((GetSkill(player, type, doMsgs, FURTIVENESS_SKILL) == 0)) {
SetSkill(player, type, doMsgs, FURTIVENESS_SKILL, 1);
ShowText(player, type, doMsgs, "Skeletal Fountain gives you the Furtiveness Skill.");
}
else {
ShowText(player, type, doMsgs, "The waters of Skeletal Fountain quench your thirst.");
}
}
else if (GetGuild(player, type, doMsgs) == RANGER || GetGuild(player, type, doMsgs) == WIZARD) {
if ((GetSkill(player, type, doMsgs, PICKPOCKET_SKILL) == 0)) {
SetSkill(player, type, doMsgs, PICKPOCKET_SKILL, 1);
ShowText(player, type, doMsgs, "Skeletal Fountain gives you the Pickpocket Skill.");
}
else {
ShowText(player, type, doMsgs, "The waters of Skeletal Fountain quench your thirst.");
}
}
else if (GetGuild(player, type, doMsgs) == CLERIC) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.REFRESHCLERIC) == 0)) {
GiveSpell(player, type, doMsgs, REFRESH_SPELL, 1);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.REFRESHCLERIC, 1);
ShowText(player, type, doMsgs, "Skeletal Fountain gives you the power to refresh your party.");
}
else {
ShowText(player, type, doMsgs, "The waters of Skeletal Fountain quench your thirst.");
}
}
}
protected override void FnEvent13(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "The howling wind uproots you and carries you off.");
TeleportParty(player, type, doMsgs, 5, 3, 202, Direction.North);
}
protected override void FnEvent14(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
int i = 0;
if ((GetFlag(player, type, doMsgs, FlagTypeTile, GRAVE_ZAP) == 0)) {
ShowText(player, type, doMsgs, "Graverobbers, hearing your approach, ambush you. Sharp steel slices across your torso!");
if (GetHealthCurrent(player, type, doMsgs) > 1000) {
DoDamage(player, type, doMsgs, GetHealthCurrent(player, type, doMsgs) - 500);
SetFlag(player, type, doMsgs, FlagTypeTile, GRAVE_ZAP, 1);
}
}
switch (GetPartyCount(player, type, doMsgs)) {
case 1:
for (i = 1; i <= 3; i++) {
AddEncounter(player, type, doMsgs, i, 23);
}
break;
default:
for (i = 1; i <= 6; i++) {
AddEncounter(player, type, doMsgs, i, 24);
}
break;
}
}
protected override void FnEvent15(TwPlayerServer player, MapEventType type, bool doMsgs) {
DisableAutomaps(player, type, doMsgs);
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT) == 1) {
ShowText(player, type, doMsgs, "Searching the musty tomb unearths a few items concealed behind some rubble.");
ShowText(player, type, doMsgs, "You are rewarded for your insight.");
if (GetGuild(player, type, doMsgs) == WIZARD || GetGuild(player, type, doMsgs) == CLERIC) {
ModifyExperience(player, type, doMsgs, 15000);
GiveItem(player, type, doMsgs, DIVININGROD);
GiveItem(player, type, doMsgs, PLATINUMBAR);
GiveItem(player, type, doMsgs, HEALALLPOTION);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT, 2);
}
else if (GetGuild(player, type, doMsgs) == THIEF || GetGuild(player, type, doMsgs) == RANGER) {
ModifyExperience(player, type, doMsgs, 15000);
GiveItem(player, type, doMsgs, LANCEOFDARKNESS);
GiveItem(player, type, doMsgs, PLATINUMBAR);
GiveItem(player, type, doMsgs, SYMBOLOFDEATH);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT, 2);
}
else if (GetGuild(player, type, doMsgs) == BARBARIAN || GetGuild(player, type, doMsgs) == KNIGHT) {
ModifyExperience(player, type, doMsgs, 15000);
GiveItem(player, type, doMsgs, MERCURYAXE);
GiveItem(player, type, doMsgs, PLATINUMBAR);
GiveItem(player, type, doMsgs, SOVEREIGNSCROLL);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT, 2);
}
}
else {
ShowText(player, type, doMsgs, "The tomb appears to be a good hiding place, but your search this time is futile.");
}
}
protected override void FnEvent16(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, LUMINOUSLANTERN)) {
ShowText(player, type, doMsgs, "The torch flares, lighting your lantern. You catch a brief glimpse of the graveyard before the wind douses your flame.");
}
else {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "The torch does not cast enough illumination to light your path, nor can it be removed.");
ShowText(player, type, doMsgs, "A portable source of light would be particularly useful in the Graveyard.");
}
}
protected override void FnEvent17(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "You become dizzy and sense that you are no longer inside the tomb.");
TeleportParty(player, type, doMsgs, 5, 3, 69, Direction.East);
}
protected override void FnEvent18(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You stumble upon grave robbers ransacking a tomb.");
if (HasItem(player, type, doMsgs, BOWOFFLAMES)) {
SetTreasure(player, type, doMsgs, SILVERBAR, READTRACKSTALISMAN, 0, 0, 0, 1500);
}
else {
SetTreasure(player, type, doMsgs, SILVERBAR, BOWOFFLAMES, BLOODSHIELD, 0, 0, 2500);
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 24);
AddEncounter(player, type, doMsgs, 02, 39);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 23);
AddEncounter(player, type, doMsgs, 02, 24);
AddEncounter(player, type, doMsgs, 03, 39);
}
else {
AddEncounter(player, type, doMsgs, 01, 31);
AddEncounter(player, type, doMsgs, 02, 35);
AddEncounter(player, type, doMsgs, 03, 23);
AddEncounter(player, type, doMsgs, 05, 24);
AddEncounter(player, type, doMsgs, 06, 27);
}
}
protected override void FnEvent19(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You encounter scavengers.");
if (HasItem(player, type, doMsgs, SCROLLOFDEATH)) {
SetTreasure(player, type, doMsgs, SILVERBAR, SHAMANSCROLL, 0, 0, 0, 1000);
}
else {
SetTreasure(player, type, doMsgs, SILVERBAR, SCROLLOFDEATH, SCROLLOFSAFETY, 0, 0, 2000);
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 16);
AddEncounter(player, type, doMsgs, 02, 29);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 15);
AddEncounter(player, type, doMsgs, 02, 18);
AddEncounter(player, type, doMsgs, 05, 19);
}
else {
AddEncounter(player, type, doMsgs, 01, 15);
AddEncounter(player, type, doMsgs, 02, 18);
AddEncounter(player, type, doMsgs, 03, 30);
AddEncounter(player, type, doMsgs, 04, 30);
AddEncounter(player, type, doMsgs, 06, 33);
}
}
protected override void FnEvent1A(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "The worn tombstone bears the inscription, 'Wilthorg Zerium.'");
}
protected override void FnEvent1B(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "You stumble upon the remains of Yartor Megilthorn.");
}
protected override void FnEvent1C(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "The inscription on the tombstone has been eroded beyond recognition by the elements.");
}
protected override void FnEvent1D(TwPlayerServer player, MapEventType type, bool doMsgs) {
int mn1 = 0;
int mn2 = 0;
int i = 0;
int pfv = 0;
pfv = GetFlag(player, type, doMsgs, FlagTypeParty, RANDOMMONST);
switch (pfv) {
case 1:
mn1 = 1;
mn2 = 5;
break;
case 2:
mn1 = 15;
mn2 = 18;
break;
case 3:
mn1 = 7;
mn2 = 8;
break;
default:
mn1 = 21;
mn2 = 24;
break;
}
switch (GetPartyCount(player, type, doMsgs)) {
case 1:
AddEncounter(player, type, doMsgs, 01, mn1);
break;
case 2:
AddEncounter(player, type, doMsgs, 01, mn1);
AddEncounter(player, type, doMsgs, 02, mn2);
break;
default:
for (i = 1; i <= 2; i++) {
AddEncounter(player, type, doMsgs, i, mn1);
}
for (i = 5; i <= 6; i++) {
AddEncounter(player, type, doMsgs, i, mn2);
}
break;
}
}
protected override void FnEvent1E(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, LUMINOUSLANTERN)) {
ShowText(player, type, doMsgs, "The magical aura emanating from the tomb lights your lantern for a brief moment.");
}
else {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "You overhear a group of adventurers discussing the strange flickering of their lantern in the tomb.");
}
}
protected override void FnEvent1F(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The volcanic activity has weakened some of the walls and tomb doors in this area.");
FnEvent02(player, type, doMsgs);
}
protected override void FnEvent20(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "A ghostly voice whispers, 'To the South you will meet four Spirits. Each will offer you a gift.");
ShowText(player, type, doMsgs, "Choose wisely for you will be able to accept only one gift. Once your decision is made, enter the door of your choice.'");
}
protected override void FnEvent21(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "The sorrowful wind whispers -");
ShowText(player, type, doMsgs, "'The Spirit to the East offers the gift of increased Strength.'");
}
protected override void FnEvent22(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowPortrait(player, type, doMsgs, WRAITH);
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT) == 1 || GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT) == 2) {
ShowText(player, type, doMsgs, "You've already chosen your gift.");
}
else {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT, 1);
ShowText(player, type, doMsgs, "The Spirit of a Warrior endows you with increased Strength.");
ModAttribute(player, type, doMsgs, STRENGTH, 2);
}
}
protected override void FnEvent23(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
if (GetPartyCount(player, type, doMsgs) == 1) {
ShowText(player, type, doMsgs, "You may rejoin your party.");
}
else {
TeleportParty(player, type, doMsgs, 5, 3, 192, Direction.North);
}
}
protected override void FnEvent24(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (UsedItem(player, type, ref doMsgs, LUMINOUSLANTERN, LUMINOUSLANTERN)) {
WallClear(player, type, doMsgs);
DoorHere(player, type, doMsgs);
ShowText(player, type, doMsgs, "The Luminous Lantern glows feebly for a few moments.");
ShowText(player, type, doMsgs, "You barely detect a rusty bolt that locks the mildewed door.");
ShowText(player, type, doMsgs, "A moment later, the bolt is thrown and the door is open.");
}
else {
WallBlock(player, type, doMsgs);
ShowText(player, type, doMsgs, "A locked door bars your way. Perhaps if you had a bit of light you could determine the cause.");
}
}
protected override void FnEvent25(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "A large sign warns -");
ShowText(player, type, doMsgs, "'DO NOT ENTER unless you have all four map pieces or have completed the Queen's map quest. Proceed through this door alone and rejoin your party on the other side.'");
if (GetPartyCount(player, type, doMsgs) == 1) {
if ((HasItem(player, type, doMsgs, PARCHMENTMAP) && HasItem(player, type, doMsgs, SNAKESKINMAP) && HasItem(player, type, doMsgs, LEATHERMAP) && HasItem(player, type, doMsgs, SLATEMAP)) || (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PATHWAYDONE) == 1)) {
WallClear(player, type, doMsgs);
DoorHere(player, type, doMsgs);
}
}
else {
WallBlock(player, type, doMsgs);
ShowText(player, type, doMsgs, "Your entry is barred.");
}
}
protected override void FnEvent26(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, GREMLINCLERIC);
ShowText(player, type, doMsgs, "'Word has it that pieces of the map are scattered throughout the levels of the dungeon.'");
}
protected override void FnEvent27(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "A haunted voice quavers -");
ShowText(player, type, doMsgs, "'The Spirit to the East will offer the gift of increased Defense.'");
}
protected override void FnEvent28(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowPortrait(player, type, doMsgs, WRAITH);
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT) == 1 || GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT) == 2) {
ShowText(player, type, doMsgs, "You've already chosen your gift.");
}
else {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT, 1);
ShowText(player, type, doMsgs, "The Spirit of a Guard endows you with increased Defense.");
ModAttribute(player, type, doMsgs, DEFENSE, 2);
}
}
protected override void FnEvent29(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, DWARFKNIGHT);
ShowText(player, type, doMsgs, "'Trust the wrong thief with your goods and you may end up here permanently.'");
}
protected override void FnEvent2A(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "A distant wraith wails -");
ShowText(player, type, doMsgs, "'The Spirit to the East blesses with the gift of increased Agility.'");
}
protected override void FnEvent2B(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowPortrait(player, type, doMsgs, WRAITH);
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT) == 1 || GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT) == 2) {
ShowText(player, type, doMsgs, "You've already chosen your gift.");
}
else {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT, 1);
ShowText(player, type, doMsgs, "The Spirit of an Athlete endows you with increased Agility.");
ModAttribute(player, type, doMsgs, AGILITY, 2);
}
}
protected override void FnEvent2C(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "The ground gives way and you slide into The Crypt.");
TeleportParty(player, type, doMsgs, 6, 1, 221, Direction.South);
}
protected override void FnEvent2D(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, SKELETONKEY)) {
ShowText(player, type, doMsgs, "As you approach the portal to the Cartography Shop, your Skeleton Key tumbles to the ground and is lost in the mud.");
RemoveItem(player, type, doMsgs, SKELETONKEY);
TeleportParty(player, type, doMsgs, 5, 2, 247, Direction.North);
}
else {
ShowText(player, type, doMsgs, "The portal marks the entrance to the Cartography Shop.");
TeleportParty(player, type, doMsgs, 5, 2, 247, Direction.North);
}
}
protected override void FnEvent2E(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowText(player, type, doMsgs, "A nearby owl hoots -");
ShowText(player, type, doMsgs, "'The Spirit to the East can give you a gift that increases Initiative.'");
}
protected override void FnEvent2F(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowPortrait(player, type, doMsgs, WRAITH);
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT) == 1 || GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT) == 2) {
ShowText(player, type, doMsgs, "You've already chosen your gift.");
}
else {
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT, 1);
ShowText(player, type, doMsgs, "The Spirit of a Cavalier endows you with increased Initiative.");
ModAttribute(player, type, doMsgs, INITIATIVE, 2);
}
}
protected override void FnEvent30(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You blink as you see a shadowy figure seemingly walking through a solid wall.");
FnEvent02(player, type, doMsgs);
}
protected override void FnEvent31(TwPlayerServer player, MapEventType type, bool doMsgs) {
FnEvent02(player, type, doMsgs);
ShowPortrait(player, type, doMsgs, FOUNTAIN);
ModifyHealth(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
ShowText(player, type, doMsgs, "The waters of Twilight Fountain heal your wounds.");
}
protected override void FnEvent32(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 38);
AddEncounter(player, type, doMsgs, 05, 39);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 20);
AddEncounter(player, type, doMsgs, 02, 21);
AddEncounter(player, type, doMsgs, 05, 38);
}
else {
AddEncounter(player, type, doMsgs, 01, 36);
AddEncounter(player, type, doMsgs, 02, 40);
AddEncounter(player, type, doMsgs, 03, 38);
AddEncounter(player, type, doMsgs, 04, 38);
}
}
protected override void FnEvent33(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 23);
AddEncounter(player, type, doMsgs, 05, 29);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 24);
AddEncounter(player, type, doMsgs, 02, 24);
AddEncounter(player, type, doMsgs, 04, 18);
}
else {
AddEncounter(player, type, doMsgs, 01, 23);
AddEncounter(player, type, doMsgs, 02, 40);
AddEncounter(player, type, doMsgs, 03, 18);
AddEncounter(player, type, doMsgs, 04, 16);
}
}
protected override void FnEvent34(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 1);
AddEncounter(player, type, doMsgs, 02, 34);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 3);
AddEncounter(player, type, doMsgs, 02, 5);
}
else {
AddEncounter(player, type, doMsgs, 01, 3);
AddEncounter(player, type, doMsgs, 02, 4);
AddEncounter(player, type, doMsgs, 05, 26);
AddEncounter(player, type, doMsgs, 06, 26);
}
}
protected override void FnEvent35(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1 || GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 6);
AddEncounter(player, type, doMsgs, 02, 12);
}
else {
AddEncounter(player, type, doMsgs, 01, 7);
AddEncounter(player, type, doMsgs, 02, 6);
AddEncounter(player, type, doMsgs, 03, 13);
AddEncounter(player, type, doMsgs, 04, 10);
}
}
protected override void FnEvent36(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 20);
AddEncounter(player, type, doMsgs, 02, 39);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 24);
AddEncounter(player, type, doMsgs, 02, 23);
AddEncounter(player, type, doMsgs, 05, 39);
}
else {
AddEncounter(player, type, doMsgs, 01, 24);
AddEncounter(player, type, doMsgs, 02, 23);
AddEncounter(player, type, doMsgs, 03, 36);
AddEncounter(player, type, doMsgs, 04, 20);
AddEncounter(player, type, doMsgs, 05, 32);
}
}
protected override void FnEvent37(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You hear the sound of looting somewhere nearby.");
}
private void WallClear(TwPlayerServer player, MapEventType type, bool doMsgs) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
private void WallBlock(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
private void DoorHere(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
protected override void FnEvent38(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT) == 1) {
ShowText(player, type, doMsgs, "A luminescent message magically appears on the door.");
ShowText(player, type, doMsgs, "'You have discovered the secret of the spirits and have received their blessing! Continue your search, champion. The graveyard offers passages to the clever.'");
}
}
protected override void FnEvent39(TwPlayerServer player, MapEventType type, bool doMsgs) {
if ((GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SPIRIT) == 0)) {
ShowPortrait(player, type, doMsgs, TROLLKNIGHT);
ShowText(player, type, doMsgs, "'Ah, I see you haven't been blessed by the spirits yet!");
ShowText(player, type, doMsgs, "Walk cautiously, my friend. The graveyard is as dangerous as it is rewarding. The benevolent spirits await thee!'");
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Filename: SIPTLSChannel.cs
//
// Description: SIP transport for TLS over TCP.
//
// History:
// 13 Mar 2009 Aaron Clauson Created.
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2006 Aaron Clauson ([email protected]), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that
// the following conditions are met:
//
// 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 SIP Sorcery PTY LTD.
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Security;
using System.Security.Authentication;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using SIPSorcery.Sys;
using log4net;
namespace SIPSorcery.SIP
{
public class SIPTLSChannel : SIPChannel
{
private const string ACCEPT_THREAD_NAME = "siptls-";
private const string PRUNE_THREAD_NAME = "siptlsprune-";
private const int MAX_TLS_CONNECTIONS = 1000; // Maximum number of connections for the TLS listener.
//private const int MAX_TLS_CONNECTIONS_PER_IPADDRESS = 10; // Maximum number of connections allowed for a single remote IP address.
private static int MaxSIPTCPMessageSize = SIPConstants.SIP_MAXIMUM_RECEIVE_LENGTH;
private TcpListener m_tlsServerListener;
//private bool m_closed = false;
private Dictionary<string, SIPConnection> m_connectedSockets = new Dictionary<string, SIPConnection>();
private List<string> m_connectingSockets = new List<string>(); // List of connecting sockets to avoid SIP re-transmits initiating multiple connect attempts.
//private string m_certificatePath;
private X509Certificate2 m_serverCertificate;
private new ILog logger = AppState.GetLogger("siptls-channel");
public SIPTLSChannel(X509Certificate2 serverCertificate, IPEndPoint endPoint)
{
if (serverCertificate == null)
{
throw new ArgumentNullException("serverCertificate", "An X509 certificate must be supplied for a SIP TLS channel.");
}
if (endPoint == null)
{
throw new ArgumentNullException("endPoint", "An IP end point must be supplied for a SIP TLS channel.");
}
m_localSIPEndPoint = new SIPEndPoint(SIPProtocolsEnum.tls, endPoint);
LocalTCPSockets.Add(endPoint.ToString());
m_isReliable = true;
m_isTLS = true;
//m_certificatePath = certificateFileName;
///base.Name = "s" + Crypto.GetRandomInt(4);
m_serverCertificate = serverCertificate;
Initialise();
}
private void Initialise()
{
try
{
m_tlsServerListener = new TcpListener(m_localSIPEndPoint.GetIPEndPoint());
m_tlsServerListener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
m_tlsServerListener.Start(MAX_TLS_CONNECTIONS);
ThreadPool.QueueUserWorkItem(delegate { AcceptConnections(ACCEPT_THREAD_NAME + m_localSIPEndPoint.Port); });
ThreadPool.QueueUserWorkItem(delegate { PruneConnections(PRUNE_THREAD_NAME + m_localSIPEndPoint.Port); });
logger.Debug("SIP TLS Channel listener created " + m_localSIPEndPoint.GetIPEndPoint() + ".");
}
catch (Exception excp)
{
logger.Error("Exception SIPTLSChannel Initialise. " + excp);
throw;
}
}
private void AcceptConnections(string threadName)
{
try
{
Thread.CurrentThread.Name = threadName;
logger.Debug("SIPTLSChannel socket on " + m_localSIPEndPoint + " accept connections thread started.");
while (!Closed)
{
try
{
TcpClient tcpClient = m_tlsServerListener.AcceptTcpClient();
tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPEndPoint remoteEndPoint = (IPEndPoint)tcpClient.Client.RemoteEndPoint;
logger.Debug("SIP TLS Channel connection accepted from " + remoteEndPoint + ".");
SslStream sslStream = new SslStream(tcpClient.GetStream(), false);
SIPConnection sipTLSConnection = new SIPConnection(this, sslStream, remoteEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Listener);
sslStream.BeginAuthenticateAsServer(m_serverCertificate, EndAuthenticateAsServer, sipTLSConnection);
//sslStream.AuthenticateAsServer(m_serverCertificate, false, SslProtocols.Tls, false);
//// Display the properties and settings for the authenticated stream.
////DisplaySecurityLevel(sslStream);
////DisplaySecurityServices(sslStream);
////DisplayCertificateInformation(sslStream);
////DisplayStreamProperties(sslStream);
//// Set timeouts for the read and write to 5 seconds.
//sslStream.ReadTimeout = 5000;
//sslStream.WriteTimeout = 5000;
////SIPConnection sipTLSConnection = new SIPConnection(this, sslStream, remoteEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Listener);
//m_connectedSockets.Add(remoteEndPoint.ToString(), sipTLSConnection);
//sipTLSConnection.SIPSocketDisconnected += SIPTLSSocketDisconnected;
//sipTLSConnection.SIPMessageReceived += SIPTLSMessageReceived;
////byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
//sipTLSConnection.SIPStream.BeginRead(sipTLSConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), sipTLSConnection);
}
catch (Exception e)
{
logger.Error("SIPTLSChannel Accept Connection Exception. " + e);
//sslStream.Close();
//tcpClient.Close();
}
}
logger.Debug("SIPTLSChannel socket on " + m_localSIPEndPoint + " listening halted.");
}
catch (Exception excp)
{
logger.Error("Exception SIPTLSChannel Listen. " + excp);
//throw excp;
}
}
public void EndAuthenticateAsServer(IAsyncResult ar)
{
try
{
SIPConnection sipTLSConnection = (SIPConnection)ar.AsyncState;
SslStream sslStream = (SslStream)sipTLSConnection.SIPStream;
sslStream.EndAuthenticateAsServer(ar);
// Set timeouts for the read and write to 5 seconds.
sslStream.ReadTimeout = 5000;
sslStream.WriteTimeout = 5000;
m_connectedSockets.Add(sipTLSConnection.RemoteEndPoint.ToString(), sipTLSConnection);
sipTLSConnection.SIPSocketDisconnected += SIPTLSSocketDisconnected;
sipTLSConnection.SIPMessageReceived += SIPTLSMessageReceived;
//byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
sipTLSConnection.SIPStream.BeginRead(sipTLSConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), sipTLSConnection);
}
catch (Exception excp)
{
logger.Error("Exception SIPTLSChannel EndAuthenticateAsServer. " + excp);
//throw excp;
}
}
public void ReceiveCallback(IAsyncResult ar)
{
SIPConnection sipTLSConnection = (SIPConnection)ar.AsyncState;
if (sipTLSConnection != null && sipTLSConnection.SIPStream != null && sipTLSConnection.SIPStream.CanRead)
{
try
{
int bytesRead = sipTLSConnection.SIPStream.EndRead(ar);
if (sipTLSConnection.SocketReadCompleted(bytesRead))
{
sipTLSConnection.SIPStream.BeginRead(sipTLSConnection.SocketBuffer, sipTLSConnection.SocketBufferEndPosition, MaxSIPTCPMessageSize - sipTLSConnection.SocketBufferEndPosition, new AsyncCallback(ReceiveCallback), sipTLSConnection);
}
}
catch (SocketException sockExcp) // Occurs if the remote end gets disconnected.
{
logger.Warn("SocketException SIPTLSChannel ReceiveCallback. " + sockExcp);
}
catch (Exception excp)
{
logger.Warn("Exception SIPTLSChannel ReceiveCallback. " + excp);
SIPTLSSocketDisconnected(sipTLSConnection.RemoteEndPoint);
}
}
}
public override void Send(IPEndPoint destinationEndPoint, string message)
{
byte[] messageBuffer = Encoding.UTF8.GetBytes(message);
Send(destinationEndPoint, messageBuffer);
}
public override void Send(IPEndPoint dstEndPoint, byte[] buffer)
{
Send(dstEndPoint, buffer, null);
}
public override void Send(IPEndPoint dstEndPoint, byte[] buffer, string serverCertificateName)
{
try
{
if (buffer == null)
{
throw new ApplicationException("An empty buffer was specified to Send in SIPTLSChannel.");
}
else if (LocalTCPSockets.Contains(dstEndPoint.ToString()))
{
logger.Error("SIPTLSChannel blocked Send to " + dstEndPoint.ToString() + " as it was identified as a locally hosted TCP socket.\r\n" + Encoding.UTF8.GetString(buffer));
throw new ApplicationException("A Send call was made in SIPTLSChannel to send to another local TCP socket.");
}
else
{
bool sent = false;
bool existingConnection = false;
// Lookup a client socket that is connected to the destination.
//m_sipConn(buffer, buffer.Length, destinationEndPoint);
if (m_connectedSockets.ContainsKey(dstEndPoint.ToString()))
{
existingConnection = true;
SIPConnection sipTLSClient = m_connectedSockets[dstEndPoint.ToString()];
try
{
if (sipTLSClient.SIPStream != null && sipTLSClient.SIPStream.CanWrite)
{
sipTLSClient.SIPStream.BeginWrite(buffer, 0, buffer.Length, new AsyncCallback(EndSend), sipTLSClient);
sent = true;
sipTLSClient.LastTransmission = DateTime.Now;
}
else
{
logger.Warn("A SIPTLSChannel write operation to " + dstEndPoint + " was dropped as the stream was null or could not be written to.");
}
}
catch (SocketException)
{
logger.Warn("Could not send to TLS socket " + dstEndPoint + ", closing and removing.");
sipTLSClient.SIPStream.Close();
m_connectedSockets.Remove(dstEndPoint.ToString());
}
}
if (!sent && !existingConnection)
{
if (serverCertificateName.IsNullOrBlank())
{
throw new ApplicationException("The SIP TLS Channel must be provided with the name of the expected server certificate, please use alternative method.");
}
if (!m_connectingSockets.Contains(dstEndPoint.ToString()))
{
logger.Debug("Attempting to establish TLS connection to " + dstEndPoint + ".");
TcpClient tcpClient = new TcpClient();
tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
tcpClient.Client.Bind(m_localSIPEndPoint.GetIPEndPoint());
m_connectingSockets.Add(dstEndPoint.ToString());
tcpClient.BeginConnect(dstEndPoint.Address, dstEndPoint.Port, EndConnect, new object[] { tcpClient, dstEndPoint, buffer, serverCertificateName });
}
else
{
logger.Warn("Could not send SIP packet to TLS " + dstEndPoint + " and another connection was already in progress so dropping message.");
}
}
}
}
catch (Exception excp)
{
logger.Error("Exception (" + excp.GetType().ToString() + ") SIPTLSChannel Send (sendto=>" + dstEndPoint + "). " + excp);
throw excp;
}
}
private void EndSend(IAsyncResult ar)
{
try
{
SIPConnection sipConnection = (SIPConnection)ar.AsyncState;
sipConnection.SIPStream.EndWrite(ar);
}
catch (Exception excp)
{
logger.Error("Exception EndSend. " + excp);
}
}
private void EndConnect(IAsyncResult ar)
{
object[] stateObj = (object[])ar.AsyncState;
TcpClient tcpClient = (TcpClient)stateObj[0];
IPEndPoint dstEndPoint = (IPEndPoint)stateObj[1];
byte[] buffer = (byte[])stateObj[2];
string serverCN = (string)stateObj[3];
try
{
m_connectingSockets.Remove(dstEndPoint.ToString());
tcpClient.EndConnect(ar);
SslStream sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
//DisplayCertificateInformation(sslStream);
SIPConnection callerConnection = new SIPConnection(this, sslStream, dstEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Caller);
sslStream.BeginAuthenticateAsClient(serverCN, EndAuthenticateAsClient, new object[] { tcpClient, dstEndPoint, buffer, callerConnection });
//sslStream.AuthenticateAsClient(serverCN);
//if (tcpClient != null && tcpClient.Connected)
//{
// SIPConnection callerConnection = new SIPConnection(this, sslStream, dstEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Caller);
// m_connectedSockets.Add(dstEndPoint.ToString(), callerConnection);
// callerConnection.SIPSocketDisconnected += SIPTLSSocketDisconnected;
// callerConnection.SIPMessageReceived += SIPTLSMessageReceived;
// //byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
// callerConnection.SIPStream.BeginRead(callerConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), callerConnection);
// logger.Debug("Established TLS connection to " + dstEndPoint + ".");
// callerConnection.SIPStream.BeginWrite(buffer, 0, buffer.Length, EndSend, callerConnection);
//}
//else
//{
// logger.Warn("Could not establish TLS connection to " + dstEndPoint + ".");
//}
}
catch (Exception excp)
{
logger.Error("Exception SIPTLSChannel EndConnect. " + excp);
if(tcpClient != null)
{
try
{
tcpClient.Close();
}
catch(Exception closeExcp)
{
logger.Warn("Exception SIPTLSChannel EndConnect Close TCP Client. " + closeExcp);
}
}
}
}
private void EndAuthenticateAsClient(IAsyncResult ar)
{
try
{
object[] stateObj = (object[])ar.AsyncState;
TcpClient tcpClient = (TcpClient)stateObj[0];
IPEndPoint dstEndPoint = (IPEndPoint)stateObj[1];
byte[] buffer = (byte[])stateObj[2];
SIPConnection callerConnection = (SIPConnection)stateObj[3];
SslStream sslStream = (SslStream)callerConnection.SIPStream;
sslStream.EndAuthenticateAsClient(ar);
if (tcpClient != null && tcpClient.Connected)
{
//SIPConnection callerConnection = new SIPConnection(this, sslStream, dstEndPoint, SIPProtocolsEnum.tls, SIPConnectionsEnum.Caller);
m_connectedSockets.Add(callerConnection.RemoteEndPoint.ToString(), callerConnection);
callerConnection.SIPSocketDisconnected += SIPTLSSocketDisconnected;
callerConnection.SIPMessageReceived += SIPTLSMessageReceived;
//byte[] receiveBuffer = new byte[MaxSIPTCPMessageSize];
callerConnection.SIPStream.BeginRead(callerConnection.SocketBuffer, 0, MaxSIPTCPMessageSize, new AsyncCallback(ReceiveCallback), callerConnection);
logger.Debug("Established TLS connection to " + callerConnection.RemoteEndPoint + ".");
callerConnection.SIPStream.BeginWrite(buffer, 0, buffer.Length, EndSend, callerConnection);
}
else
{
logger.Warn("Could not establish TLS connection to " + callerConnection.RemoteEndPoint + ".");
}
}
catch (Exception excp)
{
logger.Error("Exception SIPTLSChannel EndAuthenticateAsClient. " + excp);
}
}
protected override Dictionary<string, SIPConnection> GetConnectionsList()
{
return m_connectedSockets;
}
public override bool IsConnectionEstablished(IPEndPoint remoteEndPoint)
{
lock (m_connectedSockets)
{
return m_connectedSockets.ContainsKey(remoteEndPoint.ToString());
}
}
private void SIPTLSSocketDisconnected(IPEndPoint remoteEndPoint)
{
try
{
logger.Debug("TLS socket from " + remoteEndPoint + " disconnected.");
lock (m_connectedSockets)
{
m_connectedSockets.Remove(remoteEndPoint.ToString());
}
m_connectingSockets.Remove(remoteEndPoint.ToString());
}
catch (Exception excp)
{
logger.Error("Exception SIPTLSClientDisconnected. " + excp);
}
}
private void SIPTLSMessageReceived(SIPChannel channel, SIPEndPoint remoteEndPoint, byte[] buffer)
{
if (SIPMessageReceived != null)
{
SIPMessageReceived(channel, remoteEndPoint, buffer);
}
}
private X509Certificate GetServerCert()
{
//X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
X509Store store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
X509CertificateCollection cert = store.Certificates.Find(X509FindType.FindBySubjectName, "10.0.0.100", true);
return cert[0];
}
private void DisplayCertificateChain(X509Certificate2 certificate)
{
X509Chain ch = new X509Chain();
ch.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
ch.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
ch.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
ch.Build(certificate);
Console.WriteLine("Chain Information");
Console.WriteLine("Chain revocation flag: {0}", ch.ChainPolicy.RevocationFlag);
Console.WriteLine("Chain revocation mode: {0}", ch.ChainPolicy.RevocationMode);
Console.WriteLine("Chain verification flag: {0}", ch.ChainPolicy.VerificationFlags);
Console.WriteLine("Chain verification time: {0}", ch.ChainPolicy.VerificationTime);
Console.WriteLine("Chain status length: {0}", ch.ChainStatus.Length);
Console.WriteLine("Chain application policy count: {0}", ch.ChainPolicy.ApplicationPolicy.Count);
Console.WriteLine("Chain certificate policy count: {0} {1}", ch.ChainPolicy.CertificatePolicy.Count, Environment.NewLine);
//Output chain element information.
Console.WriteLine("Chain Element Information");
Console.WriteLine("Number of chain elements: {0}", ch.ChainElements.Count);
Console.WriteLine("Chain elements synchronized? {0} {1}", ch.ChainElements.IsSynchronized, Environment.NewLine);
foreach (X509ChainElement element in ch.ChainElements)
{
Console.WriteLine("Element issuer name: {0}", element.Certificate.Issuer);
Console.WriteLine("Element certificate valid until: {0}", element.Certificate.NotAfter);
Console.WriteLine("Element certificate is valid: {0}", element.Certificate.Verify());
Console.WriteLine("Element error status length: {0}", element.ChainElementStatus.Length);
Console.WriteLine("Element information: {0}", element.Information);
Console.WriteLine("Number of element extensions: {0}{1}", element.Certificate.Extensions.Count, Environment.NewLine);
if (ch.ChainStatus.Length > 1)
{
for (int index = 0; index < element.ChainElementStatus.Length; index++)
{
Console.WriteLine(element.ChainElementStatus[index].Status);
Console.WriteLine(element.ChainElementStatus[index].StatusInformation);
}
}
}
}
private void DisplaySecurityLevel(SslStream stream)
{
logger.Debug(String.Format("Cipher: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength));
logger.Debug(String.Format("Hash: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength));
logger.Debug(String.Format("Key exchange: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength));
logger.Debug(String.Format("Protocol: {0}", stream.SslProtocol));
}
private void DisplaySecurityServices(SslStream stream)
{
logger.Debug(String.Format("Is authenticated: {0} as server? {1}", stream.IsAuthenticated, stream.IsServer));
logger.Debug(String.Format("IsSigned: {0}", stream.IsSigned));
logger.Debug(String.Format("Is Encrypted: {0}", stream.IsEncrypted));
}
private void DisplayStreamProperties(SslStream stream)
{
logger.Debug(String.Format("Can read: {0}, write {1}", stream.CanRead, stream.CanWrite));
logger.Debug(String.Format("Can timeout: {0}", stream.CanTimeout));
}
private void DisplayCertificateInformation(SslStream stream)
{
logger.Debug(String.Format("Certificate revocation list checked: {0}", stream.CheckCertRevocationStatus));
X509Certificate localCertificate = stream.LocalCertificate;
if (stream.LocalCertificate != null)
{
logger.Debug(String.Format("Local cert was issued to {0} and is valid from {1} until {2}.",
localCertificate.Subject,
localCertificate.GetEffectiveDateString(),
localCertificate.GetExpirationDateString()));
}
else
{
logger.Warn("Local certificate is null.");
}
// Display the properties of the client's certificate.
X509Certificate remoteCertificate = stream.RemoteCertificate;
if (stream.RemoteCertificate != null)
{
logger.Debug(String.Format("Remote cert was issued to {0} and is valid from {1} until {2}.",
remoteCertificate.Subject,
remoteCertificate.GetEffectiveDateString(),
remoteCertificate.GetExpirationDateString()));
}
else
{
logger.Warn("Remote certificate is null.");
}
}
private bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
else
{
logger.Warn(String.Format("Certificate error: {0}", sslPolicyErrors));
return true;
}
}
public override void Close()
{
logger.Debug("Closing SIP TLS Channel " + SIPChannelEndPoint + ".");
Closed = true;
try
{
m_tlsServerListener.Stop();
}
catch (Exception listenerCloseExcp)
{
logger.Warn("Exception SIPTLSChannel Close (shutting down listener). " + listenerCloseExcp.Message);
}
foreach (SIPConnection tcpConnection in m_connectedSockets.Values)
{
try
{
tcpConnection.SIPStream.Close();
}
catch (Exception connectionCloseExcp)
{
logger.Warn("Exception SIPTLSChannel Close (shutting down connection to " + tcpConnection.RemoteEndPoint + "). " + connectionCloseExcp.Message);
}
}
}
private void Dispose(bool disposing)
{
try
{
this.Close();
}
catch (Exception excp)
{
logger.Error("Exception Disposing SIPTLSChannel. " + excp.Message);
}
}
}
}
| |
// 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 AndNotInt16()
{
var test = new SimpleBinaryOpTest__AndNotInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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 (Avx.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__AndNotInt16
{
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(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
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<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, 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 Vector256<Int16> _fld1;
public Vector256<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AndNotInt16 testClass)
{
var result = Avx2.AndNot(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndNotInt16 testClass)
{
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
{
var result = Avx2.AndNot(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AndNotInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
}
public SimpleBinaryOpTest__AndNotInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.AndNot(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_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 = Avx2.AndNot(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_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 = Avx2.AndNot(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_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(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.AndNot), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector256<Int16>* pClsVar2 = &_clsVar2)
{
var result = Avx2.AndNot(
Avx.LoadVector256((Int16*)(pClsVar1)),
Avx.LoadVector256((Int16*)(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<Vector256<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Avx2.AndNot(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.AndNot(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.AndNot(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AndNotInt16();
var result = Avx2.AndNot(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__AndNotInt16();
fixed (Vector256<Int16>* pFld1 = &test._fld1)
fixed (Vector256<Int16>* pFld2 = &test._fld2)
{
var result = Avx2.AndNot(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.AndNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<Int16>* pFld1 = &_fld1)
fixed (Vector256<Int16>* pFld2 = &_fld2)
{
var result = Avx2.AndNot(
Avx.LoadVector256((Int16*)(pFld1)),
Avx.LoadVector256((Int16*)(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 = Avx2.AndNot(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 = Avx2.AndNot(
Avx.LoadVector256((Int16*)(&test._fld1)),
Avx.LoadVector256((Int16*)(&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(Vector256<Int16> op1, Vector256<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((short)(~left[0] & right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(~left[i] & right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.AndNot)}<Int16>(Vector256<Int16>, Vector256<Int16>): {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 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
namespace ZXing.OneD.RSS
{
/// <summary>
/// Decodes RSS-14, including truncated and stacked variants. See ISO/IEC 24724:2006.
/// </summary>
public sealed class RSS14Reader : AbstractRSSReader
{
private static readonly int[] OUTSIDE_EVEN_TOTAL_SUBSET = { 1, 10, 34, 70, 126 };
private static readonly int[] INSIDE_ODD_TOTAL_SUBSET = { 4, 20, 48, 81 };
private static readonly int[] OUTSIDE_GSUM = { 0, 161, 961, 2015, 2715 };
private static readonly int[] INSIDE_GSUM = { 0, 336, 1036, 1516 };
private static readonly int[] OUTSIDE_ODD_WIDEST = { 8, 6, 4, 3, 1 };
private static readonly int[] INSIDE_ODD_WIDEST = { 2, 4, 6, 8 };
private static readonly int[][] FINDER_PATTERNS = {
new[] {3, 8, 2, 1},
new[] {3, 5, 5, 1},
new[] {3, 3, 7, 1},
new[] {3, 1, 9, 1},
new[] {2, 7, 4, 1},
new[] {2, 5, 6, 1},
new[] {2, 3, 8, 1},
new[] {1, 5, 7, 1},
new[] {1, 3, 9, 1},
};
private readonly List<Pair> possibleLeftPairs;
private readonly List<Pair> possibleRightPairs;
/// <summary>
/// Initializes a new instance of the <see cref="RSS14Reader"/> class.
/// </summary>
public RSS14Reader()
{
possibleLeftPairs = new List<Pair>();
possibleRightPairs = new List<Pair>();
}
/// <summary>
/// <p>Attempts to decode a one-dimensional barcode format given a single row of
/// an image.</p>
/// </summary>
/// <param name="rowNumber">row number from top of the row</param>
/// <param name="row">the black/white pixel data of the row</param>
/// <param name="hints">decode hints</param>
/// <returns>
/// <see cref="Result"/>containing encoded string and start/end of barcode or null, if an error occurs or barcode cannot be found
/// </returns>
override public Result decodeRow(int rowNumber,
BitArray row,
IDictionary<DecodeHintType, object> hints)
{
Pair leftPair = decodePair(row, false, rowNumber, hints);
addOrTally(possibleLeftPairs, leftPair);
row.reverse();
Pair rightPair = decodePair(row, true, rowNumber, hints);
addOrTally(possibleRightPairs, rightPair);
row.reverse();
int lefSize = possibleLeftPairs.Count;
for (int i = 0; i < lefSize; i++)
{
Pair left = possibleLeftPairs[i];
if (left.Count > 1)
{
int rightSize = possibleRightPairs.Count;
for (int j = 0; j < rightSize; j++)
{
Pair right = possibleRightPairs[j];
if (right.Count > 1)
{
if (checkChecksum(left, right))
{
return constructResult(left, right);
}
}
}
}
}
return null;
}
private static void addOrTally(IList<Pair> possiblePairs, Pair pair)
{
if (pair == null)
{
return;
}
bool found = false;
foreach (Pair other in possiblePairs)
{
if (other.Value == pair.Value)
{
other.incrementCount();
found = true;
break;
}
}
if (!found)
{
possiblePairs.Add(pair);
}
}
/// <summary>
/// Resets this instance.
/// </summary>
public override void reset()
{
possibleLeftPairs.Clear();
possibleRightPairs.Clear();
}
private static Result constructResult(Pair leftPair, Pair rightPair)
{
long symbolValue = 4537077L * leftPair.Value + rightPair.Value;
String text = symbolValue.ToString();
StringBuilder buffer = new StringBuilder(14);
for (int i = 13 - text.Length; i > 0; i--)
{
buffer.Append('0');
}
buffer.Append(text);
int checkDigit = 0;
for (int i = 0; i < 13; i++)
{
int digit = buffer[i] - '0';
checkDigit += (i & 0x01) == 0 ? 3 * digit : digit;
}
checkDigit = 10 - (checkDigit % 10);
if (checkDigit == 10)
{
checkDigit = 0;
}
buffer.Append(checkDigit);
ResultPoint[] leftPoints = leftPair.FinderPattern.ResultPoints;
ResultPoint[] rightPoints = rightPair.FinderPattern.ResultPoints;
return new Result(
buffer.ToString(),
null,
new ResultPoint[] { leftPoints[0], leftPoints[1], rightPoints[0], rightPoints[1], },
BarcodeFormat.RSS_14);
}
private static bool checkChecksum(Pair leftPair, Pair rightPair)
{
//int leftFPValue = leftPair.FinderPattern.Value;
//int rightFPValue = rightPair.FinderPattern.Value;
//if ((leftFPValue == 0 && rightFPValue == 8) ||
// (leftFPValue == 8 && rightFPValue == 0))
//{
//}
int checkValue = (leftPair.ChecksumPortion + 16 * rightPair.ChecksumPortion) % 79;
int targetCheckValue =
9 * leftPair.FinderPattern.Value + rightPair.FinderPattern.Value;
if (targetCheckValue > 72)
{
targetCheckValue--;
}
if (targetCheckValue > 8)
{
targetCheckValue--;
}
return checkValue == targetCheckValue;
}
private Pair decodePair(BitArray row, bool right, int rowNumber, IDictionary<DecodeHintType, object> hints)
{
int[] startEnd = findFinderPattern(row, right);
if (startEnd == null)
return null;
FinderPattern pattern = parseFoundFinderPattern(row, rowNumber, right, startEnd);
if (pattern == null)
return null;
ResultPointCallback resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK) ? null :
(ResultPointCallback)hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
if (resultPointCallback != null)
{
float center = (startEnd[0] + startEnd[1]) / 2.0f;
if (right)
{
// row is actually reversed
center = row.Size - 1 - center;
}
resultPointCallback(new ResultPoint(center, rowNumber));
}
DataCharacter outside = decodeDataCharacter(row, pattern, true);
if (outside == null)
return null;
DataCharacter inside = decodeDataCharacter(row, pattern, false);
if (inside == null)
return null;
return new Pair(1597*outside.Value + inside.Value,
outside.ChecksumPortion + 4*inside.ChecksumPortion,
pattern);
}
private DataCharacter decodeDataCharacter(BitArray row, FinderPattern pattern, bool outsideChar)
{
int[] counters = getDataCharacterCounters();
counters[0] = 0;
counters[1] = 0;
counters[2] = 0;
counters[3] = 0;
counters[4] = 0;
counters[5] = 0;
counters[6] = 0;
counters[7] = 0;
if (outsideChar)
{
if (!recordPatternInReverse(row, pattern.StartEnd[0], counters))
return null;
}
else
{
if (!recordPattern(row, pattern.StartEnd[1] + 1, counters))
return null;
// reverse it
for (int i = 0, j = counters.Length - 1; i < j; i++, j--)
{
int temp = counters[i];
counters[i] = counters[j];
counters[j] = temp;
}
}
int numModules = outsideChar ? 16 : 15;
float elementWidth = (float)ZXing.Common.Detector.MathUtils.sum(counters) / (float)numModules;
int[] oddCounts = this.getOddCounts();
int[] evenCounts = this.getEvenCounts();
float[] oddRoundingErrors = this.getOddRoundingErrors();
float[] evenRoundingErrors = this.getEvenRoundingErrors();
for (int i = 0; i < counters.Length; i++)
{
float value = (float)counters[i] / elementWidth;
int rounded = (int)(value + 0.5f); // Round
if (rounded < 1)
{
rounded = 1;
}
else if (rounded > 8)
{
rounded = 8;
}
int offset = i >> 1;
if ((i & 0x01) == 0)
{
oddCounts[offset] = rounded;
oddRoundingErrors[offset] = value - rounded;
}
else
{
evenCounts[offset] = rounded;
evenRoundingErrors[offset] = value - rounded;
}
}
if (!adjustOddEvenCounts(outsideChar, numModules))
return null;
int oddSum = 0;
int oddChecksumPortion = 0;
for (int i = oddCounts.Length - 1; i >= 0; i--)
{
oddChecksumPortion *= 9;
oddChecksumPortion += oddCounts[i];
oddSum += oddCounts[i];
}
int evenChecksumPortion = 0;
int evenSum = 0;
for (int i = evenCounts.Length - 1; i >= 0; i--)
{
evenChecksumPortion *= 9;
evenChecksumPortion += evenCounts[i];
evenSum += evenCounts[i];
}
int checksumPortion = oddChecksumPortion + 3 * evenChecksumPortion;
if (outsideChar)
{
if ((oddSum & 0x01) != 0 || oddSum > 12 || oddSum < 4)
{
return null;
}
int group = (12 - oddSum) / 2;
int oddWidest = OUTSIDE_ODD_WIDEST[group];
int evenWidest = 9 - oddWidest;
int vOdd = RSSUtils.getRSSvalue(oddCounts, oddWidest, false);
int vEven = RSSUtils.getRSSvalue(evenCounts, evenWidest, true);
int tEven = OUTSIDE_EVEN_TOTAL_SUBSET[group];
int gSum = OUTSIDE_GSUM[group];
return new DataCharacter(vOdd * tEven + vEven + gSum, checksumPortion);
}
else
{
if ((evenSum & 0x01) != 0 || evenSum > 10 || evenSum < 4)
{
return null;
}
int group = (10 - evenSum) / 2;
int oddWidest = INSIDE_ODD_WIDEST[group];
int evenWidest = 9 - oddWidest;
int vOdd = RSSUtils.getRSSvalue(oddCounts, oddWidest, true);
int vEven = RSSUtils.getRSSvalue(evenCounts, evenWidest, false);
int tOdd = INSIDE_ODD_TOTAL_SUBSET[group];
int gSum = INSIDE_GSUM[group];
return new DataCharacter(vEven * tOdd + vOdd + gSum, checksumPortion);
}
}
private int[] findFinderPattern(BitArray row, bool rightFinderPattern)
{
int[] counters = getDecodeFinderCounters();
counters[0] = 0;
counters[1] = 0;
counters[2] = 0;
counters[3] = 0;
int width = row.Size;
bool isWhite = false;
int rowOffset = 0;
while (rowOffset < width)
{
isWhite = !row[rowOffset];
if (rightFinderPattern == isWhite)
{
// Will encounter white first when searching for right finder pattern
break;
}
rowOffset++;
}
int counterPosition = 0;
int patternStart = rowOffset;
for (int x = rowOffset; x < width; x++)
{
if (row[x] != isWhite)
{
counters[counterPosition]++;
}
else
{
if (counterPosition == 3)
{
if (isFinderPattern(counters))
{
return new int[] { patternStart, x };
}
patternStart += counters[0] + counters[1];
counters[0] = counters[2];
counters[1] = counters[3];
counters[2] = 0;
counters[3] = 0;
counterPosition--;
}
else
{
counterPosition++;
}
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
return null;
}
private FinderPattern parseFoundFinderPattern(BitArray row, int rowNumber, bool right, int[] startEnd)
{
// Actually we found elements 2-5
bool firstIsBlack = row[startEnd[0]];
int firstElementStart = startEnd[0] - 1;
// Locate element 1
while (firstElementStart >= 0 && firstIsBlack != row[firstElementStart])
{
firstElementStart--;
}
firstElementStart++;
int firstCounter = startEnd[0] - firstElementStart;
// Make 'counters' hold 1-4
int[] counters = getDecodeFinderCounters();
Array.Copy(counters, 0, counters, 1, counters.Length - 1);
counters[0] = firstCounter;
int value;
if (!parseFinderValue(counters, FINDER_PATTERNS, out value))
return null;
int start = firstElementStart;
int end = startEnd[1];
if (right)
{
// row is actually reversed
start = row.Size - 1 - start;
end = row.Size - 1 - end;
}
return new FinderPattern(value, new int[] { firstElementStart, startEnd[1] }, start, end, rowNumber);
}
private bool adjustOddEvenCounts(bool outsideChar, int numModules)
{
int oddSum = ZXing.Common.Detector.MathUtils.sum(getOddCounts());
int evenSum = ZXing.Common.Detector.MathUtils.sum(getEvenCounts());
int mismatch = oddSum + evenSum - numModules;
bool oddParityBad = (oddSum & 0x01) == (outsideChar ? 1 : 0);
bool evenParityBad = (evenSum & 0x01) == 1;
bool incrementOdd = false;
bool decrementOdd = false;
bool incrementEven = false;
bool decrementEven = false;
if (outsideChar)
{
if (oddSum > 12)
{
decrementOdd = true;
}
else if (oddSum < 4)
{
incrementOdd = true;
}
if (evenSum > 12)
{
decrementEven = true;
}
else if (evenSum < 4)
{
incrementEven = true;
}
}
else
{
if (oddSum > 11)
{
decrementOdd = true;
}
else if (oddSum < 5)
{
incrementOdd = true;
}
if (evenSum > 10)
{
decrementEven = true;
}
else if (evenSum < 4)
{
incrementEven = true;
}
}
/*if (mismatch == 2) {
if (!(oddParityBad && evenParityBad)) {
throw ReaderException.Instance;
}
decrementOdd = true;
decrementEven = true;
} else if (mismatch == -2) {
if (!(oddParityBad && evenParityBad)) {
throw ReaderException.Instance;
}
incrementOdd = true;
incrementEven = true;
} else */
if (mismatch == 1)
{
if (oddParityBad)
{
if (evenParityBad)
{
return false;
}
decrementOdd = true;
}
else
{
if (!evenParityBad)
{
return false;
}
decrementEven = true;
}
}
else if (mismatch == -1)
{
if (oddParityBad)
{
if (evenParityBad)
{
return false;
}
incrementOdd = true;
}
else
{
if (!evenParityBad)
{
return false;
}
incrementEven = true;
}
}
else if (mismatch == 0)
{
if (oddParityBad)
{
if (!evenParityBad)
{
return false;
}
// Both bad
if (oddSum < evenSum)
{
incrementOdd = true;
decrementEven = true;
}
else
{
decrementOdd = true;
incrementEven = true;
}
}
else
{
if (evenParityBad)
{
return false;
}
// Nothing to do!
}
}
else
{
return false;
}
if (incrementOdd)
{
if (decrementOdd)
{
return false;
}
increment(getOddCounts(), getOddRoundingErrors());
}
if (decrementOdd)
{
decrement(getOddCounts(), getOddRoundingErrors());
}
if (incrementEven)
{
if (decrementEven)
{
return false;
}
increment(getEvenCounts(), getOddRoundingErrors());
}
if (decrementEven)
{
decrement(getEvenCounts(), getEvenRoundingErrors());
}
return true;
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
namespace CPI.Audio
{
/// <summary>
/// Generates tones from a touch-tone phone.
/// </summary>
public class TouchToneGenerator : IDisposable
{
# region Static Fields
private static readonly double[] columnTones = new double[] { 1209, 1336, 1477 };
private static readonly double[] rowTones = new double[] { 697, 770, 852, 941 };
private static readonly Dictionary<char, double> columnTone = new Dictionary<char, double>();
private static readonly Dictionary<char, double> rowTone = new Dictionary<char, double>();
private static readonly Dictionary<char, char> letterTranslations = new Dictionary<char, char>();
# endregion
# region Static Constructors
static TouchToneGenerator()
{
columnTone['1'] = columnTones[0];
columnTone['2'] = columnTones[1];
columnTone['3'] = columnTones[2];
columnTone['4'] = columnTones[0];
columnTone['5'] = columnTones[1];
columnTone['6'] = columnTones[2];
columnTone['7'] = columnTones[0];
columnTone['8'] = columnTones[1];
columnTone['9'] = columnTones[2];
columnTone['*'] = columnTones[0];
columnTone['0'] = columnTones[1];
columnTone['#'] = columnTones[2];
rowTone['1'] = rowTones[0];
rowTone['2'] = rowTones[0];
rowTone['3'] = rowTones[0];
rowTone['4'] = rowTones[1];
rowTone['5'] = rowTones[1];
rowTone['6'] = rowTones[1];
rowTone['7'] = rowTones[2];
rowTone['8'] = rowTones[2];
rowTone['9'] = rowTones[2];
rowTone['*'] = rowTones[3];
rowTone['0'] = rowTones[3];
rowTone['#'] = rowTones[3];
letterTranslations['1'] = '1';
letterTranslations['2'] = '2';
letterTranslations['3'] = '3';
letterTranslations['4'] = '4';
letterTranslations['5'] = '5';
letterTranslations['6'] = '6';
letterTranslations['7'] = '7';
letterTranslations['8'] = '8';
letterTranslations['9'] = '9';
letterTranslations['*'] = '*';
letterTranslations['0'] = '0';
letterTranslations['#'] = '#';
letterTranslations['A'] = '2';
letterTranslations['B'] = '2';
letterTranslations['C'] = '2';
letterTranslations['D'] = '3';
letterTranslations['E'] = '3';
letterTranslations['F'] = '3';
letterTranslations['G'] = '4';
letterTranslations['H'] = '4';
letterTranslations['I'] = '4';
letterTranslations['J'] = '5';
letterTranslations['K'] = '5';
letterTranslations['L'] = '5';
letterTranslations['M'] = '6';
letterTranslations['N'] = '6';
letterTranslations['O'] = '6';
letterTranslations['P'] = '7';
letterTranslations['R'] = '7';
letterTranslations['S'] = '7';
letterTranslations['T'] = '8';
letterTranslations['U'] = '8';
letterTranslations['V'] = '8';
letterTranslations['W'] = '9';
letterTranslations['X'] = '9';
letterTranslations['Y'] = '9';
}
# endregion
# region Private Fields
private readonly WaveWriter8Bit _writer;
private readonly int _samplesPerTone;
private readonly int _samplesPerPause;
# endregion
# region Constructors
/// <summary>
/// Instantiates a new TouchToneGenerator object.
/// </summary>
/// <param name="output">The Stream object to write the wave to.</param>
/// <remarks>
/// When this object is disposed, it will close its underlying stream. To change this default behavior,
/// you can call an overloaded constructor which takes a closeUnderlyingStream parameter.
/// </remarks>
public TouchToneGenerator(Stream output)
: this(output, true) { }
/// <summary>
/// Instantiates a new TouchToneGenerator object.
/// </summary>
/// <param name="output">The Stream object to write the wave to.</param>
/// <param name="closeUnderlyingStream">
/// Determines whether to close the the stream that the TouchToneGenerator
/// is writing to when the TouchToneGenerator is closed.
/// </param>
public TouchToneGenerator(Stream output, bool closeUnderlyingStream)
{
_writer = new WaveWriter8Bit(output, 8000, false, closeUnderlyingStream);
_samplesPerTone = _writer.SampleRate * 9 / 20;
_samplesPerPause = _writer.SampleRate / 20;
}
# endregion
# region Methods
/// <summary>
/// Generates touchtone phone tones for a string of digits.
/// </summary>
/// <param name="phoneNumber">
/// A string of digits.
/// Valid digits are: 1234567890*#ABCDEFGHIJKLMNOPRSTUVWXY
/// Invalid digits will be silently ignored.
/// </param>
public void GenerateTones(string phoneNumber)
{
foreach (char digit in phoneNumber.ToUpper())
{
if (letterTranslations.ContainsKey(digit))
GenerateTone(letterTranslations[digit]);
}
}
private void GenerateTone(char digit)
{
double columnFrequency = columnTone[digit];
double rowFrequency = rowTone[digit];
double samplesPerColumnCycle = _writer.SampleRate / columnFrequency;
double samplesPerRowCycle = _writer.SampleRate / rowFrequency;
Sample8Bit sample = new Sample8Bit(false);
long startPoint = _writer.CurrentSample;
// Write out the tone associated with the digit's column
for (int currentSample = 0; currentSample < _samplesPerTone; currentSample++)
{
double sampleValue = Math.Sin(currentSample / samplesPerColumnCycle * 2 * Math.PI) * 60;
sample.LeftChannel = (byte)(sampleValue + 128);
_writer.Write(sample);
}
// go back to the starting point
_writer.CurrentSample = startPoint;
// Overlay the tone associated with the digit's row
for (int currentSample = 0; currentSample < _samplesPerTone; currentSample++)
{
// Figure out what the sample was originally set to
Sample8Bit originalSample = _writer.Read();
_writer.CurrentSample--;
double sampleValue = Math.Sin(currentSample / samplesPerRowCycle * 2 * Math.PI) * 60;
sample.LeftChannel = (byte)(sampleValue + originalSample.LeftChannel);
_writer.Write(sample);
}
// Insert a pause
sample.LeftChannel = 128;
for (int currentSample = 0; currentSample < _samplesPerPause; currentSample++)
{
_writer.Write(sample);
}
}
/// <summary>
/// Closes the TouchToneGenerator and saves the underlying stream.
/// </summary>
public void Close()
{
if (_writer != null)
_writer.Close();
}
/// <summary>
/// Closes the TouchToneGenerator and the underlying stream.
/// </summary>
/// <param name="disposing">true if called by the Dispose() method; false if called by a finalizer.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Close();
}
}
# endregion
#region IDisposable Members
/// <summary>
/// Disposes this object and cleans up any resources used.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
| |
/***************************************************************************\
*
* File: NonClientArea.cs
*
* Description:
* HWND-based NonClientArea proxy
*
* Copyright (C) 2002 by Microsoft Corporation. All rights reserved.
*
\***************************************************************************/
using System;
using System.Collections;
using System.Globalization;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Provider;
using System.ComponentModel;
using MS.Win32;
namespace MS.Internal.AutomationProxies
{
class NonClientArea: ProxyHwnd, IScrollProvider
{
#region Constructors
internal NonClientArea (IntPtr hwnd)
: base( hwnd, null, 0 )
{
_createOnEvent = new WinEventTracker.ProxyRaiseEvents (RaiseEvents);
}
#endregion
#region ProxyHwnd Interface
internal override void AdviseEventAdded (AutomationEvent eventId, AutomationProperty [] aidProps)
{
// we need to create the menu proxy so that the global event for menu will be listened for.
// This proxy will get advise of events needed for menus
ProxyHwnd menuProxy = CreateNonClientMenu();
if (menuProxy == null)
{
// If the window does not have a menu, it at least has a system menu.
WindowsTitleBar titleBar = (WindowsTitleBar)CreateNonClientChild(NonClientItem.TitleBar);
if (titleBar != null)
{
menuProxy = (ProxyHwnd)titleBar.CreateTitleBarChild(WindowsTitleBar._systemMenu);
}
}
if (menuProxy != null)
{
menuProxy.AdviseEventAdded(eventId, aidProps);
}
base.AdviseEventAdded(eventId, aidProps);
}
internal override void AdviseEventRemoved (AutomationEvent eventId, AutomationProperty [] aidProps)
{
// we need to create the menu proxy so that the global event for menu will be listened for.
// This proxy will get advise of events needed for menus
ProxyHwnd menuProxy = CreateNonClientMenu();
if (menuProxy == null)
{
// If the window does not have a menu, it at least has a system menu.
WindowsTitleBar titleBar = (WindowsTitleBar)CreateNonClientChild(NonClientItem.TitleBar);
if (titleBar != null)
{
menuProxy = (ProxyHwnd)titleBar.CreateTitleBarChild(WindowsTitleBar._systemMenu);
}
}
if (menuProxy != null)
{
menuProxy.AdviseEventRemoved(eventId, aidProps);
}
base.AdviseEventRemoved(eventId, aidProps);
}
// Picks a WinEvent to track for a UIA property
protected override int[] PropertyToWinEvent(AutomationProperty idProp)
{
if (idProp == AutomationElement.IsEnabledProperty)
{
return new int[] { NativeMethods.EventObjectStateChange };
}
return base.PropertyToWinEvent(idProp);
}
#endregion ProxyHwnd Interface
#region Proxy Create
// Static Create method called by UIAutomation to create this proxy.
// returns null if unsuccessful
internal static IRawElementProviderSimple Create(IntPtr hwnd, int idChild, int idObject)
{
return Create(hwnd, idChild);
}
internal static IRawElementProviderSimple Create(IntPtr hwnd, int idChild)
{
if (!UnsafeNativeMethods.IsWindow(hwnd))
{
return null;
}
System.Diagnostics.Debug.Assert(idChild == 0, string.Format(CultureInfo.CurrentCulture, "Invalid Child Id, idChild == {2}\n\rClassName: \"{0}\"\n\rhwnd = 0x{1:x8}", Misc.ProxyGetClassName(hwnd), hwnd.ToInt32(), idChild));
NativeMethods.Win32Rect clientRect = new NativeMethods.Win32Rect();
NativeMethods.Win32Rect windowRect = new NativeMethods.Win32Rect();
try
{
bool hasNonClientControls =
// Note: GetClientRect will do MapWindowsPoints
Misc.GetClientRectInScreenCoordinates(hwnd, ref clientRect)
&& Misc.GetWindowRect(hwnd, ref windowRect)
&& !windowRect.Equals(clientRect);
if(hasNonClientControls || WindowsFormsHelper.IsWindowsFormsControl(hwnd))
{
return new NonClientArea(hwnd);
}
return null;
}
catch (ElementNotAvailableException)
{
return null;
}
}
// proxy factory used to create menu bar items in response to OBJID_MENU winevents
// This is wired up to the #nonclientmenubar pseudo-classname in the proxy table
internal static IRawElementProviderSimple CreateMenuBarItem(IntPtr hwnd, int idChild, int idObject)
{
return CreateMenuBarItem(hwnd, idChild);
}
private static IRawElementProviderSimple CreateMenuBarItem(IntPtr hwnd, int idChild)
{
IntPtr menu = UnsafeNativeMethods.GetMenu(hwnd);
if (menu == IntPtr.Zero)
{
return null;
}
NonClientArea nonClientArea = new NonClientArea( hwnd );
WindowsMenu appMenu = new WindowsMenu(hwnd, nonClientArea, menu, WindowsMenu.MenuType.Toplevel, (int) NonClientItem.Menu);
if (idChild == 0)
{
return appMenu;
}
else
{
return appMenu.CreateMenuItem(idChild - 1);
}
}
// proxy factory used to create sytem menu in response to OBJID_MENU winevents
// This is wired up to the #nonclientsysmenu pseudo-classname in the proxy table
internal static IRawElementProviderSimple CreateSystemMenu(IntPtr hwnd, int idChild, int idObject)
{
return CreateSystemMenu(hwnd);
}
private static IRawElementProviderSimple CreateSystemMenu(IntPtr hwnd)
{
NonClientArea nonClientArea = new NonClientArea(hwnd);
WindowsTitleBar titleBar = (WindowsTitleBar)nonClientArea.CreateNonClientChild(NonClientItem.TitleBar);
return titleBar.CreateTitleBarChild(WindowsTitleBar._systemMenu);
}
#endregion
#region Public Methods
internal static void RaiseEvents(IntPtr hwnd, int eventId, object idProp, int idObject, int idChild)
{
switch (idObject)
{
case NativeMethods.OBJID_WINDOW:
RaiseEventsOnWindow(hwnd, eventId, idProp, idObject, idChild);
break;
case NativeMethods.OBJID_HSCROLL :
case NativeMethods.OBJID_VSCROLL :
RaiseEventsOnScroll(hwnd, eventId, idProp, idObject, idChild);
break;
case NativeMethods.OBJID_CLIENT:
RaiseEventsOnClient(hwnd, eventId, idProp, idObject, idChild);
break;
case NativeMethods.OBJID_SYSMENU:
case NativeMethods.OBJID_MENU:
RaiseMenuEventsOnClient(hwnd, eventId, idProp, idObject, idChild);
break;
}
}
// Returns a Proxy element corresponding to the specified screen coordinates.
internal override ProxySimple ElementProviderFromPoint (int x, int y)
{
int hit = Misc.ProxySendMessageInt(_hwnd, NativeMethods.WM_NCHITTEST, IntPtr.Zero, NativeMethods.Util.MAKELPARAM(x, y));
switch (hit)
{
case NativeMethods.HTHSCROLL:
{
ProxyFragment ret = CreateNonClientChild(NonClientItem.HScrollBar);
return ret.ElementProviderFromPoint(x, y);
}
case NativeMethods.HTVSCROLL:
{
ProxyFragment ret = CreateNonClientChild(NonClientItem.VScrollBar);
return ret.ElementProviderFromPoint(x, y);
}
case NativeMethods.HTCAPTION :
case NativeMethods.HTMINBUTTON :
case NativeMethods.HTMAXBUTTON :
case NativeMethods.HTHELP :
case NativeMethods.HTCLOSE :
case NativeMethods.HTSYSMENU :
WindowsTitleBar tb = new WindowsTitleBar(_hwnd, this, 0);
return tb.ElementProviderFromPoint (x, y);
case NativeMethods.HTGROWBOX:
return CreateNonClientChild(NonClientItem.Grip);
case NativeMethods.HTBOTTOMRIGHT:
return FindGrip(x, y);
case NativeMethods.HTBOTTOMLEFT:
return FindGripMirrored(x, y);
case NativeMethods.HTMENU:
return FindMenus(x, y);
case NativeMethods.HTLEFT:
case NativeMethods.HTRIGHT:
case NativeMethods.HTTOP:
case NativeMethods.HTTOPLEFT:
case NativeMethods.HTTOPRIGHT:
case NativeMethods.HTBOTTOM:
case NativeMethods.HTBORDER:
// We do not handle the borders so return null here and let the
// HWNDProvider handle them as the whole window.
return null;
default:
// Leave all other cases (especially including HTCLIENT) alone...
return null;
}
}
// Returns an item corresponding to the focused element (if there is one), or null otherwise.
internal override ProxySimple GetFocus()
{
if (WindowsMenu.IsInSystemMenuMode())
{
// Since in system menu mode try to find point on the SystemMenu
WindowsTitleBar titleBar = (WindowsTitleBar)CreateNonClientChild(NonClientItem.TitleBar);
if (titleBar != null)
{
ProxyFragment systemMenu = (ProxyFragment)titleBar.CreateTitleBarChild(WindowsTitleBar._systemMenu);
if (systemMenu != null)
{
// need to drill down ourself, since the FragmentRoot of the System Menu Bar will
// be NonClient area hence UIAutomation will not drill down
ProxySimple proxy = systemMenu.GetFocus();
if (proxy != null)
{
return proxy;
}
}
}
}
return base.GetFocus();
}
#endregion Public Methods
internal override ProviderOptions ProviderOptions
{
get
{
return base.ProviderOptions | ProviderOptions.NonClientAreaProvider;
}
}
// Returns the Run Time Id.
internal override int [] GetRuntimeId ()
{
return new int [] { 1, unchecked((int)(long)_hwnd) };
}
// Returns a pattern interface if supported, else null.
internal override object GetPatternProvider (AutomationPattern iid)
{
if (iid == ScrollPattern.Pattern && WindowScroll.HasScrollableStyle(_hwnd))
{
return this;
}
return null;
}
#region IRawElementProvider
// Next Silbing: assumes none, must be overloaded by a subclass if any
// The method is called on the parent with a reference to the child.
// This makes the implementation a lot more clean than the UIAutomation call
internal override ProxySimple GetNextSibling (ProxySimple child)
{
return ReturnNextNonClientChild (true, (NonClientItem) child._item + 1);
}
// Prev Silbing: assumes none, must be overloaded by a subclass if any
// The method is called on the parent with a reference to the child.
// This makes the implementation a lot more clean than the UIAutomation call
internal override ProxySimple GetPreviousSibling (ProxySimple child)
{
return ReturnNextNonClientChild (false, (NonClientItem) child._item - 1);
}
// GetFirstChild: assumes none, must be overloaded by a subclass if any
internal override ProxySimple GetFirstChild ()
{
return ReturnNextNonClientChild (true, (NonClientItem)((int)NonClientItem.MIN + 1));
}
// GetLastChild: assumes none, must be overloaded by a subclass if any
internal override ProxySimple GetLastChild ()
{
return ReturnNextNonClientChild (false, (NonClientItem)((int)NonClientItem.MAX - 1));
}
#endregion
#region Scroll Pattern
// Request to scroll Horizontally and vertically by the specified amount
void IScrollProvider.SetScrollPercent (double horizontalPercent, double verticalPercent)
{
WindowScroll.SetScrollPercent (_hwnd, horizontalPercent, verticalPercent, true);
}
// Request to scroll horizontally and vertically by the specified scrolling amount
void IScrollProvider.Scroll (ScrollAmount horizontalAmount, ScrollAmount verticalAmount)
{
WindowScroll.Scroll (_hwnd, horizontalAmount, verticalAmount, true);
}
// Calc the position of the horizontal scroll bar thumb in the 0..100 % range
double IScrollProvider.HorizontalScrollPercent
{
get
{
return (double) WindowScroll.GetPropertyScroll (ScrollPattern.HorizontalScrollPercentProperty, _hwnd);
}
}
// Calc the position of the Vertical scroll bar thumb in the 0..100 % range
double IScrollProvider.VerticalScrollPercent
{
get
{
return (double)WindowScroll.GetPropertyScroll(ScrollPattern.VerticalScrollPercentProperty, _hwnd);
}
}
// Percentage of the window that is visible along the horizontal axis.
double IScrollProvider.HorizontalViewSize
{
get
{
return (double)WindowScroll.GetPropertyScroll(ScrollPattern.HorizontalViewSizeProperty, _hwnd);
}
}
// Percentage of the window that is visible along the vertical axis.
double IScrollProvider.VerticalViewSize
{
get
{
return (double)WindowScroll.GetPropertyScroll(ScrollPattern.VerticalViewSizeProperty, _hwnd);
}
}
// Can the element be horizontaly scrolled
bool IScrollProvider.HorizontallyScrollable
{
get
{
return (bool) WindowScroll.GetPropertyScroll (ScrollPattern.HorizontallyScrollableProperty, _hwnd);
}
}
// Can the element be verticaly scrolled
bool IScrollProvider.VerticallyScrollable
{
get
{
return (bool) WindowScroll.GetPropertyScroll (ScrollPattern.VerticallyScrollableProperty, _hwnd);
}
}
#endregion
#region Private Methods
// Not all the non-client children exist for every window that has a non-client area.
// This gets the next child that is actually there.
private ProxyFragment ReturnNextNonClientChild (bool next, NonClientItem start)
{
ProxyFragment el;
for (int i = (int) start; i > (int) NonClientItem.MIN && i < (int) NonClientItem.MAX; i += next ? 1 : -1)
{
el = CreateNonClientChild ((NonClientItem) i);
if (el != null)
return el;
}
return null;
}
// The ApplicationWindow pattern provider code needs to be able to create menu bars correctly
// and uses the NonClientArea proxy to accomplish this.
// the scroll bars are not always peripheral so we create them with a negative number so the
// base class can tell if they are peripheral or not.
internal enum NonClientItem
{
MIN = -5,
Grip = -4,
HScrollBar = -3,
VScrollBar = -2,
TitleBar = 0,
Menu,
MAX,
}
// Create the approiate child this can return null if that child does not exist
internal ProxyFragment CreateNonClientChild (NonClientItem item)
{
switch (item)
{
case NonClientItem.HScrollBar :
if (WindowsScrollBar.HasHorizontalScrollBar (_hwnd))
{
// the listview needs special handling WindowsListViewScrollBar inherits from WindowsScrollBar
// and overrides some of its behavoir
if (Misc.ProxyGetClassName(_hwnd) == "SysListView32")
return new WindowsListViewScrollBar (_hwnd, this, (int) item, NativeMethods.SB_HORZ);
else
return new WindowsScrollBar (_hwnd, this, (int) item, NativeMethods.SB_HORZ);
}
break;
case NonClientItem.VScrollBar :
if (WindowsScrollBar.HasVerticalScrollBar (_hwnd))
{
// the listview needs special handling WindowsListViewScrollBar inherits from WindowsScrollBar
// and overrides some of its behavoir
if (Misc.ProxyGetClassName(_hwnd) == "SysListView32")
return new WindowsListViewScrollBar (_hwnd, this, (int) item, NativeMethods.SB_VERT);
else
return new WindowsScrollBar (_hwnd, this, (int) item, NativeMethods.SB_VERT);
}
break;
case NonClientItem.TitleBar :
{
// Note 2 checks above will succeed for the win32popup menu, hence adding this last one
if (WindowsTitleBar.HasTitleBar (_hwnd))
{
return new WindowsTitleBar (_hwnd, this, (int) item);
}
break;
}
case NonClientItem.Menu :
{
return CreateNonClientMenu();
}
case NonClientItem.Grip :
{
int style = WindowStyle;
if (Misc.IsBitSet(style, NativeMethods.WS_VSCROLL) && Misc.IsBitSet(style, NativeMethods.WS_HSCROLL))
{
if (WindowsGrip.IsGripPresent(_hwnd, false))
{
return new WindowsGrip(_hwnd, this, (int)item);
}
}
break;
}
default :
return null;
}
return null;
}
internal ProxyHwnd CreateNonClientMenu ()
{
// child windows don't have menus
int style = WindowStyle;
if (!Misc.IsBitSet(style, NativeMethods.WS_CHILD))
{
ProxyHwnd menuProxy = null;
if (WindowsMenu.IsInSystemMenuMode())
{
// Since in system menu mode try to find point on the SystemMenu
WindowsTitleBar titleBar = (WindowsTitleBar)CreateNonClientChild(NonClientItem.TitleBar);
if (titleBar != null)
{
menuProxy = (ProxyHwnd)titleBar.CreateTitleBarChild(WindowsTitleBar._systemMenu);
}
}
else
{
IntPtr menu = UnsafeNativeMethods.GetMenu(_hwnd);
if (menu != IntPtr.Zero)
{
menuProxy = new WindowsMenu(_hwnd, this, menu, WindowsMenu.MenuType.Toplevel, (int)NonClientItem.Menu);
}
}
if (menuProxy != null)
{
// if this menu is not visible its really not there
if (menuProxy.BoundingRectangle.Width != 0 && menuProxy.BoundingRectangle.Height != 0)
{
return menuProxy;
}
}
}
return null;
}
private ProxyFragment FindGrip(int x,int y)
{
// Note that for sizeable windows, being over the size grip may
// return in fact HTBOTTOMRIGHT for sizing purposes.
// make sure we don't accidently include the borders
ProxyFragment grip = CreateNonClientChild(NonClientItem.Grip);
if (grip != null)
{
Rect rect = grip.BoundingRectangle;
if (x < rect.Right && y < rect.Bottom)
{
return grip;
}
}
return null;
}
private ProxyFragment FindGripMirrored(int x, int y)
{
if (Misc.IsLayoutRTL(_hwnd))
{
// Right to left mirroring style
// Note that for sizeable windows, being over the size grip may
// return in fact HTBOTTOMLEFT for sizing purposes.
// make sure we don't accidently include the borders
ProxyFragment grip = CreateNonClientChild(NonClientItem.Grip);
if (grip != null)
{
Rect rect = grip.BoundingRectangle;
if (x > rect.Left && y < rect.Bottom)
{
return grip;
}
}
}
return null;
}
private ProxySimple FindMenus(int x, int y)
{
if (WindowsMenu.IsInSystemMenuMode())
{
// Since in system menu mode try to find point on the SystemMenu
WindowsTitleBar titleBar = (WindowsTitleBar)CreateNonClientChild(NonClientItem.TitleBar);
if (titleBar != null)
{
ProxyFragment systemMenu = (ProxyFragment)titleBar.CreateTitleBarChild(WindowsTitleBar._systemMenu);
if (systemMenu != null)
{
// need to drill down ourself, since the FragmentRoot of the System Menu Bar will
// be NonClient area hence UIAutomation will not drill down
ProxySimple proxy = systemMenu.ElementProviderFromPoint(x, y);
if (proxy != null)
{
return proxy;
}
}
}
}
else
{
// Not in system menu mode so it may be a Popup Menu, have a go at it
ProxyFragment menu = CreateNonClientChild(NonClientItem.Menu);
if (menu != null)
{
// need to drill down ourself, since the FragmentRoot of the MenuBar will
// be NonClient area hence UIAutomation will not drill down
ProxySimple proxy = menu.ElementProviderFromPoint(x, y);
if (proxy != null)
{
return proxy;
}
// We may have been on the Menu but not on a menu Item
return menu;
}
}
return null;
}
private static void RaiseMenuEventsOnClient(IntPtr hwnd, int eventId, object idProp, int idObject, int idChild)
{
ProxySimple el = WindowsMenu.CreateMenuItemFromEvent(hwnd, eventId, idChild, idObject);
if (el != null)
{
el.DispatchEvents(eventId, idProp, idObject, idChild);
}
}
private static void RaiseEventsOnClient(IntPtr hwnd, int eventId, object idProp, int idObject, int idChild)
{
if (Misc.GetClassName(hwnd) == "ComboLBox")
{
ProxySimple el = (ProxySimple)WindowsListBox.Create(hwnd, idChild);
if (el != null)
{
el.DispatchEvents(eventId, idProp, idObject, idChild);
}
}
}
private static void RaiseEventsOnScroll(IntPtr hwnd, int eventId, object idProp, int idObject, int idChild)
{
if ((idProp == ScrollPattern.VerticalScrollPercentProperty && idObject != NativeMethods.OBJID_VSCROLL) ||
(idProp == ScrollPattern.HorizontalScrollPercentProperty && idObject != NativeMethods.OBJID_HSCROLL))
{
return;
}
ProxyFragment el = new NonClientArea(hwnd);
if (el == null)
return;
if (idProp == InvokePattern.InvokedEvent)
{
NonClientItem item = idObject == NativeMethods.OBJID_HSCROLL ? NonClientItem.HScrollBar : NonClientItem.VScrollBar;
int sbFlag = idObject == NativeMethods.OBJID_HSCROLL ? NativeMethods.SB_HORZ : NativeMethods.SB_VERT;
ProxyFragment scrollBar = new WindowsScrollBar(hwnd, el, (int)item, sbFlag);
if (scrollBar != null)
{
ProxySimple scrollBarBit = WindowsScrollBarBits.CreateFromChildId(hwnd, scrollBar, idChild, sbFlag);
if (scrollBarBit != null)
{
scrollBarBit.DispatchEvents(eventId, idProp, idObject, idChild);
}
}
return;
}
if (eventId == NativeMethods.EventObjectStateChange && idProp == ValuePattern.IsReadOnlyProperty)
{
if (idChild == 0)
{
//
if (idObject == NativeMethods.OBJID_HSCROLL || idObject == NativeMethods.OBJID_VSCROLL)
{
idObject = NativeMethods.OBJID_WINDOW;
}
el.DispatchEvents(eventId, idProp, idObject, idChild);
}
return;
}
if (idProp == ValuePattern.ValueProperty && eventId == NativeMethods.EVENT_OBJECT_VALUECHANGE)
{
NonClientItem item = idObject == NativeMethods.OBJID_HSCROLL ? NonClientItem.HScrollBar : NonClientItem.VScrollBar;
WindowsScrollBar scrollBar = new WindowsScrollBar(hwnd, el, (int)item, idObject == NativeMethods.OBJID_HSCROLL ? NativeMethods.SB_HORZ : NativeMethods.SB_VERT);
scrollBar.DispatchEvents(0, ValuePattern.ValueProperty, NativeMethods.OBJID_CLIENT, 0);
return;
}
if (Misc.GetClassName(hwnd) == "ComboLBox")
{
el = (ProxyFragment)WindowsListBox.Create(hwnd, 0);
}
if (el != null)
{
el.DispatchEvents(eventId, idProp, idObject, idChild);
}
}
private static void RaiseEventsOnWindow(IntPtr hwnd, int eventId, object idProp, int idObject, int idChild)
{
ProxyFragment elw = new NonClientArea(hwnd);
if (eventId == NativeMethods.EventObjectNameChange)
{
int style = Misc.GetWindowStyle(hwnd);
if (Misc.IsBitSet(style, NativeMethods.WS_CHILD))
{
// Full control names do not change. They are named by the static label.
return;
}
else
{
// But the title bar name does so allow title bar proxy to procees the event.
WindowsTitleBar tb = new WindowsTitleBar(hwnd, elw, 0);
tb.DispatchEvents(eventId, idProp, idObject, idChild);
}
}
elw.DispatchEvents(eventId, idProp, idObject, idChild);
}
#endregion Private Methods
#region Private Fields
#endregion Private Fields
}
}
| |
namespace Macabresoft.Macabre2D.UI.Common;
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization;
using Macabresoft.AvaloniaEx;
using Macabresoft.Core;
using Macabresoft.Macabre2D.Framework;
/// <summary>
/// Interface for a node in the content tree.
/// </summary>
public interface IContentNode : INameable {
/// <summary>
/// Occurs when the path to this file has changed.
/// </summary>
event EventHandler<ValueChangedEventArgs<string>> PathChanged;
/// <summary>
/// Gets the identifier.
/// </summary>
Guid Id { get; }
/// <summary>
/// Gets the parent.
/// </summary>
IContentDirectory Parent { get; }
/// <summary>
/// Gets or sets the name without an extension.
/// </summary>
string NameWithoutExtension { get; set; }
/// <summary>
/// Changes the parent of this node.
/// </summary>
/// <param name="newParent">The new parent.</param>
void ChangeParent(IContentDirectory newParent);
/// <summary>
/// Gets the content path to this file or directory, which assumes a root of the project content directory.
/// </summary>
/// <returns>The content path.</returns>
string GetContentPath();
/// <summary>
/// Gets the depth of this node in the content hierarchy. The root is 0 and each directory deeper is 1.
/// </summary>
/// <returns>The depth.</returns>
int GetDepth();
/// <summary>
/// Gets the full path to this file or directory.
/// </summary>
/// <returns>The full path.</returns>
string GetFullPath();
/// <summary>
/// Checks whether or not this node is a descendent of the provided directory.
/// </summary>
/// <param name="directory">The directory.</param>
/// <returns>A value indicating whether or not this node is a descendent of the provided directory.</returns>
bool IsDescendentOf(IContentDirectory directory);
}
/// <summary>
/// A node in the content tree.
/// </summary>
public abstract class ContentNode : NotifyPropertyChanged, IContentNode {
private string _name;
/// <inheritdoc />
public event EventHandler<ValueChangedEventArgs<string>> PathChanged;
/// <inheritdoc />
public abstract Guid Id { get; }
/// <inheritdoc />
public string Name {
get => this._name;
set {
var originalPath = this.GetFullPath();
if (string.IsNullOrEmpty(value)) {
this.RaisePropertyChanged(nameof(this.Name));
}
else if (this.Set(ref this._name, value, true)) {
if (this.Parent is IContentDirectory directory) {
directory.RemoveChild(this);
directory.AddChild(this);
}
this.OnPathChanged(originalPath);
}
}
}
/// <inheritdoc />
[DataMember(Name = "Name")]
[Category("File System")]
public string NameWithoutExtension {
get => this.GetNameWithoutExtension();
set => this.Name = $"{value}{this.GetFileExtension()}";
}
/// <inheritdoc />
public IContentDirectory Parent { get; private set; }
/// <inheritdoc />
public void ChangeParent(IContentDirectory newParent) {
var originalParent = this.Parent;
if (newParent != originalParent && newParent != this) {
var originalPath = originalParent != null ? this.GetFullPath() : string.Empty;
originalParent?.RemoveChild(this);
if (newParent?.AddChild(this) == true) {
this.Parent = newParent;
if (originalParent != null) {
this.OnPathChanged(originalPath);
}
}
else {
originalParent?.AddChild(this);
}
}
}
/// <inheritdoc />
public virtual string GetContentPath() {
if (this.Parent != null && !string.IsNullOrEmpty(this.NameWithoutExtension)) {
return Path.Combine(this.Parent.GetContentPath(), this.NameWithoutExtension);
}
return this.NameWithoutExtension ?? string.Empty;
}
/// <inheritdoc />
public int GetDepth() {
return this.Parent?.GetDepth() + 1 ?? 0;
}
/// <inheritdoc />
public virtual string GetFullPath() {
if (this.Parent != null && !string.IsNullOrEmpty(this.Name)) {
return Path.Combine(this.Parent.GetFullPath(), this.Name);
}
return this.Name ?? string.Empty;
}
/// <inheritdoc />
public bool IsDescendentOf(IContentDirectory directory) {
var isDescendent = false;
if (this.Parent != null) {
isDescendent = this.Parent == directory || this.Parent.IsDescendentOf(directory);
}
return isDescendent;
}
/// <summary>
/// Gets the file extension.
/// </summary>
/// <returns>The file extension.</returns>
protected abstract string GetFileExtension();
/// <summary>
/// Gets the name without its file extension.
/// </summary>
/// <returns>The name without its file extension.</returns>
protected abstract string GetNameWithoutExtension();
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="parent">The parent.</param>
protected void Initialize(string name, IContentDirectory parent) {
this._name = name;
this.ChangeParent(parent);
}
/// <summary>
/// Called when the path changes.
/// </summary>
/// <param name="originalPath">The original path from before the change.</param>
protected virtual void OnPathChanged(string originalPath) {
var eventArgs = new ValueChangedEventArgs<string>(originalPath, this.GetFullPath());
if (eventArgs.HasChanged) {
this.RaisePathChanged(this, eventArgs);
}
}
/// <summary>
/// Raises the <see cref="PathChanged" /> event.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event arguments.</param>
protected void RaisePathChanged(object sender, ValueChangedEventArgs<string> e) {
this.PathChanged?.SafeInvoke(sender, e);
}
}
| |
// 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;
using System.Diagnostics;
using System.Security.Principal;
using Xunit;
namespace System.ServiceProcess.Tests
{
internal sealed class ServiceProvider
{
public readonly string TestMachineName;
public readonly TimeSpan ControlTimeout;
public readonly string TestServiceName;
public readonly string TestServiceDisplayName;
public readonly string DependentTestServiceNamePrefix;
public readonly string DependentTestServiceDisplayNamePrefix;
public readonly string TestServiceRegistryKey;
public ServiceProvider()
{
TestMachineName = ".";
ControlTimeout = TimeSpan.FromSeconds(10);
TestServiceName = Guid.NewGuid().ToString();
TestServiceDisplayName = "Test Service " + TestServiceName;
DependentTestServiceNamePrefix = TestServiceName + ".Dependent";
DependentTestServiceDisplayNamePrefix = TestServiceDisplayName + ".Dependent";
TestServiceRegistryKey = @"HKEY_USERS\.DEFAULT\dotnetTests\ServiceController\" + TestServiceName;
// Create the service
CreateTestServices();
}
private void CreateTestServices()
{
// Create the test service and its dependent services. Then, start the test service.
// All control tests assume that the test service is running when they are executed.
// So all tests should make sure to restart the service if they stop, pause, or shut
// it down.
RunServiceExecutable("create");
}
public void DeleteTestServices()
{
RunServiceExecutable("delete");
RegistryKey users = Registry.Users;
if (users.OpenSubKey(".DEFAULT\\dotnetTests") != null)
users.DeleteSubKeyTree(".DEFAULT\\dotnetTests");
}
private void RunServiceExecutable(string action)
{
const string serviceExecutable = "System.ServiceProcess.ServiceController.TestNativeService.exe";
var process = new Process();
process.StartInfo.FileName = serviceExecutable;
process.StartInfo.Arguments = string.Format("\"{0}\" \"{1}\" {2}", TestServiceName, TestServiceDisplayName, action);
process.Start();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception("error: " + serviceExecutable + " failed with exit code " + process.ExitCode.ToString());
}
}
}
public class ServiceControllerTests : IDisposable
{
private const int ExpectedDependentServiceCount = 3;
ServiceProvider _testService;
public ServiceControllerTests()
{
_testService = new ServiceProvider();
}
private static bool RunningWithElevatedPrivileges
{
get
{
return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithServiceName()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(_testService.TestServiceName, controller.ServiceName);
Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName);
Assert.Equal(_testService.TestMachineName, controller.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithDisplayName()
{
var controller = new ServiceController(_testService.TestServiceDisplayName);
Assert.Equal(_testService.TestServiceName, controller.ServiceName);
Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName);
Assert.Equal(_testService.TestMachineName, controller.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ConstructWithMachineName()
{
var controller = new ServiceController(_testService.TestServiceName, _testService.TestMachineName);
Assert.Equal(_testService.TestServiceName, controller.ServiceName);
Assert.Equal(_testService.TestServiceDisplayName, controller.DisplayName);
Assert.Equal(_testService.TestMachineName, controller.MachineName);
Assert.Equal(ServiceType.Win32OwnProcess, controller.ServiceType);
Assert.Throws<ArgumentException>(() => { var c = new ServiceController(_testService.TestServiceName, ""); });
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ControlCapabilities()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.True(controller.CanStop);
Assert.True(controller.CanPauseAndContinue);
Assert.False(controller.CanShutdown);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void StartWithArguments()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
var args = new[] { "a", "b", "c", "d", "e" };
controller.Start(args);
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
// The test service writes the arguments that it was started with to the _testService.TestServiceRegistryKey.
// Read this key to verify that the arguments were properly passed to the service.
string argsString = Registry.GetValue(_testService.TestServiceRegistryKey, "ServiceArguments", null) as string;
Assert.Equal(string.Join(",", args), argsString);
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void StopAndStart()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
for (int i = 0; i < 2; i++)
{
controller.Stop();
controller.WaitForStatus(ServiceControllerStatus.Stopped, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Stopped, controller.Status);
controller.Start();
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void PauseAndContinue()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
for (int i = 0; i < 2; i++)
{
controller.Pause();
controller.WaitForStatus(ServiceControllerStatus.Paused, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Paused, controller.Status);
controller.Continue();
controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout);
Assert.Equal(ServiceControllerStatus.Running, controller.Status);
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void WaitForStatusTimeout()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Throws<System.ServiceProcess.TimeoutException>(() => controller.WaitForStatus(ServiceControllerStatus.Paused, TimeSpan.Zero));
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void GetServices()
{
bool foundTestService = false;
foreach (var service in ServiceController.GetServices())
{
if (service.ServiceName == _testService.TestServiceName)
{
foundTestService = true;
}
}
Assert.True(foundTestService, "Test service was not enumerated with all services");
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void GetDevices()
{
var devices = ServiceController.GetDevices();
Assert.True(devices.Length != 0);
const ServiceType SERVICE_TYPE_DRIVER =
ServiceType.FileSystemDriver |
ServiceType.KernelDriver |
ServiceType.RecognizerDriver;
Assert.All(devices, device => Assert.NotEqual(0, (int)(device.ServiceType & SERVICE_TYPE_DRIVER)));
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void Dependencies()
{
// The test service creates a number of dependent services, each of which is depended on
// by all the services created after it.
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ExpectedDependentServiceCount, controller.DependentServices.Length);
for (int i = 0; i < controller.DependentServices.Length; i++)
{
var dependent = AssertHasDependent(controller, _testService.DependentTestServiceNamePrefix + i, _testService.DependentTestServiceDisplayNamePrefix + i);
Assert.Equal(ServiceType.Win32OwnProcess, dependent.ServiceType);
// Assert that this dependent service is depended on by all the test services created after it
Assert.Equal(ExpectedDependentServiceCount - i - 1, dependent.DependentServices.Length);
for (int j = i + 1; j < ExpectedDependentServiceCount; j++)
{
AssertHasDependent(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j);
}
// Assert that the dependent service depends on the main test service
AssertDependsOn(dependent, _testService.TestServiceName, _testService.TestServiceDisplayName);
// Assert that this dependent service depends on all the test services created before it
Assert.Equal(i + 1, dependent.ServicesDependedOn.Length);
for (int j = i - 1; j >= 0; j--)
{
AssertDependsOn(dependent, _testService.DependentTestServiceNamePrefix + j, _testService.DependentTestServiceDisplayNamePrefix + j);
}
}
}
[ConditionalFact(nameof(RunningWithElevatedPrivileges))]
public void ServicesStartMode()
{
var controller = new ServiceController(_testService.TestServiceName);
Assert.Equal(ServiceStartMode.Manual, controller.StartType);
// Check for the startType of the dependent services.
for (int i = 0; i < controller.DependentServices.Length; i++)
{
Assert.Equal(ServiceStartMode.Disabled, controller.DependentServices[i].StartType);
}
}
public void Dispose()
{
_testService.DeleteTestServices();
}
private static ServiceController AssertHasDependent(ServiceController controller, string serviceName, string displayName)
{
var dependent = FindService(controller.DependentServices, serviceName, displayName);
Assert.NotNull(dependent);
return dependent;
}
private static ServiceController AssertDependsOn(ServiceController controller, string serviceName, string displayName)
{
var dependency = FindService(controller.ServicesDependedOn, serviceName, displayName);
Assert.NotNull(dependency);
return dependency;
}
private static ServiceController FindService(ServiceController[] services, string serviceName, string displayName)
{
foreach (ServiceController service in services)
{
if (service.ServiceName == serviceName && service.DisplayName == displayName)
{
return service;
}
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
namespace Internal.Cryptography.Pal
{
internal sealed partial class StorePal
{
private static CollectionBackedStoreProvider s_machineRootStore;
private static CollectionBackedStoreProvider s_machineIntermediateStore;
private static readonly object s_machineLoadLock = new object();
public static IStorePal FromHandle(IntPtr storeHandle)
{
throw new PlatformNotSupportedException();
}
public static ILoaderPal FromBlob(byte[] rawData, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
{
Debug.Assert(password != null);
ICertificatePal singleCert;
if (CertificatePal.TryReadX509Der(rawData, out singleCert) ||
CertificatePal.TryReadX509Pem(rawData, out singleCert))
{
// The single X509 structure methods shouldn't return true and out null, only empty
// collections have that behavior.
Debug.Assert(singleCert != null);
return SingleCertToLoaderPal(singleCert);
}
List<ICertificatePal> certPals;
if (PkcsFormatReader.TryReadPkcs7Der(rawData, out certPals) ||
PkcsFormatReader.TryReadPkcs7Pem(rawData, out certPals) ||
PkcsFormatReader.TryReadPkcs12(rawData, password, out certPals))
{
Debug.Assert(certPals != null);
return ListToLoaderPal(certPals);
}
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
public static ILoaderPal FromFile(string fileName, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
{
using (SafeBioHandle bio = Interop.Crypto.BioNewFile(fileName, "rb"))
{
Interop.Crypto.CheckValidOpenSslHandle(bio);
return FromBio(bio, password);
}
}
private static ILoaderPal FromBio(SafeBioHandle bio, SafePasswordHandle password)
{
int bioPosition = Interop.Crypto.BioTell(bio);
Debug.Assert(bioPosition >= 0);
ICertificatePal singleCert;
if (CertificatePal.TryReadX509Pem(bio, out singleCert))
{
return SingleCertToLoaderPal(singleCert);
}
// Rewind, try again.
CertificatePal.RewindBio(bio, bioPosition);
if (CertificatePal.TryReadX509Der(bio, out singleCert))
{
return SingleCertToLoaderPal(singleCert);
}
// Rewind, try again.
CertificatePal.RewindBio(bio, bioPosition);
List<ICertificatePal> certPals;
if (PkcsFormatReader.TryReadPkcs7Pem(bio, out certPals))
{
return ListToLoaderPal(certPals);
}
// Rewind, try again.
CertificatePal.RewindBio(bio, bioPosition);
if (PkcsFormatReader.TryReadPkcs7Der(bio, out certPals))
{
return ListToLoaderPal(certPals);
}
// Rewind, try again.
CertificatePal.RewindBio(bio, bioPosition);
if (PkcsFormatReader.TryReadPkcs12(bio, password, out certPals))
{
return ListToLoaderPal(certPals);
}
// Since we aren't going to finish reading, leaving the buffer where it was when we got
// it seems better than leaving it in some arbitrary other position.
//
// But, before seeking back to start, save the Exception representing the last reported
// OpenSSL error in case the last BioSeek would change it.
Exception openSslException = Interop.Crypto.CreateOpenSslCryptographicException();
// Use BioSeek directly for the last seek attempt, because any failure here should instead
// report the already created (but not yet thrown) exception.
Interop.Crypto.BioSeek(bio, bioPosition);
throw openSslException;
}
public static IExportPal FromCertificate(ICertificatePal cert)
{
return new ExportProvider(cert);
}
public static IExportPal LinkFromCertificateCollection(X509Certificate2Collection certificates)
{
return new ExportProvider(certificates);
}
public static IStorePal FromSystemStore(string storeName, StoreLocation storeLocation, OpenFlags openFlags)
{
if (storeLocation == StoreLocation.CurrentUser)
{
if (X509Store.DisallowedStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase))
{
return new DirectoryBasedStoreProvider.UnsupportedDisallowedStore(openFlags);
}
return new DirectoryBasedStoreProvider(storeName, openFlags);
}
Debug.Assert(storeLocation == StoreLocation.LocalMachine);
if ((openFlags & OpenFlags.ReadWrite) == OpenFlags.ReadWrite)
{
throw new CryptographicException(
SR.Cryptography_Unix_X509_MachineStoresReadOnly,
new PlatformNotSupportedException(SR.Cryptography_Unix_X509_MachineStoresReadOnly));
}
// The static store approach here is making an optimization based on not
// having write support. Once writing is permitted the stores would need
// to fresh-read whenever being requested.
if (s_machineRootStore == null)
{
lock (s_machineLoadLock)
{
if (s_machineRootStore == null)
{
LoadMachineStores();
}
}
}
if (X509Store.RootStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase))
{
return s_machineRootStore;
}
if (X509Store.IntermediateCAStoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase))
{
return s_machineIntermediateStore;
}
throw new CryptographicException(
SR.Cryptography_Unix_X509_MachineStoresRootOnly,
new PlatformNotSupportedException(SR.Cryptography_Unix_X509_MachineStoresRootOnly));
}
private static ILoaderPal SingleCertToLoaderPal(ICertificatePal singleCert)
{
return new SingleCertLoader(singleCert);
}
private static ILoaderPal ListToLoaderPal(List<ICertificatePal> certPals)
{
return new CertCollectionLoader(certPals);
}
private static void LoadMachineStores()
{
Debug.Assert(
Monitor.IsEntered(s_machineLoadLock),
"LoadMachineStores assumes a lock(s_machineLoadLock)");
var rootStore = new List<X509Certificate2>();
var intermedStore = new List<X509Certificate2>();
DirectoryInfo rootStorePath = null;
IEnumerable<FileInfo> trustedCertFiles;
try
{
rootStorePath = new DirectoryInfo(Interop.Crypto.GetX509RootStorePath());
}
catch (ArgumentException)
{
// If SSL_CERT_DIR is set to the empty string, or anything else which gives
// "The path is not of a legal form", then the GetX509RootStorePath value is ignored.
}
if (rootStorePath != null && rootStorePath.Exists)
{
trustedCertFiles = rootStorePath.EnumerateFiles();
}
else
{
trustedCertFiles = Array.Empty<FileInfo>();
}
FileInfo rootStoreFile = null;
try
{
rootStoreFile = new FileInfo(Interop.Crypto.GetX509RootStoreFile());
}
catch (ArgumentException)
{
// If SSL_CERT_FILE is set to the empty string, or anything else which gives
// "The path is not of a legal form", then the GetX509RootStoreFile value is ignored.
}
if (rootStoreFile != null && rootStoreFile.Exists)
{
trustedCertFiles = Append(trustedCertFiles, rootStoreFile);
}
HashSet<X509Certificate2> uniqueRootCerts = new HashSet<X509Certificate2>();
HashSet<X509Certificate2> uniqueIntermediateCerts = new HashSet<X509Certificate2>();
foreach (FileInfo file in trustedCertFiles)
{
using (SafeBioHandle fileBio = Interop.Crypto.BioNewFile(file.FullName, "rb"))
{
ICertificatePal pal;
while (CertificatePal.TryReadX509Pem(fileBio, out pal) ||
CertificatePal.TryReadX509Der(fileBio, out pal))
{
X509Certificate2 cert = new X509Certificate2(pal);
// The HashSets are just used for uniqueness filters, they do not survive this method.
if (StringComparer.Ordinal.Equals(cert.Subject, cert.Issuer))
{
if (uniqueRootCerts.Add(cert))
{
rootStore.Add(cert);
continue;
}
}
else
{
if (uniqueIntermediateCerts.Add(cert))
{
intermedStore.Add(cert);
continue;
}
}
// There's a good chance we'll encounter duplicates on systems that have both one-cert-per-file
// and one-big-file trusted certificate stores. Anything that wasn't unique will end up here.
cert.Dispose();
}
}
}
var rootStorePal = new CollectionBackedStoreProvider(rootStore);
s_machineIntermediateStore = new CollectionBackedStoreProvider(intermedStore);
// s_machineRootStore's nullarity is the loaded-state sentinel, so write it with Volatile.
Debug.Assert(Monitor.IsEntered(s_machineLoadLock), "LoadMachineStores assumes a lock(s_machineLoadLock)");
Volatile.Write(ref s_machineRootStore, rootStorePal);
}
private static IEnumerable<T> Append<T>(IEnumerable<T> current, T addition)
{
foreach (T element in current)
yield return element;
yield return addition;
}
}
}
| |
namespace dotless.Core.Importers
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Input;
using Parser;
using Parser.Tree;
using Utils;
using System.Text.RegularExpressions;
using System.Reflection;
public class Importer : IImporter
{
private static readonly Regex _embeddedResourceRegex = new Regex(@"^dll://(?<Assembly>.+?)#(?<Resource>.+)$");
public static Regex EmbeddedResourceRegex { get { return _embeddedResourceRegex; } }
public IFileReader FileReader { get; set; }
/// <summary>
/// List of successful imports
/// </summary>
public List<string> Imports { get; set; }
public Func<Parser> Parser { get; set; }
private readonly List<string> _paths = new List<string>();
/// <summary>
/// The raw imports of every @import node, for use with @import
/// </summary>
protected readonly List<string> _rawImports = new List<string>();
/// <summary>
/// Duplicates of reference imports should be ignored just like normal imports
/// but a reference import must not interfere with a regular import, hence a different list
/// </summary>
private readonly List<string> _referenceImports = new List<string>();
public virtual string CurrentDirectory { get; set; }
/// <summary>
/// Whether or not the importer should alter urls
/// </summary>
public bool IsUrlRewritingDisabled { get; set; }
public string RootPath { get; set; }
/// <summary>
/// Import all files as if they are less regardless of file extension
/// </summary>
public bool ImportAllFilesAsLess { get; set; }
/// <summary>
/// Import the css and include inline
/// </summary>
public bool InlineCssFiles { get; set; }
public Importer() : this(new FileReader())
{
}
public Importer(IFileReader fileReader) : this(fileReader, false, "", false, false)
{
}
public Importer(IFileReader fileReader, bool disableUrlReWriting, string rootPath, bool inlineCssFiles, bool importAllFilesAsLess)
{
FileReader = fileReader;
IsUrlRewritingDisabled = disableUrlReWriting;
RootPath = rootPath;
InlineCssFiles = inlineCssFiles;
ImportAllFilesAsLess = importAllFilesAsLess;
Imports = new List<string>();
CurrentDirectory = "";
}
/// <summary>
/// Whether a url has a protocol on it
/// </summary>
private static bool IsProtocolUrl(string url)
{
return Regex.IsMatch(url, @"^([a-zA-Z]{2,}:)");
}
/// <summary>
/// Whether a url has a protocol on it
/// </summary>
private static bool IsNonRelativeUrl(string url)
{
return url.StartsWith(@"/") || url.StartsWith(@"~/") || Regex.IsMatch(url, @"^[a-zA-Z]:");
}
/// <summary>
/// Whether a url represents an embedded resource
/// </summary>
private static bool IsEmbeddedResource(string path)
{
return _embeddedResourceRegex.IsMatch(path);
}
/// <summary>
/// Get a list of the current paths, used to pass back in to alter url's after evaluation
/// </summary>
/// <returns></returns>
public List<string> GetCurrentPathsClone()
{
return new List<string>(_paths);
}
/// <summary>
/// returns true if the import should be ignored because it is a duplicate and import-once was used
/// </summary>
/// <param name="import"></param>
/// <returns></returns>
protected bool CheckIgnoreImport(Import import)
{
return CheckIgnoreImport(import, import.Path);
}
/// <summary>
/// returns true if the import should be ignored because it is a duplicate and import-once was used
/// </summary>
/// <param name="import"></param>
/// <returns></returns>
protected bool CheckIgnoreImport(Import import, string path)
{
if (IsOptionSet(import.ImportOptions, ImportOptions.Multiple))
{
return false;
}
// The import option Reference is set at parse time,
// but the IsReference bit is set at evaluation time (inherited from parent)
// so we check both.
if (import.IsReference || IsOptionSet(import.ImportOptions, ImportOptions.Reference))
{
if (_rawImports.Contains(path, StringComparer.InvariantCultureIgnoreCase))
{
// Already imported as a regular import, so the reference import is redundant
return true;
}
return CheckIgnoreImport(_referenceImports, path);
}
return CheckIgnoreImport(_rawImports, path);
}
private bool CheckIgnoreImport(List<string> importList, string path) {
if (importList.Contains(path, StringComparer.InvariantCultureIgnoreCase))
{
return true;
}
importList.Add(path);
return false;
}
/// <summary>
/// Imports the file inside the import as a dot-less file.
/// </summary>
/// <param name="import"></param>
/// <returns> The action for the import node to process</returns>
public virtual ImportAction Import(Import import)
{
// if the import is protocol'd (e.g. http://www.opencss.com/css?blah) then leave the import alone
if (IsProtocolUrl(import.Path) && !IsEmbeddedResource(import.Path))
{
if (import.Path.EndsWith(".less"))
{
throw new FileNotFoundException(string.Format(".less cannot import non local less files [{0}].", import.Path), import.Path);
}
if (CheckIgnoreImport(import))
{
return ImportAction.ImportNothing;
}
return ImportAction.LeaveImport;
}
var file = import.Path;
if (!IsNonRelativeUrl(file))
{
file = GetAdjustedFilePath(import.Path, _paths);
}
if (CheckIgnoreImport(import, file))
{
return ImportAction.ImportNothing;
}
bool importAsless = ImportAllFilesAsLess || IsOptionSet(import.ImportOptions, ImportOptions.Less);
if (!importAsless && import.Path.EndsWith(".css") && !import.Path.EndsWith(".less.css"))
{
if (InlineCssFiles || IsOptionSet(import.ImportOptions, ImportOptions.Inline))
{
if (IsEmbeddedResource(import.Path) && ImportEmbeddedCssContents(file, import))
return ImportAction.ImportCss;
if (ImportCssFileContents(file, import))
return ImportAction.ImportCss;
}
return ImportAction.LeaveImport;
}
if (Parser == null)
throw new InvalidOperationException("Parser cannot be null.");
if (!ImportLessFile(file, import))
{
if (IsOptionSet(import.ImportOptions, ImportOptions.Optional))
{
return ImportAction.ImportNothing;
}
if (IsOptionSet(import.ImportOptions, ImportOptions.Css))
{
return ImportAction.LeaveImport;
}
if (import.Path.EndsWith(".less", StringComparison.InvariantCultureIgnoreCase))
{
throw new FileNotFoundException(string.Format("You are importing a file ending in .less that cannot be found [{0}].", file), file);
}
return ImportAction.LeaveImport;
}
return ImportAction.ImportLess;
}
public IDisposable BeginScope(Import parentScope) {
return new ImportScope(this, Path.GetDirectoryName(parentScope.Path));
}
/// <summary>
/// Uses the paths to adjust the file path
/// </summary>
protected string GetAdjustedFilePath(string path, IEnumerable<string> pathList)
{
return pathList.Concat(new[] { path }).AggregatePaths(CurrentDirectory);
}
/// <summary>
/// Imports a less file and puts the root into the import node
/// </summary>
protected bool ImportLessFile(string lessPath, Import import)
{
string contents, file = null;
if (IsEmbeddedResource(lessPath))
{
contents = ResourceLoader.GetResource(lessPath, FileReader, out file);
if (contents == null) return false;
}
else
{
string fullName = lessPath;
if (!string.IsNullOrEmpty(CurrentDirectory)) {
fullName = CurrentDirectory.Replace(@"\", "/").TrimEnd('/') + '/' + lessPath;
}
bool fileExists = FileReader.DoesFileExist(fullName);
if (!fileExists && !fullName.EndsWith(".less"))
{
fullName += ".less";
fileExists = FileReader.DoesFileExist(fullName);
}
if (!fileExists) return false;
contents = FileReader.GetFileContents(fullName);
file = fullName;
}
_paths.Add(Path.GetDirectoryName(import.Path));
try
{
if (!string.IsNullOrEmpty(file))
{
Imports.Add(file);
}
import.InnerRoot = Parser().Parse(contents, lessPath);
}
catch
{
Imports.Remove(file);
throw;
}
finally
{
_paths.RemoveAt(_paths.Count - 1);
}
return true;
}
/// <summary>
/// Imports a css file from an embedded resource and puts the contents into the import node
/// </summary>
/// <param name="file"></param>
/// <param name="import"></param>
/// <returns></returns>
private bool ImportEmbeddedCssContents(string file, Import import)
{
string content = ResourceLoader.GetResource(file, FileReader, out file);
if (content == null) return false;
import.InnerContent = content;
return true;
}
/// <summary>
/// Imports a css file and puts the contents into the import node
/// </summary>
protected bool ImportCssFileContents(string file, Import import)
{
if (!FileReader.DoesFileExist(file))
{
return false;
}
import.InnerContent = FileReader.GetFileContents(file);
Imports.Add(file);
return true;
}
/// <summary>
/// Called for every Url and allows the importer to adjust relative url's to be relative to the
/// primary url
/// </summary>
public string AlterUrl(string url, List<string> pathList)
{
if (!IsProtocolUrl (url) && !IsNonRelativeUrl (url))
{
if (pathList.Any() && !IsUrlRewritingDisabled)
{
url = GetAdjustedFilePath(url, pathList);
}
return RootPath + url;
}
return url;
}
private class ImportScope : IDisposable {
private readonly Importer importer;
public ImportScope(Importer importer, string path) {
this.importer = importer;
this.importer._paths.Add(path);
}
public void Dispose() {
this.importer._paths.RemoveAt(this.importer._paths.Count - 1);
}
}
private bool IsOptionSet(ImportOptions options, ImportOptions test)
{
return (options & test) == test;
}
}
/// <summary>
/// Utility class used to retrieve the content of an embedded resource using a separate app domain in order to unload the assembly when done.
/// </summary>
class ResourceLoader : MarshalByRefObject
{
private byte[] _fileContents;
private string _resourceName;
private string _resourceContent;
/// <summary>
/// Gets the text content of an embedded resource.
/// </summary>
/// <param name="file">The path in the form: dll://AssemblyName#ResourceName</param>
/// <returns>The content of the resource</returns>
public static string GetResource(string file, IFileReader fileReader, out string fileDependency)
{
fileDependency = null;
var match = Importer.EmbeddedResourceRegex.Match(file);
if (!match.Success) return null;
var loader = new ResourceLoader();
loader._resourceName = match.Groups["Resource"].Value;
try
{
fileDependency = match.Groups["Assembly"].Value;
LoadFromCurrentAppDomain(loader, fileDependency);
if (String.IsNullOrEmpty(loader._resourceContent))
LoadFromNewAppDomain(loader, fileReader, fileDependency);
}
catch (Exception)
{
throw new FileNotFoundException("Unable to load resource [" + loader._resourceName + "] in assembly [" + fileDependency + "]");
}
finally
{
loader._fileContents = null;
}
return loader._resourceContent;
}
private static void LoadFromCurrentAppDomain(ResourceLoader loader, String assemblyName)
{
foreach (var assembly in AppDomain.CurrentDomain
.GetAssemblies()
.Where(x => !IsDynamicAssembly(x) && x.Location.EndsWith(assemblyName, StringComparison.InvariantCultureIgnoreCase)))
{
if (assembly.GetManifestResourceNames().Contains(loader._resourceName))
{
using (var stream = assembly.GetManifestResourceStream(loader._resourceName))
using (var reader = new StreamReader(stream))
{
loader._resourceContent = reader.ReadToEnd();
if (!String.IsNullOrEmpty(loader._resourceContent))
return;
}
}
}
}
private static bool IsDynamicAssembly(Assembly assembly) {
try {
string loc = assembly.Location;
return false;
} catch (NotSupportedException) {
// Location is not supported for dynamic assemblies, so it will throw a NotSupportedException
return true;
}
}
private static void LoadFromNewAppDomain(ResourceLoader loader, IFileReader fileReader, String assemblyName)
{
if (!fileReader.DoesFileExist(assemblyName))
{
throw new FileNotFoundException("Unable to locate assembly file [" + assemblyName + "]");
}
loader._fileContents = fileReader.GetBinaryFileContents(assemblyName);
var domainSetup = new AppDomainSetup();
domainSetup.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var domain = AppDomain.CreateDomain("LoaderDomain", null, domainSetup);
domain.DoCallBack(loader.LoadResource);
AppDomain.Unload(domain);
}
// Runs in the separate app domain
private void LoadResource()
{
var assembly = Assembly.Load(_fileContents);
using (var stream = assembly.GetManifestResourceStream(_resourceName))
using (var reader = new StreamReader(stream))
{
_resourceContent = reader.ReadToEnd();
}
}
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2016 Colin Green ([email protected])
*
* SharpNEAT is free software; you can redistribute it and/or modify
* it under the terms of The MIT License (MIT).
*
* You should have received a copy of the MIT License
* along with SharpNEAT; if not, see https://opensource.org/licenses/MIT.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Xml;
using SharpNeat.Network;
using SharpNeat.Utility;
namespace SharpNeat.Genomes.Neat
{
/// <summary>
/// Static class for reading and writing NeatGenome(s) to and from XML.
/// </summary>
public static class NeatGenomeXmlIO
{
#region Constants [XML Strings]
const string __ElemRoot = "Root";
const string __ElemNetworks = "Networks";
const string __ElemNetwork = "Network";
const string __ElemNodes = "Nodes";
const string __ElemNode = "Node";
const string __ElemConnections = "Connections";
const string __ElemConnection = "Con";
const string __ElemActivationFunctions = "ActivationFunctions";
const string __AttrId = "id";
const string __AttrBirthGeneration = "birthGen";
const string __AttrFitness = "fitness";
const string __AttrType = "type";
const string __AttrSourceId = "src";
const string __AttrTargetId = "tgt";
const string __AttrWeight = "wght";
const string __AttrActivationFunctionId = "fnId";
const string __AttrAuxState = "aux";
#endregion
#region Public Static Methods [Save to XmlDocument]
/// <summary>
/// Writes a single NeatGenome to XML within a containing 'Root' element and the activation function
/// library that the genome is associated with.
/// The XML is returned as a newly created XmlDocument.
/// </summary>
/// <param name="genome">The genome to save.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static XmlDocument SaveComplete(NeatGenome genome, bool nodeFnIds)
{
XmlDocument doc = new XmlDocument();
using(XmlWriter xw = doc.CreateNavigator().AppendChild())
{
WriteComplete(xw, genome, nodeFnIds);
}
return doc;
}
/// <summary>
/// Writes a list of NeatGenome(s) to XML within a containing 'Root' element and the activation
/// function library that the genomes are associated with.
/// The XML is returned as a newly created XmlDocument.
/// </summary>
/// <param name="genomeList">List of genomes to write as XML.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static XmlDocument SaveComplete(IList<NeatGenome> genomeList, bool nodeFnIds)
{
XmlDocument doc = new XmlDocument();
using(XmlWriter xw = doc.CreateNavigator().AppendChild())
{
WriteComplete(xw, genomeList, nodeFnIds);
}
return doc;
}
/// <summary>
/// Writes a single NeatGenome to XML.
/// The XML is returned as a newly created XmlDocument.
/// </summary>
/// <param name="genome">The genome to save.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static XmlDocument Save(NeatGenome genome, bool nodeFnIds)
{
XmlDocument doc = new XmlDocument();
using(XmlWriter xw = doc.CreateNavigator().AppendChild())
{
Write(xw, genome, nodeFnIds);
}
return doc;
}
#endregion
#region Public Static Methods [Load from XmlDocument]
/// <summary>
/// Loads a list of NeatGenome(s) from XML that has a containing 'Root' element. The root element
/// also contains the activation function library that the network definitions are associated with.
/// </summary>
/// <param name="xmlNode">The XmlNode to read from. This can be an XmlDocument or XmlElement.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be read. If false then
/// all node activation function IDs default to 0.</param>
/// <param name="genomeFactory">A NeatGenomeFactory object to construct genomes against.</param>
public static List<NeatGenome> LoadCompleteGenomeList(XmlNode xmlNode, bool nodeFnIds, NeatGenomeFactory genomeFactory)
{
using(XmlNodeReader xr = new XmlNodeReader(xmlNode))
{
return ReadCompleteGenomeList(xr, nodeFnIds, genomeFactory);
}
}
/// <summary>
/// Reads a NeatGenome from XML.
/// </summary>
/// <param name="xmlNode">The XmlNode to read from. This can be an XmlDocument or XmlElement.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be read. They are required
/// for HyperNEAT genomes but not for NEAT</param>
public static NeatGenome LoadGenome(XmlNode xmlNode, bool nodeFnIds)
{
using(XmlNodeReader xr = new XmlNodeReader(xmlNode))
{
return ReadGenome(xr, nodeFnIds);
}
}
#endregion
#region Public Static Methods [Write to XML]
/// <summary>
/// Writes a list of NeatGenome(s) to XML within a containing 'Root' element and the activation
/// function library that the genomes are associated with.
/// </summary>
/// <param name="xw">XmlWriter to write XML to.</param>
/// <param name="genomeList">List of genomes to write as XML.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static void WriteComplete(XmlWriter xw, IList<NeatGenome> genomeList, bool nodeFnIds)
{
if(genomeList.Count == 0)
{ // Nothing to do.
return;
}
// <Root>
xw.WriteStartElement(__ElemRoot);
// Write activation function library from the first genome.
// (we expect all genomes to use the same library).
IActivationFunctionLibrary activationFnLib = genomeList[0].ActivationFnLibrary;
NetworkXmlIO.Write(xw, activationFnLib);
// <Networks>
xw.WriteStartElement(__ElemNetworks);
// Write genomes.
foreach(NeatGenome genome in genomeList) {
Debug.Assert(genome.ActivationFnLibrary == activationFnLib);
Write(xw, genome, nodeFnIds);
}
// </Networks>
xw.WriteEndElement();
// </Root>
xw.WriteEndElement();
}
/// <summary>
/// Writes a single NeatGenome to XML within a containing 'Root' element and the activation
/// function library that the genome is associated with.
/// </summary>
/// <param name="xw">XmlWriter to write XML to.</param>
/// <param name="genome">Genome to write as XML.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static void WriteComplete(XmlWriter xw, NeatGenome genome, bool nodeFnIds)
{
// <Root>
xw.WriteStartElement(__ElemRoot);
// Write activation function library.
NetworkXmlIO.Write(xw, genome.ActivationFnLibrary);
// <Networks>
xw.WriteStartElement(__ElemNetworks);
// Write single genome.
Write(xw, genome, nodeFnIds);
// </Networks>
xw.WriteEndElement();
// </Root>
xw.WriteEndElement();
}
/// <summary>
/// Writes a NeatGenome to XML.
/// </summary>
/// <param name="xw">XmlWriter to write XML to.</param>
/// <param name="genome">Genome to write as XML.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be emitted. They are required
/// for HyperNEAT genomes but not for NEAT.</param>
public static void Write(XmlWriter xw, NeatGenome genome, bool nodeFnIds)
{
xw.WriteStartElement(__ElemNetwork);
xw.WriteAttributeString(__AttrId, genome.Id.ToString(NumberFormatInfo.InvariantInfo));
xw.WriteAttributeString(__AttrBirthGeneration, genome.BirthGeneration.ToString(NumberFormatInfo.InvariantInfo));
xw.WriteAttributeString(__AttrFitness, genome.EvaluationInfo.Fitness.ToString("R", NumberFormatInfo.InvariantInfo));
// Emit nodes.
StringBuilder sb = new StringBuilder();
xw.WriteStartElement(__ElemNodes);
foreach(NeuronGene nGene in genome.NeuronGeneList)
{
xw.WriteStartElement(__ElemNode);
xw.WriteAttributeString(__AttrType, NetworkXmlIO.GetNodeTypeString(nGene.NodeType));
xw.WriteAttributeString(__AttrId, nGene.Id.ToString(NumberFormatInfo.InvariantInfo));
if(nodeFnIds)
{ // Write activation fn ID.
xw.WriteAttributeString(__AttrActivationFunctionId, nGene.ActivationFnId.ToString(NumberFormatInfo.InvariantInfo));
// Write aux state as comma separated list of real values.
XmlIoUtils.WriteAttributeString(xw, __AttrAuxState, nGene.AuxState);
}
xw.WriteEndElement();
}
xw.WriteEndElement();
// Emit connections.
xw.WriteStartElement(__ElemConnections);
foreach(ConnectionGene cGene in genome.ConnectionList)
{
xw.WriteStartElement(__ElemConnection);
xw.WriteAttributeString(__AttrId, cGene.InnovationId.ToString(NumberFormatInfo.InvariantInfo));
xw.WriteAttributeString(__AttrSourceId, cGene.SourceNodeId.ToString(NumberFormatInfo.InvariantInfo));
xw.WriteAttributeString(__AttrTargetId, cGene.TargetNodeId.ToString(NumberFormatInfo.InvariantInfo));
xw.WriteAttributeString(__AttrWeight, cGene.Weight.ToString("R", NumberFormatInfo.InvariantInfo));
xw.WriteEndElement();
}
xw.WriteEndElement();
// </Network>
xw.WriteEndElement();
}
#endregion
#region Public Static Methods [Read from XML]
/// <summary>
/// Reads a list of NeatGenome(s) from XML that has a containing 'Root' element. The root
/// element also contains the activation function library that the genomes are associated with.
/// </summary>
/// <param name="xr">The XmlReader to read from.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be read. If false then
/// all node activation function IDs default to 0.</param>
/// <param name="genomeFactory">A NeatGenomeFactory object to construct genomes against.</param>
public static List<NeatGenome> ReadCompleteGenomeList(XmlReader xr, bool nodeFnIds, NeatGenomeFactory genomeFactory)
{
// Find <Root>.
XmlIoUtils.MoveToElement(xr, false, __ElemRoot);
// Read IActivationFunctionLibrary. This library is not used, it is compared against the one already present in the
// genome factory to confirm that the loaded genomes are compatible with the genome factory.
XmlIoUtils.MoveToElement(xr, true, __ElemActivationFunctions);
IActivationFunctionLibrary activationFnLib = NetworkXmlIO.ReadActivationFunctionLibrary(xr);
XmlIoUtils.MoveToElement(xr, false, __ElemNetworks);
// Read genomes.
List<NeatGenome> genomeList = new List<NeatGenome>();
using(XmlReader xrSubtree = xr.ReadSubtree())
{
// Re-scan for the root <Networks> element.
XmlIoUtils.MoveToElement(xrSubtree, false);
// Move to first Network elem.
XmlIoUtils.MoveToElement(xrSubtree, true, __ElemNetwork);
// Read Network elements.
do
{
NeatGenome genome = ReadGenome(xrSubtree, nodeFnIds);
genomeList.Add(genome);
}
while(xrSubtree.ReadToNextSibling(__ElemNetwork));
}
// Check for empty list.
if(genomeList.Count == 0) {
return genomeList;
}
// Get the number of inputs and outputs expected by the genome factory.
int inputCount = genomeFactory.InputNeuronCount;
int outputCount = genomeFactory.OutputNeuronCount;
// Check all genomes have the same number of inputs & outputs.
// Also track the highest genomeID and innovation ID values; we need these to construct a new genome factory.
uint maxGenomeId = 0;
uint maxInnovationId = 0;
foreach(NeatGenome genome in genomeList)
{
// Check number of inputs/outputs.
if(genome.InputNeuronCount != inputCount || genome.OutputNeuronCount != outputCount) {
throw new SharpNeatException(string.Format("Genome with wrong number of inputs and/or outputs, expected [{0}][{1}] got [{2}][{3}]",
inputCount, outputCount, genome.InputNeuronCount, genome.OutputNeuronCount));
}
// Track max IDs.
maxGenomeId = Math.Max(maxGenomeId, genome.Id);
// Node and connection innovation IDs are in the same ID space.
foreach(NeuronGene nGene in genome.NeuronGeneList) {
maxInnovationId = Math.Max(maxInnovationId, nGene.InnovationId);
}
// Register connection IDs.
foreach(ConnectionGene cGene in genome.ConnectionGeneList) {
maxInnovationId = Math.Max(maxInnovationId, cGene.InnovationId);
}
}
// Check that activation functions in XML match that in the genome factory.
IList<ActivationFunctionInfo> loadedActivationFnList = activationFnLib.GetFunctionList();
IList<ActivationFunctionInfo> factoryActivationFnList = genomeFactory.ActivationFnLibrary.GetFunctionList();
if(loadedActivationFnList.Count != factoryActivationFnList.Count) {
throw new SharpNeatException("The activation function library loaded from XML does not match the genome factory's activation function library.");
}
for(int i=0; i<factoryActivationFnList.Count; i++)
{
if( (loadedActivationFnList[i].Id != factoryActivationFnList[i].Id)
|| (loadedActivationFnList[i].ActivationFunction.FunctionId != factoryActivationFnList[i].ActivationFunction.FunctionId)) {
throw new SharpNeatException("The activation function library loaded from XML does not match the genome factory's activation function library.");
}
}
// Initialise the genome factory's genome and innovation ID generators.
genomeFactory.GenomeIdGenerator.Reset(Math.Max(genomeFactory.GenomeIdGenerator.Peek, maxGenomeId+1));
genomeFactory.InnovationIdGenerator.Reset(Math.Max(genomeFactory.InnovationIdGenerator.Peek, maxInnovationId+1));
// Retrospectively assign the genome factory to the genomes. This is how we overcome the genome/genomeFactory
// chicken and egg problem.
foreach(NeatGenome genome in genomeList) {
genome.GenomeFactory = genomeFactory;
}
return genomeList;
}
/// <summary>
/// Reads a NeatGenome from XML.
/// </summary>
/// <param name="xr">The XmlReader to read from.</param>
/// <param name="nodeFnIds">Indicates if node activation function IDs should be read. They are required
/// for HyperNEAT genomes but not for NEAT</param>
public static NeatGenome ReadGenome(XmlReader xr, bool nodeFnIds)
{
// Find <Network>.
XmlIoUtils.MoveToElement(xr, false, __ElemNetwork);
int initialDepth = xr.Depth;
// Read genome ID attribute if present. Otherwise default to zero; it's the caller's responsibility to
// check IDs are unique and in-line with the genome factory's ID generators.
string genomeIdStr = xr.GetAttribute(__AttrId);
uint genomeId;
uint.TryParse(genomeIdStr, out genomeId);
// Read birthGeneration attribute if present. Otherwise default to zero.
string birthGenStr = xr.GetAttribute(__AttrBirthGeneration);
uint birthGen;
uint.TryParse(birthGenStr, out birthGen);
// Find <Nodes>.
XmlIoUtils.MoveToElement(xr, true, __ElemNodes);
// Create a reader over the <Nodes> sub-tree.
int inputNodeCount = 0;
int outputNodeCount = 0;
NeuronGeneList nGeneList = new NeuronGeneList();
using(XmlReader xrSubtree = xr.ReadSubtree())
{
// Re-scan for the root <Nodes> element.
XmlIoUtils.MoveToElement(xrSubtree, false);
// Move to first node elem.
XmlIoUtils.MoveToElement(xrSubtree, true, __ElemNode);
// Read node elements.
do
{
NodeType neuronType = NetworkXmlIO.ReadAttributeAsNodeType(xrSubtree, __AttrType);
uint id = XmlIoUtils.ReadAttributeAsUInt(xrSubtree, __AttrId);
int functionId = 0;
double[] auxState = null;
if(nodeFnIds)
{ // Read activation fn ID.
functionId = XmlIoUtils.ReadAttributeAsInt(xrSubtree, __AttrActivationFunctionId);
// Read aux state as comma separated list of real values.
auxState = XmlIoUtils.ReadAttributeAsDoubleArray(xrSubtree, __AttrAuxState);
}
NeuronGene nGene = new NeuronGene(id, neuronType, functionId, auxState);
nGeneList.Add(nGene);
// Track the number of input and output nodes.
switch(neuronType)
{
case NodeType.Input:
inputNodeCount++;
break;
case NodeType.Output:
outputNodeCount++;
break;
}
}
while(xrSubtree.ReadToNextSibling(__ElemNode));
}
// Find <Connections>.
XmlIoUtils.MoveToElement(xr, false, __ElemConnections);
// Create a reader over the <Connections> sub-tree.
ConnectionGeneList cGeneList = new ConnectionGeneList();
using(XmlReader xrSubtree = xr.ReadSubtree())
{
// Re-scan for the root <Connections> element.
XmlIoUtils.MoveToElement(xrSubtree, false);
// Move to first connection elem.
string localName = XmlIoUtils.MoveToElement(xrSubtree, true);
if(localName == __ElemConnection)
{ // We have at least one connection.
// Read connection elements.
do
{
uint id = XmlIoUtils.ReadAttributeAsUInt(xrSubtree, __AttrId);
uint srcId = XmlIoUtils.ReadAttributeAsUInt(xrSubtree, __AttrSourceId);
uint tgtId = XmlIoUtils.ReadAttributeAsUInt(xrSubtree, __AttrTargetId);
double weight = XmlIoUtils.ReadAttributeAsDouble(xrSubtree, __AttrWeight);
ConnectionGene cGene = new ConnectionGene(id, srcId, tgtId, weight);
cGeneList.Add(cGene);
}
while(xrSubtree.ReadToNextSibling(__ElemConnection));
}
}
// Move the reader beyond the closing tags </Connections> and </Network>.
do
{
if (xr.Depth <= initialDepth) {
break;
}
}
while(xr.Read());
// Construct and return loaded NeatGenome.
return new NeatGenome(null, genomeId, birthGen, nGeneList, cGeneList, inputNodeCount, outputNodeCount, true);
}
#endregion
}
}
| |
// MvxRestClient.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, [email protected]
using MvvmCross.Platform;
using MvvmCross.Platform.Exceptions;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace MvvmCross.Plugins.Network.Rest
{
[Preserve(AllMembers = true)]
public class MvxRestClient : IMvxRestClient
{
protected static void TryCatch(Action toTry, Action<Exception> errorAction)
{
try
{
toTry();
}
catch (Exception exception)
{
errorAction?.Invoke(exception);
}
}
protected Dictionary<string, object> Options { set; private get; }
public MvxRestClient()
{
Options = new Dictionary<string, object>
{
{MvxKnownOptions.ForceWindowsPhoneToUseCompression, "true"}
};
}
public void ClearSetting(string key)
{
try
{
Options.Remove(key);
}
catch (KeyNotFoundException)
{
// ignored - not a problem
}
}
public void SetSetting(string key, object value)
{
Options[key] = value;
}
public IMvxAbortable MakeRequest(MvxRestRequest restRequest, Action<MvxStreamRestResponse> successAction, Action<Exception> errorAction)
{
HttpWebRequest httpRequest = null;
TryCatch(() =>
{
httpRequest = BuildHttpRequest(restRequest);
Action processResponse = () => ProcessResponse(restRequest, httpRequest, successAction, errorAction);
if (restRequest.NeedsRequestStream)
{
ProcessRequestThen(restRequest, httpRequest, processResponse, errorAction);
}
else
{
processResponse();
}
}, errorAction);
return httpRequest != null ? new MvxRestRequestAsyncHandle(httpRequest) : null;
}
public IMvxAbortable MakeRequest(MvxRestRequest restRequest, Action<MvxRestResponse> successAction, Action<Exception> errorAction)
{
HttpWebRequest httpRequest = null;
TryCatch(() =>
{
httpRequest = BuildHttpRequest(restRequest);
Action processResponse = () => ProcessResponse(restRequest, httpRequest, successAction, errorAction);
if (restRequest.NeedsRequestStream)
{
ProcessRequestThen(restRequest, httpRequest, processResponse, errorAction);
}
else
{
processResponse();
}
}, errorAction);
return httpRequest != null ? new MvxRestRequestAsyncHandle(httpRequest) : null;
}
public Task<MvxStreamRestResponse> MakeStreamRequestAsync(MvxRestRequest restRequest, CancellationToken cancellationToken = default(CancellationToken))
{
TaskCompletionSource<MvxStreamRestResponse> taskCompletionSource = new TaskCompletionSource<MvxStreamRestResponse>();
HttpWebRequest httpRequest = BuildHttpRequest(restRequest);
using (CancellationTokenRegistration tokenRegistration = cancellationToken.Register(() =>
{
httpRequest.Abort();
taskCompletionSource.SetCanceled();
}))
{
Action processResponse = () => ProcessStreamResponse(restRequest, httpRequest, response => taskCompletionSource.SetResult(response));
Action<Exception> processExceptionResponse = (ex) => ProcessStreamExceptionResponse(restRequest, ex, response => taskCompletionSource.SetResult(response));
if (restRequest.NeedsRequestStream)
{
ProcessRequestThen(restRequest, httpRequest, processResponse, processExceptionResponse);
}
else
{
processResponse();
}
}
return taskCompletionSource.Task;
}
public Task<MvxRestResponse> MakeRequestAsync(MvxRestRequest restRequest, CancellationToken cancellationToken = default(CancellationToken))
{
TaskCompletionSource<MvxRestResponse> taskCompletionSource = new TaskCompletionSource<MvxRestResponse>();
HttpWebRequest httpRequest = BuildHttpRequest(restRequest);
using (CancellationTokenRegistration tokenRegistration = cancellationToken.Register(() =>
{
httpRequest.Abort();
taskCompletionSource.SetCanceled();
}))
{
Action processResponse = () => ProcessResponse(restRequest, httpRequest, response => taskCompletionSource.SetResult(response));
Action<Exception> processExceptionResponse = (ex) => ProcessExceptionResponse(restRequest, ex, response => taskCompletionSource.SetResult(response));
if (restRequest.NeedsRequestStream)
{
ProcessRequestThen(restRequest, httpRequest, processResponse, processExceptionResponse);
}
else
{
processResponse();
}
}
return taskCompletionSource.Task;
}
protected virtual HttpWebRequest BuildHttpRequest(MvxRestRequest restRequest)
{
var httpRequest = CreateHttpWebRequest(restRequest);
SetMethod(restRequest, httpRequest);
SetContentType(restRequest, httpRequest);
SetUserAgent(restRequest, httpRequest);
SetAccept(restRequest, httpRequest);
SetCookieContainer(restRequest, httpRequest);
SetCredentials(restRequest, httpRequest);
SetCustomHeaders(restRequest, httpRequest);
SetPlatformSpecificProperties(restRequest, httpRequest);
return httpRequest;
}
private static void SetCustomHeaders(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
if (restRequest.Headers != null)
{
foreach (var kvp in restRequest.Headers)
{
httpRequest.Headers[kvp.Key] = kvp.Value;
}
}
}
protected virtual void SetCredentials(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
if (restRequest.Credentials != null)
{
httpRequest.Credentials = restRequest.Credentials;
}
}
protected virtual void SetCookieContainer(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
// note that we don't call
// httpRequest.SupportsCookieContainer
// here - this is because Android complained about this...
try
{
if (restRequest.CookieContainer != null)
{
httpRequest.CookieContainer = restRequest.CookieContainer;
}
}
catch (Exception exception)
{
Mvx.Warning("Error masked during Rest call - cookie creation - {0}", exception.ToLongString());
}
}
protected virtual void SetAccept(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
if (!string.IsNullOrEmpty(restRequest.Accept))
{
httpRequest.Accept = restRequest.Accept;
}
}
protected virtual void SetUserAgent(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
if (!string.IsNullOrEmpty(restRequest.UserAgent))
{
httpRequest.Headers["user-agent"] = restRequest.UserAgent;
}
}
protected virtual void SetContentType(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
if (!string.IsNullOrEmpty(restRequest.ContentType))
{
httpRequest.ContentType = restRequest.ContentType;
}
}
protected virtual void SetMethod(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
httpRequest.Method = restRequest.Verb;
}
protected virtual HttpWebRequest CreateHttpWebRequest(MvxRestRequest restRequest)
{
return (HttpWebRequest)WebRequest.Create(restRequest.Uri);
}
protected virtual void SetPlatformSpecificProperties(MvxRestRequest restRequest, HttpWebRequest httpRequest)
{
// do nothing by default
}
protected virtual void ProcessResponse(MvxRestRequest restRequest, HttpWebRequest httpRequest, Action<MvxRestResponse> successAction)
{
httpRequest.BeginGetResponse(result =>
{
var response = (HttpWebResponse)httpRequest.EndGetResponse(result);
var code = response.StatusCode;
var restResponse = new MvxRestResponse
{
CookieCollection = response.Cookies,
Tag = restRequest.Tag,
StatusCode = code
};
successAction?.Invoke(restResponse);
}, null);
}
protected virtual void ProcessStreamResponse(MvxRestRequest restRequest, HttpWebRequest httpRequest, Action<MvxStreamRestResponse> successAction)
{
httpRequest.BeginGetResponse(result =>
{
var response = (HttpWebResponse)httpRequest.EndGetResponse(result);
var code = response.StatusCode;
var responseStream = response.GetResponseStream();
var restResponse = new MvxStreamRestResponse
{
CookieCollection = response.Cookies,
Stream = responseStream,
Tag = restRequest.Tag,
StatusCode = code
};
successAction?.Invoke(restResponse);
}, null);
}
protected virtual void ProcessStreamExceptionResponse(MvxRestRequest restRequest, Exception ex, Action<MvxStreamRestResponse> continueAction)
{
var restResponse = new MvxStreamRestResponse
{
Tag = restRequest?.Tag,
StatusCode = HttpStatusCode.BadRequest
};
continueAction?.Invoke(restResponse);
}
protected virtual void ProcessExceptionResponse(MvxRestRequest restRequest, Exception ex, Action<MvxRestResponse> continueAction)
{
var restResponse = new MvxRestResponse
{
Tag = restRequest?.Tag,
StatusCode = HttpStatusCode.BadRequest
};
continueAction?.Invoke(restResponse);
}
protected virtual void ProcessRequestThen(MvxRestRequest restRequest, HttpWebRequest httpRequest, Action continueAction)
{
httpRequest.BeginGetRequestStream(result =>
{
using (var stream = httpRequest.EndGetRequestStream(result))
{
restRequest.ProcessRequestStream(stream);
stream.Flush();
}
continueAction?.Invoke();
}, null);
}
protected virtual void ProcessResponse(MvxRestRequest restRequest, HttpWebRequest httpRequest, Action<MvxRestResponse> successAction, Action<Exception> errorAction)
{
httpRequest.BeginGetResponse(result =>
TryCatch(() =>
{
var response = (HttpWebResponse)httpRequest.EndGetResponse(result);
var code = response.StatusCode;
var restResponse = new MvxRestResponse
{
CookieCollection = response.Cookies,
Tag = restRequest.Tag,
StatusCode = code
};
successAction?.Invoke(restResponse);
}, errorAction)
, null);
}
protected virtual void ProcessResponse(MvxRestRequest restRequest, HttpWebRequest httpRequest, Action<MvxStreamRestResponse> successAction, Action<Exception> errorAction)
{
httpRequest.BeginGetResponse(result =>
TryCatch(() =>
{
var response = (HttpWebResponse)httpRequest.EndGetResponse(result);
var code = response.StatusCode;
var responseStream = response.GetResponseStream();
var restResponse = new MvxStreamRestResponse
{
CookieCollection = response.Cookies,
Stream = responseStream,
Tag = restRequest.Tag,
StatusCode = code
};
successAction?.Invoke(restResponse);
}, errorAction)
, null);
}
protected virtual void ProcessRequestThen(MvxRestRequest restRequest, HttpWebRequest httpRequest, Action continueAction, Action<Exception> errorAction)
{
httpRequest.BeginGetRequestStream(result =>
TryCatch(() =>
{
using (var stream = httpRequest.EndGetRequestStream(result))
{
restRequest.ProcessRequestStream(stream);
stream.Flush();
}
continueAction?.Invoke();
}, errorAction)
, 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 System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
/// <summary>
/// A synthesized instance method used for binding
/// expressions outside of a method - specifically, binding
/// DebuggerDisplayAttribute expressions.
/// </summary>
internal sealed class SynthesizedContextMethodSymbol : SynthesizedInstanceMethodSymbol
{
private readonly NamedTypeSymbol _container;
public SynthesizedContextMethodSymbol(NamedTypeSymbol container)
{
_container = container;
}
public override int Arity
{
get { return 0; }
}
public override Symbol AssociatedSymbol
{
get { return null; }
}
public override Symbol ContainingSymbol
{
get { return _container; }
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.NotApplicable; }
}
public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<MethodSymbol>.Empty; }
}
public override bool HidesBaseMethodsByName
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
public override bool IsAsync
{
get { return false; }
}
public override bool IsExtensionMethod
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsSealed
{
get { return true; }
}
public override bool IsStatic
{
get { return false; }
}
public override bool IsVararg
{
get { return false; }
}
public override bool IsVirtual
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { throw ExceptionUtilities.Unreachable; }
}
public override MethodKind MethodKind
{
get { return MethodKind.Ordinary; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return ImmutableArray<ParameterSymbol>.Empty; }
}
public override bool ReturnsVoid
{
get { return true; }
}
internal override RefKind RefKind
{
get { return RefKind.None; }
}
public override TypeSymbol ReturnType
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers
{
get { throw ExceptionUtilities.Unreachable; }
}
public override ImmutableArray<TypeSymbol> TypeArguments
{
get { return ImmutableArray<TypeSymbol>.Empty; }
}
public override ImmutableArray<TypeParameterSymbol> TypeParameters
{
get { return ImmutableArray<TypeParameterSymbol>.Empty; }
}
internal override Microsoft.Cci.CallingConvention CallingConvention
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool GenerateDebugInfo
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool HasDeclarativeSecurity
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool HasSpecialName
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override MethodImplAttributes ImplementationAttributes
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override bool RequiresSecurityObject
{
get { throw ExceptionUtilities.Unreachable; }
}
internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation
{
get { throw ExceptionUtilities.Unreachable; }
}
public override DllImportData GetDllImportData()
{
throw ExceptionUtilities.Unreachable;
}
internal override ImmutableArray<string> GetAppliedConditionalSymbols()
{
throw ExceptionUtilities.Unreachable;
}
internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation()
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsMetadataFinal
{
get
{
return false;
}
}
internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false)
{
throw ExceptionUtilities.Unreachable;
}
internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| |
/*
Copyright 2012 Michael Edwards
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//-CRE-
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Linq;
using System.Threading.Tasks;
using Glass.Mapper.Configuration.Attributes;
namespace Glass.Mapper.Configuration
{
/// <summary>
/// Represents the configuration for a .Net type
/// </summary>
[DebuggerDisplay("Type: {Type}")]
public abstract class AbstractTypeConfiguration
{
private IDictionary<ConstructorInfo, Delegate> _constructorMethods;
private AbstractPropertyConfiguration[] _properties;
/// <summary>
/// The type this configuration represents
/// </summary>
/// <value>The type.</value>
public Type Type { get; set; }
/// <summary>
/// A list of the properties configured on a type
/// </summary>
/// <value>The properties.</value>
public AbstractPropertyConfiguration[] Properties { get { return _properties; } }
/// <summary>
/// A list of the constructors on a type
/// </summary>
/// <value>The constructor methods.</value>
public IDictionary<ConstructorInfo, Delegate> ConstructorMethods { get { return _constructorMethods; } set { _constructorMethods = value;
DefaultConstructor = _constructorMethods.Where(x=>x.Key.GetParameters().Length == 0).Select(x=>x.Value).FirstOrDefault();
} }
/// <summary>
/// This is the classes default constructor
/// </summary>
public Delegate DefaultConstructor { get; private set; }
/// <summary>
/// Indicates properties should be automatically mapped
/// </summary>
public bool AutoMap { get; set; }
/// <summary>
/// Indicates that the type is cachable
/// </summary>
public bool Cachable { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="AbstractTypeConfiguration"/> class.
/// </summary>
public AbstractTypeConfiguration()
{
_properties = new AbstractPropertyConfiguration[]{};
}
/// <summary>
/// Adds the property.
/// </summary>
/// <param name="property">The property.</param>
public virtual void AddProperty(AbstractPropertyConfiguration property)
{
if (property != null)
{
if (_properties.Any(x => x.PropertyInfo.Name == property.PropertyInfo.Name))
{
throw new MapperException(
"You cannot have duplicate mappings for properties. Property Name: {0} Type: {1}".Formatted(
property.PropertyInfo.Name, Type.Name));
}
_properties = _properties.Concat(new[] {property}).ToArray();
_propertMappingExpression = CreatePropertyExpression(property);
}
}
private Action<object, AbstractDataMappingContext> _propertMappingExpression = (obj, context) => { };
protected virtual Action<object, AbstractDataMappingContext> CreatePropertyExpression(
AbstractPropertyConfiguration property)
{
var next = _propertMappingExpression;
return (obj, context) =>
{
try
{
property.Mapper.MapCmsToProperty(context);
}
catch (Exception e)
{
throw new MapperException(
"Failed to map property {0} on {1}".Formatted(property.PropertyInfo.Name,
property.PropertyInfo.DeclaringType.FullName), e);
}
next(obj, context);
};
}
/// <summary>
/// Maps the properties to object.
/// </summary>
/// <param name="obj">The obj.</param>
/// <param name="service">The service.</param>
/// <param name="context">The context.</param>
public void MapPropertiesToObject( object obj, IAbstractService service, AbstractTypeCreationContext context)
{
try
{
//create properties
AbstractDataMappingContext dataMappingContext = service.CreateDataMappingContext(context, obj);
_propertMappingExpression(obj, dataMappingContext);
//var tasks = Properties.Select(x =>
// {
// var t = new Task(() => x.Mapper.MapCmsToProperty(dataMappingContext));
// t.Start();
// return t;
// });
//Task.WaitAll(tasks.ToArray());
//for(int i = Properties.Length-1; i >= 0; i--)
//{
// var prop = Properties[i];
// try
// {
// prop.Mapper.MapCmsToProperty(context);
// }
// catch (Exception e)
// {
// throw new MapperException(
// "Failed to map property {0} on {1}".Formatted(prop.PropertyInfo.Name,
// prop.PropertyInfo.DeclaringType.FullName), e);
// }
//}
}
catch (Exception ex)
{
throw new MapperException(
"Failed to map properties on {0}.".Formatted(context.DataSummary()), ex);
}
}
/// <summary>
/// Called when the AutoMap property is true. Automatically maps un-specified properties.
/// </summary>
public void PerformAutoMap()
{
//we now run the auto-mapping after all the static configuration is loaded
if (AutoMap)
{
//TODO: ME - probably need some binding flags.
var properties = AutoMapProperties(Type);
foreach (var propConfig in properties)
{
AddProperty(propConfig);
}
}
}
/// <summary>
/// Autoes the map properties.
/// </summary>
/// <param name="type">The type.</param>
/// <returns></returns>
public virtual IEnumerable<AbstractPropertyConfiguration> AutoMapProperties(Type type)
{
BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
BindingFlags.FlattenHierarchy;
IEnumerable<PropertyInfo> properties = type.GetProperties(flags);
if (type.IsInterface)
{
foreach (var inter in type.GetInterfaces())
{
properties = properties.Union(inter.GetProperties(flags));
}
}
var propList = new List<AbstractPropertyConfiguration>();
foreach (var property in properties)
{
if (Properties.All(x => x.PropertyInfo != property))
{
//skipped already mapped properties
if(_properties.Any(x=>x.PropertyInfo.Name == property.Name))
continue;
//skip properties that are actually indexers
if (property.GetIndexParameters().Length > 0)
{
continue;
}
//check for an attribute
var propConfig = AttributeTypeLoader.ProcessProperty(property);
if (propConfig == null)
{
//no attribute then automap
propConfig = AutoMapProperty(property);
}
if (propConfig != null)
propList.Add(propConfig);
}
}
return propList;
}
/// <summary>
/// Called to map each property automatically
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
protected virtual AbstractPropertyConfiguration AutoMapProperty(PropertyInfo property)
{
return null;
}
}
}
| |
// 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 Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// RoutesOperations operations.
/// </summary>
internal partial class RoutesOperations : IServiceOperations<NetworkClient>, IRoutesOperations
{
/// <summary>
/// Initializes a new instance of the RoutesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal RoutesOperations(NetworkClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkClient
/// </summary>
public NetworkClient Client { get; private set; }
/// <summary>
/// Deletes the specified route from a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified route from a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Route>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (routeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Route>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route in the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='routeParameters'>
/// Parameters supplied to the create or update route operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<Route>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<Route> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, routeTableName, routeName, routeParameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets all routes in a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Route>>> ListWithHttpMessagesAsync(string resourceGroupName, string routeTableName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Route>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Route>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified route from a route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (routeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates a route in the specified route table.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='routeTableName'>
/// The name of the route table.
/// </param>
/// <param name='routeName'>
/// The name of the route.
/// </param>
/// <param name='routeParameters'>
/// Parameters supplied to the create or update route operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Route>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string routeName, Route routeParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (routeTableName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeTableName");
}
if (routeName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeName");
}
if (routeParameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "routeParameters");
}
if (routeParameters != null)
{
routeParameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("routeTableName", routeTableName);
tracingParameters.Add("routeName", routeName);
tracingParameters.Add("routeParameters", routeParameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/routeTables/{routeTableName}/routes/{routeName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{routeTableName}", System.Uri.EscapeDataString(routeTableName));
_url = _url.Replace("{routeName}", System.Uri.EscapeDataString(routeName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(routeParameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(routeParameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Route>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Route>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all routes in a route table.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Route>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Route>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Route>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace EvanBaCloudIPs.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/*
* 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 NUnit.Framework;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;
using System.Collections.Generic;
namespace QuantConnect.Tests.Common.Data
{
[TestFixture]
public class WickedRenkoConsolidatorTests
{
[Test]
public void WickedOutputTypeIsRenkoBar()
{
var consolidator = new WickedRenkoConsolidator(10.0m);
Assert.AreEqual(typeof(RenkoBar), consolidator.OutputType);
}
[Test]
public void WickedNoFallingRenko()
{
var consolidator = new TestWickedRenkoConsolidator(1.0m);
var renkos = new List<RenkoBar>();
consolidator.DataConsolidated += (sender, renko) =>
renkos.Add(renko);
var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0);
var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1);
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m));
consolidator.Update(new IndicatorDataPoint(tickOn2, 9.1m));
Assert.AreEqual(renkos.Count, 0);
var openRenko = consolidator.OpenRenko();
Assert.AreEqual(openRenko.Open, 10.0m);
Assert.AreEqual(openRenko.High, 10.0m);
Assert.AreEqual(openRenko.Low, 9.1m);
Assert.AreEqual(openRenko.Close, 9.1m);
}
[Test]
public void WickedNoRisingRenko()
{
var consolidator = new TestWickedRenkoConsolidator(1.0m);
var renkos = new List<RenkoBar>();
consolidator.DataConsolidated += (sender, renko) =>
renkos.Add(renko);
var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0);
var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1);
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m));
consolidator.Update(new IndicatorDataPoint(tickOn2, 10.9m));
Assert.AreEqual(renkos.Count, 0);
var openRenko = consolidator.OpenRenko();
Assert.AreEqual(openRenko.Open, 10.0m);
Assert.AreEqual(openRenko.High, 10.9m);
Assert.AreEqual(openRenko.Low, 10.0m);
Assert.AreEqual(openRenko.Close, 10.9m);
}
[Test]
public void WickedNoFallingRenkoKissLimit()
{
var consolidator = new TestWickedRenkoConsolidator(1.0m);
var renkos = new List<RenkoBar>();
consolidator.DataConsolidated += (sender, renko) =>
renkos.Add(renko);
var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0);
var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1);
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m));
consolidator.Update(new IndicatorDataPoint(tickOn2, 9.0m));
Assert.AreEqual(renkos.Count, 0);
var openRenko = consolidator.OpenRenko();
Assert.AreEqual(openRenko.Open, 10.0m);
Assert.AreEqual(openRenko.High, 10.0m);
Assert.AreEqual(openRenko.Low, 9.0m);
Assert.AreEqual(openRenko.Close, 9.0m);
}
[Test]
public void WickedNoRisingRenkoKissLimit()
{
var consolidator = new TestWickedRenkoConsolidator(1.0m);
var renkos = new List<RenkoBar>();
consolidator.DataConsolidated += (sender, renko) =>
renkos.Add(renko);
var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0);
var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1);
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m));
consolidator.Update(new IndicatorDataPoint(tickOn2, 11.0m));
Assert.AreEqual(renkos.Count, 0);
var openRenko = consolidator.OpenRenko();
Assert.AreEqual(openRenko.Open, 10.0m);
Assert.AreEqual(openRenko.High, 11.0m);
Assert.AreEqual(openRenko.Low, 10.0m);
Assert.AreEqual(openRenko.Close, 11.0m);
}
[Test]
public void WickedOneFallingRenko()
{
var consolidator = new TestWickedRenkoConsolidator(1.0m);
var renkos = new List<RenkoBar>();
consolidator.DataConsolidated += (sender, renko) =>
renkos.Add(renko);
var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0);
var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1);
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m));
consolidator.Update(new IndicatorDataPoint(tickOn2, 8.9m));
Assert.AreEqual(renkos.Count, 1);
Assert.AreEqual(renkos[0].Open, 10.0m);
Assert.AreEqual(renkos[0].High, 10.0m);
Assert.AreEqual(renkos[0].Low, 9.0m);
Assert.AreEqual(renkos[0].Close, 9.0m);
Assert.AreEqual(renkos[0].Direction, BarDirection.Falling);
Assert.AreEqual(renkos[0].Spread, 1.0m);
Assert.AreEqual(renkos[0].Start, tickOn1);
Assert.AreEqual(renkos[0].EndTime, tickOn2);
var openRenko = consolidator.OpenRenko();
Assert.AreEqual(openRenko.Start, tickOn2);
Assert.AreEqual(openRenko.EndTime, tickOn2);
Assert.AreEqual(openRenko.Open, 9.0m);
Assert.AreEqual(openRenko.High, 9.0m);
Assert.AreEqual(openRenko.Low, 8.9m);
Assert.AreEqual(openRenko.Close, 8.9m);
}
[Test]
public void WickedOneRisingRenko()
{
var consolidator = new TestWickedRenkoConsolidator(1.0m);
var renkos = new List<RenkoBar>();
consolidator.DataConsolidated += (sender, renko) =>
renkos.Add(renko);
var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0);
var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1);
consolidator.Update(new IndicatorDataPoint(tickOn1, 9.0m));
consolidator.Update(new IndicatorDataPoint(tickOn2, 10.1m));
Assert.AreEqual(renkos.Count, 1);
Assert.AreEqual(renkos[0].Open, 9.0m);
Assert.AreEqual(renkos[0].High, 10.0m);
Assert.AreEqual(renkos[0].Low, 9.0m);
Assert.AreEqual(renkos[0].Close, 10.0m);
Assert.AreEqual(renkos[0].Direction, BarDirection.Rising);
Assert.AreEqual(renkos[0].Spread, 1.0m);
Assert.AreEqual(renkos[0].Start, tickOn1);
Assert.AreEqual(renkos[0].EndTime, tickOn2);
var openRenko = consolidator.OpenRenko();
Assert.AreEqual(openRenko.Start, tickOn2);
Assert.AreEqual(openRenko.EndTime, tickOn2);
Assert.AreEqual(openRenko.Open, 10.0m);
Assert.AreEqual(openRenko.High, 10.1m);
Assert.AreEqual(openRenko.Low, 10.0m);
Assert.AreEqual(openRenko.Close, 10.1m);
}
[Test]
public void WickedTwoFallingThenOneRisingRenkos()
{
var consolidator = new TestWickedRenkoConsolidator(1.0m);
var renkos = new List<RenkoBar>();
consolidator.DataConsolidated += (sender, renko) =>
renkos.Add(renko);
var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0);
var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1);
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.5m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 9.5m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 8.9m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 9.1m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 9.2m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 8.5m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 7.8m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 7.6m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 8.5m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 9.2m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.1m));
Assert.AreEqual(renkos.Count, 3);
Assert.AreEqual(renkos[0].Open, 10.0m);
Assert.AreEqual(renkos[0].High, 10.5m);
Assert.AreEqual(renkos[0].Low, 9.0m);
Assert.AreEqual(renkos[0].Close, 9.0m);
Assert.AreEqual(renkos[0].Direction, BarDirection.Falling);
Assert.AreEqual(renkos[0].Spread, 1.0m);
Assert.AreEqual(renkos[1].Open, 9.0m);
Assert.AreEqual(renkos[1].High, 9.2m);
Assert.AreEqual(renkos[1].Low, 8.0m);
Assert.AreEqual(renkos[1].Close, 8.0m);
Assert.AreEqual(renkos[1].Direction, BarDirection.Falling);
Assert.AreEqual(renkos[1].Spread, 1.0m);
Assert.AreEqual(renkos[2].Open, 9.0m);
Assert.AreEqual(renkos[2].High, 10.0m);
Assert.AreEqual(renkos[2].Low, 7.6m);
Assert.AreEqual(renkos[2].Close, 10.0m);
Assert.AreEqual(renkos[2].Direction, BarDirection.Rising);
Assert.AreEqual(renkos[2].Spread, 1.0m);
var openRenko = consolidator.OpenRenko();
Assert.AreEqual(openRenko.Open, 10.0m);
Assert.AreEqual(openRenko.High, 10.1m);
Assert.AreEqual(openRenko.Low, 10.0m);
Assert.AreEqual(openRenko.Close, 10.1m);
}
[Test]
public void WickedTwoRisingThenOneFallingRenkos()
{
var consolidator = new TestWickedRenkoConsolidator(1.0m);
var renkos = new List<RenkoBar>();
consolidator.DataConsolidated += (sender, renko) =>
renkos.Add(renko);
var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0);
var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1);
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 9.6m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.5m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 11.1m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 11.0m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.7m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 11.6m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 12.3m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 12.3m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 12.4m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 11.5m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 9.9m));
Assert.AreEqual(renkos.Count, 3);
Assert.AreEqual(renkos[0].Open, 10.0m);
Assert.AreEqual(renkos[0].High, 11.0m);
Assert.AreEqual(renkos[0].Low, 9.6m);
Assert.AreEqual(renkos[0].Close, 11.0m);
Assert.AreEqual(renkos[0].Direction, BarDirection.Rising);
Assert.AreEqual(renkos[0].Spread, 1.0m);
Assert.AreEqual(renkos[1].Open, 11.0m);
Assert.AreEqual(renkos[1].High, 12.0m);
Assert.AreEqual(renkos[1].Low, 10.7m);
Assert.AreEqual(renkos[1].Close, 12.0m);
Assert.AreEqual(renkos[1].Direction, BarDirection.Rising);
Assert.AreEqual(renkos[1].Spread, 1.0m);
Assert.AreEqual(renkos[2].Open, 11.0m);
Assert.AreEqual(renkos[2].High, 12.4m);
Assert.AreEqual(renkos[2].Low, 10.0m);
Assert.AreEqual(renkos[2].Close, 10.0m);
Assert.AreEqual(renkos[2].Direction, BarDirection.Falling);
Assert.AreEqual(renkos[2].Spread, 1.0m);
var openRenko = consolidator.OpenRenko();
Assert.AreEqual(openRenko.Open, 10.0m);
Assert.AreEqual(openRenko.High, 10.0m);
Assert.AreEqual(openRenko.Low, 9.9m);
Assert.AreEqual(openRenko.Close, 9.9m);
}
[Test]
public void WickedThreeRisingGapRenkos()
{
var consolidator = new TestWickedRenkoConsolidator(1.0m);
var renkos = new List<RenkoBar>();
consolidator.DataConsolidated += (sender, renko) =>
renkos.Add(renko);
var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0);
var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1);
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m));
consolidator.Update(new IndicatorDataPoint(tickOn2, 14.0m));
Assert.AreEqual(renkos.Count, 3);
Assert.AreEqual(renkos[0].Start, tickOn1);
Assert.AreEqual(renkos[0].EndTime, tickOn2);
Assert.AreEqual(renkos[0].Open, 10.0m);
Assert.AreEqual(renkos[0].High, 11.0m);
Assert.AreEqual(renkos[0].Low, 10.0m);
Assert.AreEqual(renkos[0].Close, 11.0m);
Assert.AreEqual(renkos[0].Direction, BarDirection.Rising);
Assert.AreEqual(renkos[0].Spread, 1.0m);
Assert.AreEqual(renkos[1].Start, tickOn2);
Assert.AreEqual(renkos[1].EndTime, tickOn2);
Assert.AreEqual(renkos[1].Open, 11.0m);
Assert.AreEqual(renkos[1].High, 12.0m);
Assert.AreEqual(renkos[1].Low, 11.0m);
Assert.AreEqual(renkos[1].Close, 12.0m);
Assert.AreEqual(renkos[1].Direction, BarDirection.Rising);
Assert.AreEqual(renkos[1].Spread, 1.0m);
Assert.AreEqual(renkos[2].Start, tickOn2);
Assert.AreEqual(renkos[2].EndTime, tickOn2);
Assert.AreEqual(renkos[2].Open, 12.0m);
Assert.AreEqual(renkos[2].High, 13.0m);
Assert.AreEqual(renkos[2].Low, 12.0m);
Assert.AreEqual(renkos[2].Close, 13.0m);
Assert.AreEqual(renkos[2].Direction, BarDirection.Rising);
Assert.AreEqual(renkos[2].Spread, 1.0m);
var openRenko = consolidator.OpenRenko();
Assert.AreEqual(openRenko.Start, tickOn2);
Assert.AreEqual(openRenko.EndTime, tickOn2);
Assert.AreEqual(openRenko.Open, 13.0m);
Assert.AreEqual(openRenko.High, 14.0m);
Assert.AreEqual(openRenko.Low, 13.0m);
Assert.AreEqual(openRenko.Close, 14.0m);
}
[Test]
public void WickedThreeFallingGapRenkos()
{
var consolidator = new TestWickedRenkoConsolidator(1.0m);
var renkos = new List<RenkoBar>();
consolidator.DataConsolidated += (sender, renko) =>
renkos.Add(renko);
var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0);
var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1);
consolidator.Update(new IndicatorDataPoint(tickOn1, 14.0m));
consolidator.Update(new IndicatorDataPoint(tickOn2, 10.0m));
Assert.AreEqual(renkos.Count, 3);
Assert.AreEqual(renkos[0].Start, tickOn1);
Assert.AreEqual(renkos[0].EndTime, tickOn2);
Assert.AreEqual(renkos[0].Open, 14.0m);
Assert.AreEqual(renkos[0].High, 14.0m);
Assert.AreEqual(renkos[0].Low, 13.0m);
Assert.AreEqual(renkos[0].Close, 13.0m);
Assert.AreEqual(renkos[0].Direction, BarDirection.Falling);
Assert.AreEqual(renkos[0].Spread, 1.0m);
Assert.AreEqual(renkos[1].Start, tickOn2);
Assert.AreEqual(renkos[1].EndTime, tickOn2);
Assert.AreEqual(renkos[1].Open, 13.0m);
Assert.AreEqual(renkos[1].High, 13.0m);
Assert.AreEqual(renkos[1].Low, 12.0m);
Assert.AreEqual(renkos[1].Close, 12.0m);
Assert.AreEqual(renkos[1].Direction, BarDirection.Falling);
Assert.AreEqual(renkos[1].Spread, 1.0);
Assert.AreEqual(renkos[2].Start, tickOn2);
Assert.AreEqual(renkos[2].EndTime, tickOn2);
Assert.AreEqual(renkos[2].Open, 12.0m);
Assert.AreEqual(renkos[2].High, 12.0m);
Assert.AreEqual(renkos[2].Low, 11.0m);
Assert.AreEqual(renkos[2].Close, 11.0m);
Assert.AreEqual(renkos[2].Direction, BarDirection.Falling);
Assert.AreEqual(renkos[2].Spread, 1.0m);
var openRenko = consolidator.OpenRenko();
Assert.AreEqual(openRenko.Open, 11.0m);
Assert.AreEqual(openRenko.High, 11.0m);
Assert.AreEqual(openRenko.Low, 10.0m);
Assert.AreEqual(openRenko.Close, 10.0m);
}
[Test]
public void WickedTwoFallingThenThreeRisingGapRenkos()
{
var consolidator = new TestWickedRenkoConsolidator(1.0m);
var renkos = new List<RenkoBar>();
consolidator.DataConsolidated += (sender, renko) =>
renkos.Add(renko);
var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0);
var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1);
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.5m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 9.5m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 8.9m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 9.1m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 9.2m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 8.5m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 7.8m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 7.6m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 8.5m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 9.2m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 12.1m));
Assert.AreEqual(renkos.Count, 5);
Assert.AreEqual(renkos[0].Open, 10.0m);
Assert.AreEqual(renkos[0].High, 10.5m);
Assert.AreEqual(renkos[0].Low, 9.0m);
Assert.AreEqual(renkos[0].Close, 9.0m);
Assert.AreEqual(renkos[0].Direction, BarDirection.Falling);
Assert.AreEqual(renkos[0].Spread, 1.0m);
Assert.AreEqual(renkos[1].Open, 9.0m);
Assert.AreEqual(renkos[1].High, 9.2m);
Assert.AreEqual(renkos[1].Low, 8.0m);
Assert.AreEqual(renkos[1].Close, 8.0m);
Assert.AreEqual(renkos[1].Direction, BarDirection.Falling);
Assert.AreEqual(renkos[1].Spread, 1.0m);
Assert.AreEqual(renkos[2].Open, 9.0m);
Assert.AreEqual(renkos[2].High, 10.0m);
Assert.AreEqual(renkos[2].Low, 7.6m);
Assert.AreEqual(renkos[2].Close, 10.0m);
Assert.AreEqual(renkos[2].Direction, BarDirection.Rising);
Assert.AreEqual(renkos[2].Spread, 1.0m);
Assert.AreEqual(renkos[3].Open, 10.0m);
Assert.AreEqual(renkos[3].High, 11.0m);
Assert.AreEqual(renkos[3].Low, 10.0m);
Assert.AreEqual(renkos[3].Close, 11.0m);
Assert.AreEqual(renkos[3].Direction, BarDirection.Rising);
Assert.AreEqual(renkos[3].Spread, 1.0m);
Assert.AreEqual(renkos[4].Open, 11.0m);
Assert.AreEqual(renkos[4].High, 12.0m);
Assert.AreEqual(renkos[4].Low, 11.0m);
Assert.AreEqual(renkos[4].Close, 12.0m);
Assert.AreEqual(renkos[4].Direction, BarDirection.Rising);
Assert.AreEqual(renkos[4].Spread, 1.0m);
var openRenko = consolidator.OpenRenko();
Assert.AreEqual(openRenko.Open, 12.0m);
Assert.AreEqual(openRenko.High, 12.1m);
Assert.AreEqual(openRenko.Low, 12.0m);
Assert.AreEqual(openRenko.Close, 12.1m);
}
[Test]
public void WickedTwoRisingThenThreeFallingGapRenkos()
{
var consolidator = new TestWickedRenkoConsolidator(1.0m);
var renkos = new List<RenkoBar>();
consolidator.DataConsolidated += (sender, renko) =>
renkos.Add(renko);
var tickOn1 = new DateTime(2016, 1, 1, 17, 0, 0, 0);
var tickOn2 = new DateTime(2016, 1, 1, 17, 0, 0, 1);
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.0m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 9.6m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.5m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 11.1m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 11.0m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 10.7m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 11.6m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 12.3m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 12.3m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 12.4m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 11.5m));
consolidator.Update(new IndicatorDataPoint(tickOn1, 7.9m));
Assert.AreEqual(renkos.Count, 5);
Assert.AreEqual(renkos[0].Open, 10.0);
Assert.AreEqual(renkos[0].High, 11.0);
Assert.AreEqual(renkos[0].Low, 9.6);
Assert.AreEqual(renkos[0].Close, 11.0);
Assert.AreEqual(renkos[0].Direction, BarDirection.Rising);
Assert.AreEqual(renkos[0].Spread, 1.0);
Assert.AreEqual(renkos[1].Open, 11.0);
Assert.AreEqual(renkos[1].High, 12.0);
Assert.AreEqual(renkos[1].Low, 10.7);
Assert.AreEqual(renkos[1].Close, 12.0);
Assert.AreEqual(renkos[1].Direction, BarDirection.Rising);
Assert.AreEqual(renkos[1].Spread, 1.0);
Assert.AreEqual(renkos[2].Open, 11.0);
Assert.AreEqual(renkos[2].High, 12.4);
Assert.AreEqual(renkos[2].Low, 10.0);
Assert.AreEqual(renkos[2].Close, 10.0);
Assert.AreEqual(renkos[2].Direction, BarDirection.Falling);
Assert.AreEqual(renkos[2].Spread, 1.0);
Assert.AreEqual(renkos[3].Open, 10.0);
Assert.AreEqual(renkos[3].High, 10.0);
Assert.AreEqual(renkos[3].Low, 9.0);
Assert.AreEqual(renkos[3].Close, 9.0);
Assert.AreEqual(renkos[3].Direction, BarDirection.Falling);
Assert.AreEqual(renkos[3].Spread, 1.0);
Assert.AreEqual(renkos[4].Open, 9.0);
Assert.AreEqual(renkos[4].High, 9.0);
Assert.AreEqual(renkos[4].Low, 8.0);
Assert.AreEqual(renkos[4].Close, 8.0);
Assert.AreEqual(renkos[4].Direction, BarDirection.Falling);
Assert.AreEqual(renkos[4].Spread, 1.0);
var openRenko = consolidator.OpenRenko();
Assert.AreEqual(openRenko.Open, 8.0);
Assert.AreEqual(openRenko.High, 8.0);
Assert.AreEqual(openRenko.Low, 7.9);
Assert.AreEqual(openRenko.Close, 7.9);
}
[Test]
public void ConsistentRenkos()
{
// Reproduce issue #5479
// Test Renko bar consistency amongst three consolidators starting at different times
var time = new DateTime(2016, 1, 1);
var testValues = new List<decimal>
{
1.38687m, 1.38688m, 1.38687m, 1.38686m, 1.38685m, 1.38683m,
1.38682m, 1.38682m, 1.38684m, 1.38682m, 1.38682m, 1.38680m,
1.38681m, 1.38686m, 1.38688m, 1.38688m, 1.38690m, 1.38690m,
1.38691m, 1.38692m, 1.38694m, 1.38695m, 1.38697m, 1.38697m,
1.38700m, 1.38699m, 1.38699m, 1.38699m, 1.38698m, 1.38699m,
1.38697m, 1.38698m, 1.38698m, 1.38697m, 1.38698m, 1.38698m,
1.38697m, 1.38697m, 1.38700m, 1.38702m, 1.38701m, 1.38699m,
1.38697m, 1.38698m, 1.38696m, 1.38698m, 1.38697m, 1.38695m,
1.38695m, 1.38696m, 1.38693m, 1.38692m, 1.38693m, 1.38693m,
1.38692m, 1.38693m, 1.38692m, 1.38690m, 1.38686m, 1.38685m,
1.38687m, 1.38686m, 1.38686m, 1.38686m, 1.38686m, 1.38685m,
1.38684m, 1.38678m, 1.38679m, 1.38680m, 1.38680m, 1.38681m,
1.38685m, 1.38685m, 1.38683m, 1.38682m, 1.38682m, 1.38683m,
1.38682m, 1.38683m, 1.38682m, 1.38681m, 1.38680m, 1.38681m,
1.38681m, 1.38681m, 1.38682m, 1.38680m, 1.38679m, 1.38678m,
1.38675m, 1.38678m, 1.38678m, 1.38678m, 1.38682m, 1.38681m,
1.38682m, 1.38680m, 1.38682m, 1.38683m, 1.38685m, 1.38683m,
1.38683m, 1.38684m, 1.38683m, 1.38683m, 1.38684m, 1.38685m,
1.38684m, 1.38683m, 1.38686m, 1.38685m, 1.38685m, 1.38684m,
1.38685m, 1.38682m, 1.38684m, 1.38683m, 1.38682m, 1.38683m,
1.38685m, 1.38685m, 1.38685m, 1.38683m, 1.38685m, 1.38684m,
1.38686m, 1.38693m, 1.38695m, 1.38693m, 1.38694m, 1.38693m,
1.38692m, 1.38693m, 1.38695m, 1.38697m, 1.38698m, 1.38695m,
1.38696m
};
var consolidator1 = new WickedRenkoConsolidator(0.0001m);
var consolidator2 = new WickedRenkoConsolidator(0.0001m);
var consolidator3 = new WickedRenkoConsolidator(0.0001m);
// Update each of our consolidators starting at different indexes of test values
for (int i = 0; i < testValues.Count; i++)
{
var data = new IndicatorDataPoint(time.AddSeconds(i), testValues[i]);
consolidator1.Update(data);
if (i > 10)
{
consolidator2.Update(data);
}
if (i > 20)
{
consolidator3.Update(data);
}
}
// Assert that consolidator 2 and 3 price is the same as 1. Even though they started at different
// indexes they should be the same
var bar1 = consolidator1.Consolidated as RenkoBar;
var bar2 = consolidator2.Consolidated as RenkoBar;
var bar3 = consolidator3.Consolidated as RenkoBar;
Assert.AreEqual(bar1.Close, bar2.Close);
Assert.AreEqual(bar1.Close, bar3.Close);
consolidator1.Dispose();
consolidator2.Dispose();
consolidator3.Dispose();
}
private class TestWickedRenkoConsolidator : WickedRenkoConsolidator
{
public TestWickedRenkoConsolidator(decimal barSize)
: base(barSize)
{
}
public RenkoBar OpenRenko()
{
return new RenkoBar(null, OpenOn, CloseOn, BarSize, OpenRate, HighRate, LowRate, CloseRate);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#region StyleCop Suppression - generated code
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
namespace Microsoft.Management.UI.Internal
{
/// <summary>
/// A popup which child controls can signal to be dimissed.
/// </summary>
/// <remarks>
/// If a control wants to dismiss the popup then they should execute the DismissPopupCommand on a target in the popup window.
/// </remarks>
[Localizability(LocalizationCategory.None)]
partial class DismissiblePopup
{
//
// DismissPopup routed command
//
/// <summary>
/// A command which child controls can use to tell the popup to close.
/// </summary>
public static readonly RoutedCommand DismissPopupCommand = new RoutedCommand("DismissPopup",typeof(DismissiblePopup));
static private void DismissPopupCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
DismissiblePopup obj = (DismissiblePopup) sender;
obj.OnDismissPopupExecuted( e );
}
/// <summary>
/// Called when DismissPopup executes.
/// </summary>
/// <remarks>
/// A command which child controls can use to tell the popup to close.
/// </remarks>
protected virtual void OnDismissPopupExecuted(ExecutedRoutedEventArgs e)
{
OnDismissPopupExecutedImplementation(e);
}
partial void OnDismissPopupExecutedImplementation(ExecutedRoutedEventArgs e);
//
// CloseOnEscape dependency property
//
/// <summary>
/// Identifies the CloseOnEscape dependency property.
/// </summary>
public static readonly DependencyProperty CloseOnEscapeProperty = DependencyProperty.Register( "CloseOnEscape", typeof(bool), typeof(DismissiblePopup), new PropertyMetadata( BooleanBoxes.TrueBox, CloseOnEscapeProperty_PropertyChanged) );
/// <summary>
/// Gets or sets a value indicating whether the popup closes when ESC is pressed.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a value indicating whether the popup closes when ESC is pressed.")]
[Localizability(LocalizationCategory.None)]
public bool CloseOnEscape
{
get
{
return (bool) GetValue(CloseOnEscapeProperty);
}
set
{
SetValue(CloseOnEscapeProperty,BooleanBoxes.Box(value));
}
}
static private void CloseOnEscapeProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
DismissiblePopup obj = (DismissiblePopup) o;
obj.OnCloseOnEscapeChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) );
}
/// <summary>
/// Occurs when CloseOnEscape property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<bool>> CloseOnEscapeChanged;
/// <summary>
/// Called when CloseOnEscape property changes.
/// </summary>
protected virtual void OnCloseOnEscapeChanged(PropertyChangedEventArgs<bool> e)
{
OnCloseOnEscapeChangedImplementation(e);
RaisePropertyChangedEvent(CloseOnEscapeChanged, e);
}
partial void OnCloseOnEscapeChangedImplementation(PropertyChangedEventArgs<bool> e);
//
// FocusChildOnOpen dependency property
//
/// <summary>
/// Identifies the FocusChildOnOpen dependency property.
/// </summary>
public static readonly DependencyProperty FocusChildOnOpenProperty = DependencyProperty.Register( "FocusChildOnOpen", typeof(bool), typeof(DismissiblePopup), new PropertyMetadata( BooleanBoxes.TrueBox, FocusChildOnOpenProperty_PropertyChanged) );
/// <summary>
/// Gets or sets a value indicating whether focus should be set on the child when the popup opens.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a value indicating whether focus should be set on the child when the popup opens.")]
[Localizability(LocalizationCategory.None)]
public bool FocusChildOnOpen
{
get
{
return (bool) GetValue(FocusChildOnOpenProperty);
}
set
{
SetValue(FocusChildOnOpenProperty,BooleanBoxes.Box(value));
}
}
static private void FocusChildOnOpenProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
DismissiblePopup obj = (DismissiblePopup) o;
obj.OnFocusChildOnOpenChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) );
}
/// <summary>
/// Occurs when FocusChildOnOpen property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<bool>> FocusChildOnOpenChanged;
/// <summary>
/// Called when FocusChildOnOpen property changes.
/// </summary>
protected virtual void OnFocusChildOnOpenChanged(PropertyChangedEventArgs<bool> e)
{
OnFocusChildOnOpenChangedImplementation(e);
RaisePropertyChangedEvent(FocusChildOnOpenChanged, e);
}
partial void OnFocusChildOnOpenChangedImplementation(PropertyChangedEventArgs<bool> e);
//
// SetFocusOnClose dependency property
//
/// <summary>
/// Identifies the SetFocusOnClose dependency property.
/// </summary>
public static readonly DependencyProperty SetFocusOnCloseProperty = DependencyProperty.Register( "SetFocusOnClose", typeof(bool), typeof(DismissiblePopup), new PropertyMetadata( BooleanBoxes.FalseBox, SetFocusOnCloseProperty_PropertyChanged) );
/// <summary>
/// Indicates whether the focus returns to either a defined by the FocusOnCloseTarget dependency property UIElement or PlacementTarget or not.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Indicates whether the focus returns to either a defined by the FocusOnCloseTarget dependency property UIElement or PlacementTarget or not.")]
[Localizability(LocalizationCategory.None)]
public bool SetFocusOnClose
{
get
{
return (bool) GetValue(SetFocusOnCloseProperty);
}
set
{
SetValue(SetFocusOnCloseProperty,BooleanBoxes.Box(value));
}
}
static private void SetFocusOnCloseProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
DismissiblePopup obj = (DismissiblePopup) o;
obj.OnSetFocusOnCloseChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) );
}
/// <summary>
/// Occurs when SetFocusOnClose property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<bool>> SetFocusOnCloseChanged;
/// <summary>
/// Called when SetFocusOnClose property changes.
/// </summary>
protected virtual void OnSetFocusOnCloseChanged(PropertyChangedEventArgs<bool> e)
{
OnSetFocusOnCloseChangedImplementation(e);
RaisePropertyChangedEvent(SetFocusOnCloseChanged, e);
}
partial void OnSetFocusOnCloseChangedImplementation(PropertyChangedEventArgs<bool> e);
//
// SetFocusOnCloseElement dependency property
//
/// <summary>
/// Identifies the SetFocusOnCloseElement dependency property.
/// </summary>
public static readonly DependencyProperty SetFocusOnCloseElementProperty = DependencyProperty.Register( "SetFocusOnCloseElement", typeof(UIElement), typeof(DismissiblePopup), new PropertyMetadata( null, SetFocusOnCloseElementProperty_PropertyChanged) );
/// <summary>
/// If the SetFocusOnClose property is set True and this property is set to a valid UIElement, focus returns to this UIElement after the DismissiblePopup is closed.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("If the SetFocusOnClose property is set True and this property is set to a valid UIElement, focus returns to this UIElement after the DismissiblePopup is closed.")]
[Localizability(LocalizationCategory.None)]
public UIElement SetFocusOnCloseElement
{
get
{
return (UIElement) GetValue(SetFocusOnCloseElementProperty);
}
set
{
SetValue(SetFocusOnCloseElementProperty,value);
}
}
static private void SetFocusOnCloseElementProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
DismissiblePopup obj = (DismissiblePopup) o;
obj.OnSetFocusOnCloseElementChanged( new PropertyChangedEventArgs<UIElement>((UIElement)e.OldValue, (UIElement)e.NewValue) );
}
/// <summary>
/// Occurs when SetFocusOnCloseElement property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<UIElement>> SetFocusOnCloseElementChanged;
/// <summary>
/// Called when SetFocusOnCloseElement property changes.
/// </summary>
protected virtual void OnSetFocusOnCloseElementChanged(PropertyChangedEventArgs<UIElement> e)
{
OnSetFocusOnCloseElementChangedImplementation(e);
RaisePropertyChangedEvent(SetFocusOnCloseElementChanged, e);
}
partial void OnSetFocusOnCloseElementChangedImplementation(PropertyChangedEventArgs<UIElement> e);
/// <summary>
/// Called when a property changes.
/// </summary>
private void RaisePropertyChangedEvent<T>(EventHandler<PropertyChangedEventArgs<T>> eh, PropertyChangedEventArgs<T> e)
{
if (eh != null)
{
eh(this,e);
}
}
//
// Static constructor
//
/// <summary>
/// Called when the type is initialized.
/// </summary>
static DismissiblePopup()
{
CommandManager.RegisterClassCommandBinding( typeof(DismissiblePopup), new CommandBinding( DismissiblePopup.DismissPopupCommand, DismissPopupCommand_CommandExecuted ));
StaticConstructorImplementation();
}
static partial void StaticConstructorImplementation();
}
}
#endregion
| |
using System;
using System.Text;
namespace Brickred.Exchange
{
public sealed class CodecInputStream
{
private readonly byte[] buffer_;
private int buffer_pos_;
private int buffer_size_;
private int buffer_left_size_;
public CodecInputStream(byte[] buffer, int offset, int length)
{
buffer_ = buffer;
buffer_pos_ = Math.Min(
Math.Max(offset, 0), buffer.Length);
buffer_size_ = Math.Min(
Math.Max(length, 0), buffer.Length - buffer_pos_);
buffer_left_size_ = buffer_size_;
}
public CodecInputStream(byte[] buffer)
{
buffer_ = buffer;
buffer_pos_ = 0;
buffer_size_ = buffer.Length;
buffer_left_size_ = buffer_size_;
}
public int GetReadSize()
{
return buffer_size_ - buffer_left_size_;
}
public byte ReadUInt8()
{
if (buffer_left_size_ < 1) {
throw CodecException.BufferOutOfSpace();
}
byte val = buffer_[buffer_pos_];
buffer_pos_ += 1;
buffer_left_size_ -= 1;
return val;
}
public ushort ReadUInt16()
{
if (buffer_left_size_ < 2) {
throw CodecException.BufferOutOfSpace();
}
ushort val = (ushort)(buffer_[buffer_pos_ + 1] |
buffer_[buffer_pos_] << 8);
buffer_pos_ += 2;
buffer_left_size_ -= 2;
return val;
}
public uint ReadUInt32()
{
if (buffer_left_size_ < 4) {
throw CodecException.BufferOutOfSpace();
}
uint val = (uint)buffer_[buffer_pos_ + 3] |
(uint)buffer_[buffer_pos_ + 2] << 8 |
(uint)buffer_[buffer_pos_ + 1] << 16 |
(uint)buffer_[buffer_pos_] << 24;
buffer_pos_ += 4;
buffer_left_size_ -= 4;
return val;
}
public ulong ReadUInt64()
{
if (buffer_left_size_ < 8) {
throw CodecException.BufferOutOfSpace();
}
ulong val = (ulong)buffer_[buffer_pos_ + 7] |
(ulong)buffer_[buffer_pos_ + 6] << 8 |
(ulong)buffer_[buffer_pos_ + 5] << 16 |
(ulong)buffer_[buffer_pos_ + 4] << 24 |
(ulong)buffer_[buffer_pos_ + 3] << 32 |
(ulong)buffer_[buffer_pos_ + 2] << 40 |
(ulong)buffer_[buffer_pos_ + 1] << 48 |
(ulong)buffer_[buffer_pos_] << 56;
buffer_pos_ += 8;
buffer_left_size_ -= 8;
return val;
}
public ushort ReadUInt16V()
{
byte val = ReadUInt8();
if (val < 255) {
return val;
} else {
return ReadUInt16();
}
}
public uint ReadUInt32V()
{
byte val = ReadUInt8();
if (val < 254) {
return val;
} else if (val == 254) {
return ReadUInt16();
} else {
return ReadUInt32();
}
}
public ulong ReadUInt64V()
{
byte val = ReadUInt8();
if (val < 253) {
return val;
} else if (val == 253) {
return ReadUInt16();
} else if (val == 254) {
return ReadUInt32();
} else {
return ReadUInt64();
}
}
public sbyte ReadInt8()
{
return (sbyte)ReadUInt8();
}
public short ReadInt16()
{
return (short)ReadUInt16();
}
public int ReadInt32()
{
return (int)ReadUInt32();
}
public long ReadInt64()
{
return (long)ReadUInt64();
}
public short ReadInt16V()
{
return (short)ReadUInt16V();
}
public int ReadInt32V()
{
return (int)ReadUInt32V();
}
public long ReadInt64V()
{
return (long)ReadUInt64V();
}
public bool ReadBool()
{
return ReadUInt8() != 0;
}
public int ReadLength()
{
int length = (int)ReadUInt32V();
if (length < 0) {
throw CodecException.BufferOutOfSpace();
}
return length;
}
public string ReadString()
{
int length = ReadLength();
if (length <= 0) {
return "";
}
if (buffer_left_size_ < length) {
throw CodecException.BufferOutOfSpace();
}
// ArgumentException
// DecoderFallbackException
string val = Encoding.UTF8.GetString(
buffer_, buffer_pos_, length);
buffer_pos_ += length;
buffer_left_size_ -= length;
return val;
}
public byte[] ReadBytes()
{
int length = ReadLength();
if (length <= 0) {
return new byte[0];
}
if (buffer_left_size_ < length) {
throw CodecException.BufferOutOfSpace();
}
byte[] val = new byte[length];
Buffer.BlockCopy(buffer_, buffer_pos_, val, 0, length);
buffer_pos_ += length;
buffer_left_size_ -= length;
return val;
}
public T ReadStruct<T>() where T : BaseStruct, new()
{
T val = new T();
val.DecodeFromStream(this);
return val;
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using OpenMetaverse;
namespace OpenSim.Framework
{
public class EstateSettings
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly ConfigurationMember configMember;
public enum EstateSaveOptions : uint { EstateSaveSettingsOnly = 0, EstateSaveManagers = 1, EstateSaveUsers = 2, EstateSaveGroups = 4, EstateSaveBans = 8 };
public delegate void SaveDelegate(EstateSettings rs, uint listsToSave); // listsToSave is a bitmask of EstateSaveOptions
public event SaveDelegate OnSave;
// Only the client uses these
//
private uint m_EstateID = 100;
public uint EstateID
{
get { return m_EstateID; }
set { m_EstateID = value; }
}
private string m_EstateName;
public string EstateName
{
get { return m_EstateName; }
set { m_EstateName = value; }
}
private uint m_ParentEstateID = 100;
public uint ParentEstateID
{
get { return m_ParentEstateID; }
set { m_ParentEstateID = value; }
}
private float m_BillableFactor;
public float BillableFactor
{
get { return m_BillableFactor; }
set { m_BillableFactor = value; }
}
private int m_PricePerMeter;
public int PricePerMeter
{
get { return m_PricePerMeter; }
set { m_PricePerMeter = value; }
}
private int m_RedirectGridX;
public int RedirectGridX
{
get { return m_RedirectGridX; }
set { m_RedirectGridX = value; }
}
private int m_RedirectGridY;
public int RedirectGridY
{
get { return m_RedirectGridY; }
set { m_RedirectGridY = value; }
}
// Used by the sim
//
private bool m_UseGlobalTime = true;
public bool UseGlobalTime
{
get { return m_UseGlobalTime; }
set { m_UseGlobalTime = value; }
}
private bool m_FixedSun = false;
public bool FixedSun
{
get { return m_FixedSun; }
set { m_FixedSun = value; }
}
private double m_SunPosition = 0.0;
public double SunPosition
{
get { return m_SunPosition; }
set { m_SunPosition = value; }
}
private bool m_AllowVoice = true;
public bool AllowVoice
{
get { return m_AllowVoice; }
set { m_AllowVoice = value; }
}
private bool m_AllowDirectTeleport = true;
public bool AllowDirectTeleport
{
get { return m_AllowDirectTeleport; }
set { m_AllowDirectTeleport = value; }
}
private bool m_DenyAnonymous = false;
public bool DenyAnonymous
{
get { return m_DenyAnonymous; }
set { m_DenyAnonymous = value; }
}
private bool m_DenyIdentified = false;
public bool DenyIdentified
{
get { return m_DenyIdentified; }
set { m_DenyIdentified = value; }
}
private bool m_DenyTransacted = false;
public bool DenyTransacted
{
get { return m_DenyTransacted; }
set { m_DenyTransacted = value; }
}
private bool m_AbuseEmailToEstateOwner = false;
public bool AbuseEmailToEstateOwner
{
get { return m_AbuseEmailToEstateOwner; }
set { m_AbuseEmailToEstateOwner = value; }
}
private bool m_BlockDwell = false;
public bool BlockDwell
{
get { return m_BlockDwell; }
set { m_BlockDwell = value; }
}
private bool m_EstateSkipScripts = false;
public bool EstateSkipScripts
{
get { return m_EstateSkipScripts; }
set { m_EstateSkipScripts = value; }
}
private bool m_ResetHomeOnTeleport = false;
public bool ResetHomeOnTeleport
{
get { return m_ResetHomeOnTeleport; }
set { m_ResetHomeOnTeleport = value; }
}
private bool m_TaxFree = false;
public bool TaxFree
{
get { return m_TaxFree; }
set { m_TaxFree = value; }
}
private bool m_PublicAccess = true;
public bool PublicAccess
{
get { return m_PublicAccess; }
set { m_PublicAccess = value; }
}
private string m_AbuseEmail = String.Empty;
public string AbuseEmail
{
get { return m_AbuseEmail; }
set { m_AbuseEmail= value; }
}
private UUID m_EstateOwner = UUID.Zero;
public UUID EstateOwner
{
get { return m_EstateOwner; }
set { m_EstateOwner = value; }
}
private bool m_DenyMinors = false;
public bool DenyMinors
{
get { return m_DenyMinors; }
set { m_DenyMinors = value; }
}
// All those lists...
//
private List<UUID> l_EstateManagers = new List<UUID>();
public UUID[] EstateManagers
{
get { return l_EstateManagers.ToArray(); }
set { l_EstateManagers = new List<UUID>(value); }
}
private List<EstateBan> l_EstateBans = new List<EstateBan>();
public EstateBan[] EstateBans
{
get { return l_EstateBans.ToArray(); }
set { l_EstateBans = new List<EstateBan>(value); }
}
private List<UUID> l_EstateAccess = new List<UUID>();
public UUID[] EstateAccess
{
get { return l_EstateAccess.ToArray(); }
set { l_EstateAccess = new List<UUID>(value); }
}
private List<UUID> l_EstateGroups = new List<UUID>();
public UUID[] EstateGroups
{
get { return l_EstateGroups.ToArray(); }
set { l_EstateGroups = new List<UUID>(value); }
}
public EstateSettings()
{
if (configMember == null)
{
try
{
// Load legacy defaults
//
configMember =
new ConfigurationMember(Path.Combine(Util.configDir(),
"estate_settings.xml"), "ESTATE SETTINGS",
loadConfigurationOptions,
handleIncomingConfiguration, true);
l_EstateManagers.Clear();
configMember.performConfigurationRetrieve();
}
catch (Exception)
{
}
}
}
public void Save(uint listsToSave)
{
if (OnSave != null)
OnSave(this, listsToSave);
}
public void AddEstateManager(UUID avatarID)
{
if (avatarID == UUID.Zero)
return;
if (!l_EstateManagers.Contains(avatarID))
l_EstateManagers.Add(avatarID);
}
public void RemoveEstateManager(UUID avatarID)
{
if (l_EstateManagers.Contains(avatarID))
l_EstateManagers.Remove(avatarID);
}
public bool IsEstateManager(UUID avatarID)
{
if (IsEstateOwner(avatarID))
return true;
return l_EstateManagers.Contains(avatarID);
}
public bool IsEstateOwner(UUID avatarID)
{
if (avatarID == m_EstateOwner)
return true;
return false;
}
public bool IsBanned(UUID avatarID)
{
foreach (EstateBan ban in l_EstateBans)
if (ban.BannedUserID == avatarID)
return true;
return false;
}
public void AddBan(EstateBan ban)
{
if (ban == null)
return;
if (!IsBanned(ban.BannedUserID))
l_EstateBans.Add(ban);
}
public void ClearBans()
{
l_EstateBans.Clear();
}
public void RemoveBan(UUID avatarID)
{
foreach (EstateBan ban in new List<EstateBan>(l_EstateBans))
if (ban.BannedUserID == avatarID)
l_EstateBans.Remove(ban);
}
public bool HasAccess(UUID user)
{
if (IsEstateManager(user))
return true;
return l_EstateAccess.Contains(user);
}
public void AddAccess(UUID user)
{
if (user == UUID.Zero)
return;
if (!l_EstateAccess.Contains(user))
l_EstateAccess.Add(user);
}
public void RemoveAccess(UUID user)
{
if (l_EstateAccess.Contains(user))
l_EstateAccess.Remove(user);
}
public bool HasGroupAccess(UUID group)
{
return l_EstateGroups.Contains(group);
}
public void AddGroup(UUID group)
{
if (group == UUID.Zero)
return;
if (!l_EstateGroups.Contains(group))
l_EstateGroups.Add(group);
}
public void RemoveGroup(UUID group)
{
if (l_EstateGroups.Contains(group))
l_EstateGroups.Remove(group);
}
public void loadConfigurationOptions()
{
configMember.addConfigurationOption("billable_factor",
ConfigurationOption.ConfigurationTypes.TYPE_FLOAT,
String.Empty, "0.0", true);
// configMember.addConfigurationOption("estate_id",
// ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
// String.Empty, "100", true);
// configMember.addConfigurationOption("parent_estate_id",
// ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
// String.Empty, "1", true);
configMember.addConfigurationOption("redirect_grid_x",
ConfigurationOption.ConfigurationTypes.TYPE_INT32,
String.Empty, "0", true);
configMember.addConfigurationOption("redirect_grid_y",
ConfigurationOption.ConfigurationTypes.TYPE_INT32,
String.Empty, "0", true);
configMember.addConfigurationOption("price_per_meter",
ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
String.Empty, "1", true);
configMember.addConfigurationOption("estate_name",
ConfigurationOption.ConfigurationTypes.TYPE_STRING,
String.Empty, "My Estate", true);
configMember.addConfigurationOption("estate_manager_0",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_1",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_2",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_3",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_4",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_5",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_6",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_7",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_8",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("estate_manager_9",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, "00000000-0000-0000-0000-000000000000", true);
configMember.addConfigurationOption("region_flags",
ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
String.Empty, "336723974", true);
}
public bool handleIncomingConfiguration(string configuration_key, object configuration_result)
{
switch (configuration_key)
{
case "region_flags":
RegionFlags flags = (RegionFlags)(uint)configuration_result;
if ((flags & (RegionFlags)(1<<29)) != 0)
m_AllowVoice = true;
if ((flags & RegionFlags.AllowDirectTeleport) != 0)
m_AllowDirectTeleport = true;
if ((flags & RegionFlags.DenyAnonymous) != 0)
m_DenyAnonymous = true;
if ((flags & RegionFlags.DenyIdentified) != 0)
m_DenyIdentified = true;
if ((flags & RegionFlags.DenyTransacted) != 0)
m_DenyTransacted = true;
if ((flags & RegionFlags.AbuseEmailToEstateOwner) != 0)
m_AbuseEmailToEstateOwner = true;
if ((flags & RegionFlags.BlockDwell) != 0)
m_BlockDwell = true;
if ((flags & RegionFlags.EstateSkipScripts) != 0)
m_EstateSkipScripts = true;
if ((flags & RegionFlags.ResetHomeOnTeleport) != 0)
m_ResetHomeOnTeleport = true;
if ((flags & RegionFlags.TaxFree) != 0)
m_TaxFree = true;
if ((flags & RegionFlags.PublicAllowed) != 0)
m_PublicAccess = true;
break;
case "billable_factor":
m_BillableFactor = (float) configuration_result;
break;
// case "estate_id":
// m_EstateID = (uint) configuration_result;
// break;
// case "parent_estate_id":
// m_ParentEstateID = (uint) configuration_result;
// break;
case "redirect_grid_x":
m_RedirectGridX = (int) configuration_result;
break;
case "redirect_grid_y":
m_RedirectGridY = (int) configuration_result;
break;
case "price_per_meter":
m_PricePerMeter = Convert.ToInt32(configuration_result);
break;
case "estate_name":
m_EstateName = (string) configuration_result;
break;
case "estate_manager_0":
AddEstateManager((UUID)configuration_result);
break;
case "estate_manager_1":
AddEstateManager((UUID)configuration_result);
break;
case "estate_manager_2":
AddEstateManager((UUID)configuration_result);
break;
case "estate_manager_3":
AddEstateManager((UUID)configuration_result);
break;
case "estate_manager_4":
AddEstateManager((UUID)configuration_result);
break;
case "estate_manager_5":
AddEstateManager((UUID)configuration_result);
break;
case "estate_manager_6":
AddEstateManager((UUID)configuration_result);
break;
case "estate_manager_7":
AddEstateManager((UUID)configuration_result);
break;
case "estate_manager_8":
AddEstateManager((UUID)configuration_result);
break;
case "estate_manager_9":
AddEstateManager((UUID)configuration_result);
break;
}
return true;
}
}
}
| |
namespace DocumentDB.ChangeFeedProcessor
{
using ChangeFeedProcessor.DocumentLeaseStore;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Simple host for distributing change feed events across observers and thus allowing these observers scale.
/// It distributes the load across its instances and allows dynamic scaling:
/// - Partitions in partitioned collections are distributed across instances/observers.
/// - New instance takes leases from existing instances to make distribution equal.
/// - If an instance dies, the leases are distributed across remaining instances.
/// It's useful for scenario when partition count is high so that one host/VM is not capable of processing that many change feed events.
/// Client application needs to implement <see cref="DocumentDB.ChangeFeedProcessor.IChangeFeedObserver"/> and register processor implementation with ChangeFeedEventHost.
/// </summary>
/// <remarks>
/// It uses auxiliary document collection for managing leases for a partition.
/// Every EventProcessorHost instance is performing the following two tasks:
/// 1) Renew Leases: It keeps track of leases currently owned by the host and continuously keeps on renewing the leases.
/// 2) Acquire Leases: Each instance continuously polls all leases to check if there are any leases it should acquire
/// for the system to get into balanced state.
/// </remarks>
/// <example>
/// <code language="c#">
/// <![CDATA[
/// class DocumentFeedObserver : IChangeFeedObserver
/// {
/// private static int s_totalDocs = 0;
/// public Task OpenAsync(ChangeFeedObserverContext context)
/// {
/// Console.WriteLine("Worker opened, {0}", context.PartitionKeyRangeId);
/// return Task.CompletedTask; // Requires targeting .NET 4.6+.
/// }
/// public Task CloseAsync(ChangeFeedObserverContext context, ChangeFeedObserverCloseReason reason)
/// {
/// Console.WriteLine("Worker closed, {0}", context.PartitionKeyRangeId);
/// return Task.CompletedTask;
/// }
/// public Task ProcessChangesAsync(ChangeFeedObserverContext context, IReadOnlyList<Document> docs)
/// {
/// Console.WriteLine("Change feed: total {0} doc(s)", Interlocked.Add(ref s_totalDocs, docs.Count));
/// return Task.CompletedTask;
/// }
/// }
/// static async Task StartChangeFeedHost()
/// {
/// string hostName = Guid.NewGuid().ToString();
/// DocumentCollectionInfo documentCollectionLocation = new DocumentCollectionInfo
/// {
/// Uri = new Uri("https://YOUR_SERVICE.documents.azure.com:443/"),
/// MasterKey = "YOUR_SECRET_KEY==",
/// DatabaseName = "db1",
/// CollectionName = "documents"
/// };
/// DocumentCollectionInfo leaseCollectionLocation = new DocumentCollectionInfo
/// {
/// Uri = new Uri("https://YOUR_SERVICE.documents.azure.com:443/"),
/// MasterKey = "YOUR_SECRET_KEY==",
/// DatabaseName = "db1",
/// CollectionName = "leases"
/// };
/// Console.WriteLine("Main program: Creating ChangeFeedEventHost...");
/// ChangeFeedEventHost host = new ChangeFeedEventHost(hostName, documentCollectionLocation, leaseCollectionLocation);
/// await host.RegisterObserverAsync<DocumentFeedObserver>();
/// Console.WriteLine("Main program: press Enter to stop...");
/// Console.ReadLine();
/// await host.UnregisterObserversAsync();
/// }
/// ]]>
/// </code>
/// </example>
public class ChangeFeedEventHost : IPartitionObserver<DocumentServiceLease>
{
const string DefaultUserAgentSuffix = "changefeed-0.3.3";
const string LeaseContainerName = "docdb-changefeed";
const string LSNPropertyName = "_lsn";
const int DefaultMaxItemCount = 100;
readonly DocumentCollectionInfo collectionLocation;
string leasePrefix;
string collectionSelfLink;
DocumentClient documentClient;
ChangeFeedOptions changeFeedOptions;
ChangeFeedHostOptions options;
PartitionManager<DocumentServiceLease> partitionManager;
ILeaseManager<DocumentServiceLease> leaseManager;
ICheckpointManager checkpointManager;
DocumentCollectionInfo auxCollectionLocation;
ConcurrentDictionary<string, CheckpointStats> statsSinceLastCheckpoint = new ConcurrentDictionary<string, CheckpointStats>();
IChangeFeedObserverFactory observerFactory;
ConcurrentDictionary<string, WorkerData> partitionKeyRangeIdToWorkerMap;
int isShutdown = 0;
#if DEBUG
int partitionCount;
#endif
/// <summary>
/// Initializes a new instance of the <see cref="DocumentDB.ChangeFeedProcessor.ChangeFeedEventHost"/> class.
/// </summary>
/// <param name="hostName">Unique name for this host.</param>
/// <param name="documentCollectionLocation">Specifies location of the DocumentDB collection to monitor changes for.</param>
/// <param name="auxCollectionLocation">Specifies location of auxiliary data for load-balancing instances of <see cref="DocumentDB.ChangeFeedProcessor.ChangeFeedEventHost" />.</param>
public ChangeFeedEventHost(string hostName, DocumentCollectionInfo documentCollectionLocation, DocumentCollectionInfo auxCollectionLocation)
: this(hostName, documentCollectionLocation, auxCollectionLocation, new ChangeFeedOptions(), new ChangeFeedHostOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DocumentDB.ChangeFeedProcessor.ChangeFeedEventHost"/> class.
/// </summary>
/// <param name="hostName">Unique name for this host.</param>
/// <param name="documentCollectionLocation">Specifies location of the DocumentDB collection to monitor changes for.</param>
/// <param name="auxCollectionLocation">Specifies location of auxiliary data for load-balancing instances of <see cref="DocumentDB.ChangeFeedProcessor.ChangeFeedEventHost" />.</param>
/// <param name="changeFeedOptions">Options to pass to the Microsoft.AzureDocuments.DocumentClient.CreateChangeFeedQuery API.</param>
/// <param name="hostOptions">Additional options to control load-balancing of <see cref="DocumentDB.ChangeFeedProcessor.ChangeFeedEventHost" /> instances.</param>
public ChangeFeedEventHost(
string hostName,
DocumentCollectionInfo documentCollectionLocation,
DocumentCollectionInfo auxCollectionLocation,
ChangeFeedOptions changeFeedOptions,
ChangeFeedHostOptions hostOptions)
{
if (string.IsNullOrWhiteSpace(hostName)) throw new ArgumentException("The hostName parameter cannot be null or empty string.", "hostName");
if (documentCollectionLocation == null) throw new ArgumentNullException("documentCollectionLocation");
if (documentCollectionLocation.Uri == null) throw new ArgumentNullException("documentCollectionLocation.Uri");
if (string.IsNullOrWhiteSpace(documentCollectionLocation.DatabaseName)) throw new ArgumentException("documentCollectionLocation.DatabaseName");
if (string.IsNullOrWhiteSpace(documentCollectionLocation.CollectionName)) throw new ArgumentException("documentCollectionLocation.CollectionName");
if (changeFeedOptions == null) throw new ArgumentNullException("changeFeedOptions");
if (!string.IsNullOrEmpty(changeFeedOptions.PartitionKeyRangeId)) throw new ArgumentException("changeFeedOptions.PartitionKeyRangeId must be null or empty string.", "changeFeedOptions.PartitionKeyRangeId");
if (hostOptions == null) throw new ArgumentNullException("hostOptions");
if (hostOptions.MinPartitionCount > hostOptions.MaxPartitionCount) throw new ArgumentException("hostOptions.MinPartitionCount cannot be greater than hostOptions.MaxPartitionCount");
this.collectionLocation = CanoninicalizeCollectionInfo(documentCollectionLocation);
this.changeFeedOptions = changeFeedOptions;
this.options = hostOptions;
this.HostName = hostName;
this.auxCollectionLocation = CanoninicalizeCollectionInfo(auxCollectionLocation);
this.partitionKeyRangeIdToWorkerMap = new ConcurrentDictionary<string, WorkerData>();
}
/// <summary>Gets the host name, which is a unique name for the instance.</summary>
/// <value>The host name.</value>
public string HostName { get; private set; }
/// <summary>Asynchronously registers the observer interface implementation with the host.
/// This method also starts the host and enables it to start participating in the partition distribution process.</summary>
/// <typeparam name="T">Implementation of your application-specific event observer.</typeparam>
/// <returns>A task indicating that the <see cref="DocumentDB.ChangeFeedProcessor.ChangeFeedEventHost" /> instance has started.</returns>
public async Task RegisterObserverAsync<T>() where T : IChangeFeedObserver, new()
{
this.observerFactory = new ChangeFeedObserverFactory<T>();
await this.StartAsync();
}
/// <summary>
/// Asynchronously registers the observer factory implementation with the host.
/// This method also starts the host and enables it to start participating in the partition distribution process.
/// </summary>
/// <param name="factory">Implementation of your application-specific event observer factory.</typeparam>
/// <returns>A task indicating that the <see cref="DocumentDB.ChangeFeedProcessor.ChangeFeedEventHost" /> instance has started.</returns>
public async Task RegisterObserverFactoryAsync(IChangeFeedObserverFactory factory)
{
if (factory == null) throw new ArgumentNullException("factory");
this.observerFactory = factory;
await this.StartAsync();
}
/// <summary>
/// Asynchronously checks the current existing leases and calculates an estimate of remaining work per leased partitions.
/// </summary>
/// <returns>An estimate amount of remaining documents to be processed</returns>
public async Task<long> GetEstimatedRemainingWork()
{
await this.InitializeAsync();
long remaining = 0;
ChangeFeedOptions options = new ChangeFeedOptions
{
MaxItemCount = 1
};
foreach (DocumentServiceLease existingLease in await this.leaseManager.ListLeases())
{
options.PartitionKeyRangeId = existingLease.PartitionId;
options.RequestContinuation = existingLease.ContinuationToken;
IDocumentQuery<Document> query = this.documentClient.CreateDocumentChangeFeedQuery(this.collectionSelfLink, options);
FeedResponse<Document> response = null;
try
{
response = await query.ExecuteNextAsync<Document>();
long parsedLSNFromSessionToken = TryConvertToNumber(ParseAmountFromSessionToken(response.SessionToken));
long lastSequenceNumber = response.Count > 0 ? TryConvertToNumber(response.First().GetPropertyValue<string>(LSNPropertyName)) : parsedLSNFromSessionToken;
long partitionRemaining = parsedLSNFromSessionToken - lastSequenceNumber;
remaining += partitionRemaining < 0 ? 0 : partitionRemaining;
}
catch (DocumentClientException ex)
{
ExceptionDispatchInfo exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex);
DocumentClientException dcex = (DocumentClientException)exceptionDispatchInfo.SourceException;
if ((StatusCode.NotFound == (StatusCode)dcex.StatusCode && SubStatusCode.ReadSessionNotAvailable != (SubStatusCode)GetSubStatusCode(dcex))
|| StatusCode.Gone == (StatusCode)dcex.StatusCode)
{
// We are not explicitly handling Splits here to avoid any collision with an Observer that might have picked this up and managing the split
TraceLog.Error(string.Format("GetEstimateWork > Partition {0}: resource gone (subStatus={1}).", existingLease.PartitionId, GetSubStatusCode(dcex)));
}
else if (StatusCode.TooManyRequests == (StatusCode)dcex.StatusCode ||
StatusCode.ServiceUnavailable == (StatusCode)dcex.StatusCode)
{
TraceLog.Warning(string.Format("GetEstimateWork > Partition {0}: retriable exception : {1}", existingLease.PartitionId, dcex.Message));
}
else
{
TraceLog.Error(string.Format("GetEstimateWork > Partition {0}: Unhandled exception", ex.Error.Message));
}
}
}
return remaining;
}
/// <summary>Asynchronously shuts down the host instance. This method maintains the leases on all partitions currently held, and enables each
/// host instance to shut down cleanly by invoking the method with object.</summary>
/// <returns>A task that indicates the host instance has stopped.</returns>
public async Task UnregisterObserversAsync()
{
await this.StopAsync(ChangeFeedObserverCloseReason.Shutdown);
this.observerFactory = null;
}
Task IPartitionObserver<DocumentServiceLease>.OnPartitionAcquiredAsync(DocumentServiceLease lease)
{
Debug.Assert(lease != null && !string.IsNullOrEmpty(lease.Owner), "lease");
TraceLog.Informational(string.Format("Host '{0}' partition {1}: acquired!", this.HostName, lease.PartitionId));
#if DEBUG
Interlocked.Increment(ref this.partitionCount);
#endif
IChangeFeedObserver observer = this.observerFactory.CreateObserver();
ChangeFeedObserverContext context = new ChangeFeedObserverContext(lease.PartitionId, this);
CancellationTokenSource cancellation = new CancellationTokenSource();
WorkerData workerData = null;
ManualResetEvent workerTaskOkToStart = new ManualResetEvent(false);
// Create ChangeFeedOptions to use for this worker.
ChangeFeedOptions options = new ChangeFeedOptions
{
MaxItemCount = this.changeFeedOptions.MaxItemCount,
PartitionKeyRangeId = this.changeFeedOptions.PartitionKeyRangeId,
SessionToken = this.changeFeedOptions.SessionToken,
StartFromBeginning = this.changeFeedOptions.StartFromBeginning,
StartTime = this.changeFeedOptions.StartTime,
RequestContinuation = this.changeFeedOptions.RequestContinuation
};
Task workerTask = Task.Run(async () =>
{
ChangeFeedObserverCloseReason? closeReason = null;
try
{
TraceLog.Verbose(string.Format("Worker task waiting for start signal: partition '{0}'", lease.PartitionId));
workerTaskOkToStart.WaitOne();
Debug.Assert(workerData != null);
TraceLog.Verbose(string.Format("Worker task started: partition '{0}'", lease.PartitionId));
try
{
await observer.OpenAsync(context);
}
catch (Exception ex)
{
TraceLog.Error(string.Format("IChangeFeedObserver.OpenAsync exception: {0}", ex));
closeReason = ChangeFeedObserverCloseReason.ObserverError;
throw;
}
options.PartitionKeyRangeId = lease.PartitionId;
if (!string.IsNullOrEmpty(lease.ContinuationToken))
{
options.RequestContinuation = lease.ContinuationToken;
}
CheckpointStats checkpointStats = null;
if (!this.statsSinceLastCheckpoint.TryGetValue(lease.PartitionId, out checkpointStats) || checkpointStats == null)
{
// It could be that the lease was created by different host and we picked it up.
checkpointStats = this.statsSinceLastCheckpoint.AddOrUpdate(
lease.PartitionId,
new CheckpointStats(),
(partitionId, existingStats) => existingStats);
Trace.TraceWarning(string.Format("Added stats for partition '{0}' for which the lease was picked up after the host was started.", lease.PartitionId));
}
IDocumentQuery<Document> query = this.documentClient.CreateDocumentChangeFeedQuery(this.collectionSelfLink, options);
TraceLog.Verbose(string.Format("Worker start: partition '{0}', continuation '{1}'", lease.PartitionId, lease.ContinuationToken));
string lastContinuation = options.RequestContinuation;
while (this.isShutdown == 0)
{
do
{
ExceptionDispatchInfo exceptionDispatchInfo = null;
FeedResponse<Document> response = null;
try
{
response = await query.ExecuteNextAsync<Document>();
lastContinuation = response.ResponseContinuation;
}
catch (DocumentClientException ex)
{
exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex);
}
if (exceptionDispatchInfo != null)
{
DocumentClientException dcex = (DocumentClientException)exceptionDispatchInfo.SourceException;
if (StatusCode.NotFound == (StatusCode)dcex.StatusCode && SubStatusCode.ReadSessionNotAvailable != (SubStatusCode)GetSubStatusCode(dcex))
{
// Most likely, the database or collection was removed while we were enumerating.
// Shut down. The user will need to start over.
// Note: this has to be a new task, can't await for shutdown here, as shudown awaits for all worker tasks.
TraceLog.Error(string.Format("Partition {0}: resource gone (subStatus={1}). Aborting.", context.PartitionKeyRangeId, GetSubStatusCode(dcex)));
await Task.Factory.StartNew(() => this.StopAsync(ChangeFeedObserverCloseReason.ResourceGone));
break;
}
else if (StatusCode.Gone == (StatusCode)dcex.StatusCode)
{
SubStatusCode subStatusCode = (SubStatusCode)GetSubStatusCode(dcex);
if (SubStatusCode.PartitionKeyRangeGone == subStatusCode)
{
bool isSuccess = await HandleSplitAsync(context.PartitionKeyRangeId, lastContinuation, lease.Id);
if (!isSuccess)
{
TraceLog.Error(string.Format("Partition {0}: HandleSplit failed! Aborting.", context.PartitionKeyRangeId));
await Task.Factory.StartNew(() => this.StopAsync(ChangeFeedObserverCloseReason.ResourceGone));
break;
}
// Throw LeaseLostException so that we take the lease down.
throw new LeaseLostException(lease, exceptionDispatchInfo.SourceException, true);
}
else if (SubStatusCode.Splitting == subStatusCode)
{
TraceLog.Warning(string.Format("Partition {0} is splitting. Will retry to read changes until split finishes. {1}", context.PartitionKeyRangeId, dcex.Message));
}
else
{
exceptionDispatchInfo.Throw();
}
}
else if (StatusCode.TooManyRequests == (StatusCode)dcex.StatusCode ||
StatusCode.ServiceUnavailable == (StatusCode)dcex.StatusCode)
{
TraceLog.Warning(string.Format("Partition {0}: retriable exception : {1}", context.PartitionKeyRangeId, dcex.Message));
}
else if(dcex.Message.Contains("Reduce page size and try again."))
{
// Temporary workaround to compare exception message, until server provides better way of handling this case.
if (!options.MaxItemCount.HasValue) options.MaxItemCount = DefaultMaxItemCount;
else if (options.MaxItemCount <= 1)
{
TraceLog.Error(string.Format("Cannot reduce maxItemCount further as it's already at {0}.", options.MaxItemCount));
exceptionDispatchInfo.Throw();
}
options.MaxItemCount /= 2;
TraceLog.Warning(string.Format("Reducing maxItemCount, new value: {0}.", options.MaxItemCount));
}
else
{
exceptionDispatchInfo.Throw();
}
await Task.Delay(dcex.RetryAfter != TimeSpan.Zero ? dcex.RetryAfter : this.options.FeedPollDelay, cancellation.Token);
}
if (response != null)
{
if (response.Count > 0)
{
List<Document> docs = new List<Document>();
docs.AddRange(response);
try
{
context.FeedResponse = response;
await observer.ProcessChangesAsync(context, docs);
}
catch (Exception ex)
{
TraceLog.Error(string.Format("IChangeFeedObserver.ProcessChangesAsync exception: {0}", ex));
closeReason = ChangeFeedObserverCloseReason.ObserverError;
throw;
}
finally
{
context.FeedResponse = null;
}
}
checkpointStats.ProcessedDocCount += (uint)response.Count;
if (this.options.IsAutoCheckpointEnabled)
{
if (IsCheckpointNeeded(lease, checkpointStats))
{
lease = workerData.Lease = await this.CheckpointAsync(lease, response.ResponseContinuation, context);
checkpointStats.Reset();
}
else if (response.Count > 0)
{
TraceLog.Informational(string.Format("Checkpoint: not checkpointing for partition {0}, {1} docs, new continuation '{2}' as frequency condition is not met", lease.PartitionId, response.Count, response.ResponseContinuation));
}
}
if (options.MaxItemCount != this.changeFeedOptions.MaxItemCount)
{
options.MaxItemCount = this.changeFeedOptions.MaxItemCount;
}
}
}
while (query.HasMoreResults && this.isShutdown == 0);
if (this.isShutdown == 0)
{
await Task.Delay(this.options.FeedPollDelay, cancellation.Token);
}
} // Outer while (this.isShutdown == 0) loop.
closeReason = ChangeFeedObserverCloseReason.Shutdown;
}
catch (LeaseLostException ex)
{
closeReason = ex.IsGone ? ChangeFeedObserverCloseReason.LeaseGone : ChangeFeedObserverCloseReason.LeaseLost;
}
catch (TaskCanceledException ex)
{
if (cancellation.IsCancellationRequested || this.isShutdown != 0)
{
TraceLog.Informational(string.Format("Cancel signal received for partition {0} worker!", context.PartitionKeyRangeId));
if (!closeReason.HasValue)
{
closeReason = ChangeFeedObserverCloseReason.Shutdown;
}
}
else
{
TraceLog.Warning(string.Format("Partition {0}: got task cancelled exception in non-shutdown scenario [cancellation={1}, isShutdown={2}], {3}", context.PartitionKeyRangeId, cancellation.IsCancellationRequested, this.isShutdown, ex.StackTrace));
if (!closeReason.HasValue)
{
closeReason = ChangeFeedObserverCloseReason.Unknown;
}
}
}
catch (Exception ex)
{
TraceLog.Error(string.Format("Partition {0} exception: {1}", context.PartitionKeyRangeId, ex));
if (!closeReason.HasValue)
{
closeReason = ChangeFeedObserverCloseReason.Unknown;
}
}
if (closeReason.HasValue)
{
TraceLog.Informational(string.Format("Releasing lease for partition {0} due to an error, reason: {1}!", context.PartitionKeyRangeId, closeReason.Value));
// Note: this has to be a new task, because OnPartitionReleasedAsync awaits for worker task.
await Task.Factory.StartNew(async () => await this.partitionManager.TryReleasePartitionAsync(context.PartitionKeyRangeId, true, closeReason.Value));
}
TraceLog.Informational(string.Format("Partition {0}: worker finished!", context.PartitionKeyRangeId));
});
workerData = new WorkerData(workerTask, observer, context, cancellation, lease);
this.partitionKeyRangeIdToWorkerMap.AddOrUpdate(context.PartitionKeyRangeId, workerData, (string id, WorkerData d) => { return workerData; });
workerTaskOkToStart.Set();
return Task.FromResult(0);
}
async Task IPartitionObserver<DocumentServiceLease>.OnPartitionReleasedAsync(DocumentServiceLease lease, ChangeFeedObserverCloseReason reason)
{
Debug.Assert(lease != null);
#if DEBUG
Interlocked.Decrement(ref this.partitionCount);
#endif
TraceLog.Informational(string.Format("Host '{0}' releasing partition {1}...", this.HostName, lease.PartitionId));
WorkerData workerData = null;
if (this.partitionKeyRangeIdToWorkerMap.TryGetValue(lease.PartitionId, out workerData))
{
Debug.Assert(workerData != null);
await workerData.CheckpointInProgress.WaitAsync();
try
{
workerData.Cancellation.Cancel();
}
finally
{
workerData.CheckpointInProgress.Release();
}
try
{
await workerData.Observer.CloseAsync(workerData.Context, reason);
}
catch (Exception ex)
{
// Eat all client exceptions.
TraceLog.Error(string.Format("IChangeFeedObserver.CloseAsync: exception: {0}", ex));
}
await workerData.Task;
this.partitionKeyRangeIdToWorkerMap.TryRemove(lease.PartitionId, out workerData);
}
TraceLog.Informational(string.Format("Host '{0}' partition {1}: released!", this.HostName, workerData.Context.PartitionKeyRangeId));
}
static DocumentCollectionInfo CanoninicalizeCollectionInfo(DocumentCollectionInfo collectionInfo)
{
DocumentCollectionInfo result = collectionInfo;
if (string.IsNullOrEmpty(result.ConnectionPolicy.UserAgentSuffix))
{
result = new DocumentCollectionInfo(collectionInfo);
result.ConnectionPolicy.UserAgentSuffix = DefaultUserAgentSuffix;
}
return result;
}
internal async Task CheckpointAsync(string continuation, ChangeFeedObserverContext context)
{
if (string.IsNullOrEmpty(continuation)) throw new ArgumentException("continuation");
if (context == null) throw new ArgumentNullException("context");
if (string.IsNullOrEmpty(context.PartitionKeyRangeId)) throw new ArgumentException("context.PartitionKeyRangeId");
WorkerData workerData;
this.partitionKeyRangeIdToWorkerMap.TryGetValue(context.PartitionKeyRangeId, out workerData);
if (workerData == null)
{
TraceLog.Warning(string.Format("CheckpointAsync: called at wrong time, failed to get worker data for partition {0}. Most likely the partition is not longer owned by this host.", context.PartitionKeyRangeId));
throw new LeaseLostException(string.Format("Failed to find lease for partition {0} in the set of owned leases.", context.PartitionKeyRangeId));
}
if (workerData.Lease == null)
{
TraceLog.Error(string.Format("CheckpointAsync: found the worker data but lease is null, for partition {0}. This should never happen.", context.PartitionKeyRangeId));
throw new LeaseLostException(string.Format("Failed to find lease for partition {0}.", context.PartitionKeyRangeId));
}
await workerData.CheckpointInProgress.WaitAsync();
try
{
if (workerData.Cancellation.IsCancellationRequested)
{
TraceLog.Warning(string.Format("CheckpointAsync: called at wrong time, partition {0} is shutting down. The ownership of the partition by this host is about to end.", context.PartitionKeyRangeId));
throw new LeaseLostException(string.Format("CheckpointAsync: partition {0} is shutting down.", context.PartitionKeyRangeId));
}
workerData.Lease = await this.CheckpointAsync(workerData.Lease, continuation, context);
}
finally
{
workerData.CheckpointInProgress.Release();
}
}
async Task<DocumentServiceLease> CheckpointAsync(DocumentServiceLease lease, string continuation, ChangeFeedObserverContext context)
{
Debug.Assert(lease != null);
Debug.Assert(!string.IsNullOrEmpty(continuation));
DocumentServiceLease result = null;
try
{
result = (DocumentServiceLease)await this.checkpointManager.CheckpointAsync(lease, continuation, lease.SequenceNumber + 1);
Debug.Assert(result.ContinuationToken == continuation, "ContinuationToken was not updated!");
TraceLog.Informational(string.Format("Checkpoint: partition {0}, new continuation '{1}'", lease.PartitionId, continuation));
}
catch (LeaseLostException)
{
TraceLog.Warning(string.Format("Partition {0}: failed to checkpoint due to lost lease", context.PartitionKeyRangeId));
throw;
}
catch (Exception ex)
{
TraceLog.Error(string.Format("Partition {0}: failed to checkpoint due to unexpected error: {1}", context.PartitionKeyRangeId, ex.Message));
throw;
}
Debug.Assert(result != null);
return await Task.FromResult<DocumentServiceLease>(result);
}
async Task InitializeAsync()
{
this.documentClient = new DocumentClient(this.collectionLocation.Uri, this.collectionLocation.MasterKey, this.collectionLocation.ConnectionPolicy);
Uri databaseUri = UriFactory.CreateDatabaseUri(this.collectionLocation.DatabaseName);
Database database = await this.documentClient.ReadDatabaseAsync(databaseUri);
Uri collectionUri = UriFactory.CreateDocumentCollectionUri(this.collectionLocation.DatabaseName, this.collectionLocation.CollectionName);
ResourceResponse<DocumentCollection> collectionResponse = await this.documentClient.ReadDocumentCollectionAsync(
collectionUri,
new RequestOptions { PopulateQuotaInfo = true });
DocumentCollection collection = collectionResponse.Resource;
this.collectionSelfLink = collection.SelfLink;
// Grab the options-supplied prefix if present otherwise leave it empty.
string optionsPrefix = this.options.LeasePrefix ?? string.Empty;
// Beyond this point all access to collection is done via this self link: if collection is removed, we won't access new one using same name by accident.
this.leasePrefix = string.Format(CultureInfo.InvariantCulture, "{0}{1}_{2}_{3}", optionsPrefix, this.collectionLocation.Uri.Host, database.ResourceId, collection.ResourceId);
var leaseManager = new DocumentServiceLeaseManager(
this.auxCollectionLocation,
this.leasePrefix,
this.options.LeaseExpirationInterval,
this.options.LeaseRenewInterval);
await leaseManager.InitializeAsync();
this.leaseManager = leaseManager;
this.checkpointManager = (ICheckpointManager)leaseManager;
if (this.options.DiscardExistingLeases)
{
TraceLog.Warning(string.Format("Host '{0}': removing all leases, as requested by ChangeFeedHostOptions", this.HostName));
await this.leaseManager.DeleteAllAsync();
}
// Note: lease store is never stale as we use monitored colleciton Rid as id prefix for aux collection.
// Collection was removed and re-created, the rid would change.
// If it's not deleted, it's not stale. If it's deleted, it's not stale as it doesn't exist.
await this.leaseManager.CreateLeaseStoreIfNotExistsAsync();
var ranges = new Dictionary<string, PartitionKeyRange>();
foreach (var range in await CollectionHelper.EnumPartitionKeyRangesAsync(this.documentClient, this.collectionSelfLink))
{
ranges.Add(range.Id, range);
}
TraceLog.Informational(string.Format("Source collection: '{0}', {1} partition(s), {2} document(s)", this.collectionLocation.CollectionName, ranges.Count, CollectionHelper.GetDocumentCount(collectionResponse)));
await this.CreateLeases(ranges);
this.partitionManager = new PartitionManager<DocumentServiceLease>(this.HostName, this.leaseManager, this.options);
await this.partitionManager.SubscribeAsync(this);
await this.partitionManager.InitializeAsync();
}
/// <summary>
/// Create leases for new partitions and take care of split partitions.
/// </summary>
private async Task CreateLeases(IDictionary<string, PartitionKeyRange> ranges)
{
Debug.Assert(ranges != null);
// Get leases after getting ranges, to make sure that no other hosts checked in continuation for split partition after we got leases.
var existingLeases = new Dictionary<string, DocumentServiceLease>();
foreach (var lease in await this.leaseManager.ListLeases())
{
existingLeases.Add(lease.PartitionId, lease);
}
var gonePartitionIds = new HashSet<string>();
foreach (var partitionId in existingLeases.Keys)
{
if (!ranges.ContainsKey(partitionId)) gonePartitionIds.Add(partitionId);
}
var addedPartitionIds = new List<string>();
foreach (var range in ranges)
{
if (!existingLeases.ContainsKey(range.Key)) addedPartitionIds.Add(range.Key);
}
// Create leases for new partitions, if there was split, use continuation from parent partition.
var parentIdToChildLeases = new ConcurrentDictionary<string, ConcurrentQueue<DocumentServiceLease>>();
await addedPartitionIds.ForEachAsync(
async addedRangeId =>
{
this.statsSinceLastCheckpoint.AddOrUpdate(
addedRangeId,
new CheckpointStats(),
(partitionId, existingStats) => existingStats);
string continuationToken = null;
string parentIds = string.Empty;
var range = ranges[addedRangeId];
if (range.Parents != null && range.Parents.Count > 0) // Check for split.
{
foreach (var parentRangeId in range.Parents)
{
if (gonePartitionIds.Contains(parentRangeId))
{
// Transfer continiation from lease for gone parent to lease for its child partition.
Debug.Assert(existingLeases[parentRangeId] != null);
parentIds += parentIds.Length == 0 ? parentRangeId : "," + parentRangeId;
if (continuationToken != null)
{
TraceLog.Warning(string.Format("Partition {0}: found more than one parent, new continuation '{1}', current '{2}', will use '{3}'", addedRangeId, existingLeases[parentRangeId].ContinuationToken, existingLeases[parentRangeId].ContinuationToken));
}
continuationToken = existingLeases[parentRangeId].ContinuationToken;
}
}
}
bool wasCreated = await this.leaseManager.CreateLeaseIfNotExistAsync(addedRangeId, continuationToken);
if (wasCreated)
{
if (parentIds.Length == 0)
{
TraceLog.Informational(string.Format("Created lease for partition '{0}', continuation '{1}'.", addedRangeId, continuationToken));
}
else
{
TraceLog.Informational(string.Format("Created lease for partition '{0}' as child of split partition(s) '{1}', continuation '{2}'.", addedRangeId, parentIds, continuationToken));
}
}
else
{
TraceLog.Warning(string.Format("Some other host created lease for '{0}' as child of split partition(s) '{1}', continuation '{2}'.", addedRangeId, parentIds, continuationToken));
}
},
this.options.DegreeOfParallelism);
// Remove leases for splitted (and thus gone partitions) and update continuation token.
await gonePartitionIds.ForEachAsync(
async goneRangeId =>
{
await this.leaseManager.DeleteAsync(existingLeases[goneRangeId]);
TraceLog.Informational(string.Format("Deleted lease for gone (splitted) partition '{0}', continuation '{1}'", goneRangeId, existingLeases[goneRangeId].ContinuationToken));
CheckpointStats removedStatsUnused;
this.statsSinceLastCheckpoint.TryRemove(goneRangeId, out removedStatsUnused);
},
this.options.DegreeOfParallelism);
}
async Task StartAsync()
{
await this.InitializeAsync();
await this.partitionManager.StartAsync();
}
async Task StopAsync(ChangeFeedObserverCloseReason reason)
{
if (Interlocked.CompareExchange(ref this.isShutdown, 1, 0) != 0)
{
return;
}
TraceLog.Informational(string.Format("Host '{0}': STOP signal received!", this.HostName));
List<Task> closingTasks = new List<Task>();
// Trigger stop for PartitionManager so it triggers shutdown of AcquireLease task and starts processor shutdown
closingTasks.Add(this.partitionManager.StopAsync(reason));
// Stop all workers.
TraceLog.Informational(string.Format("Host '{0}': Cancelling {1} workers.", this.HostName, this.partitionKeyRangeIdToWorkerMap.Count));
foreach (var item in this.partitionKeyRangeIdToWorkerMap.Values)
{
item.Cancellation.Cancel();
closingTasks.Add(item.Task);
}
// wait for everything to shutdown
TraceLog.Informational(string.Format("Host '{0}': Waiting for {1} closing tasks...", this.HostName, closingTasks.Count));
if (closingTasks.Count > 0)
{
await Task.WhenAll(closingTasks.ToArray());
}
this.partitionKeyRangeIdToWorkerMap.Clear();
if (this.leaseManager is IDisposable)
{
((IDisposable)this.leaseManager).Dispose();
}
TraceLog.Informational(string.Format("Host '{0}': stopped.", this.HostName));
}
/// <summary>
/// Handle split for given partition.
/// </summary>
/// <param name="partitionKeyRangeId">The id of the partition that was splitted, aka parent partition.</param>
/// <param name="continuationToken">Continuation token on split partition before split.</param>
/// <param name="leaseId">The id of the lease. This is needed to avoid extra call to ILeaseManager to get the lease by partitionId.</param>
/// <returns>True on success, false on failure.</returns>
private async Task<bool> HandleSplitAsync(string partitionKeyRangeId, string continuationToken, string leaseId)
{
Debug.Assert(!string.IsNullOrEmpty(partitionKeyRangeId));
Debug.Assert(!string.IsNullOrEmpty(leaseId));
TraceLog.Informational(string.Format("Partition {0} is gone due to split, continuation '{1}'", partitionKeyRangeId, continuationToken));
List<PartitionKeyRange> allRanges = await CollectionHelper.EnumPartitionKeyRangesAsync(this.documentClient, this.collectionSelfLink);
var childRanges = new List<PartitionKeyRange>(allRanges.Where(range => range.Parents.Contains(partitionKeyRangeId)));
if (childRanges.Count < 2)
{
TraceLog.Error(string.Format("Partition {0} had split but we failed to find at least 2 child paritions."));
return false;
}
var tasks = new List<Task>();
foreach (var childRange in childRanges)
{
tasks.Add(this.leaseManager.CreateLeaseIfNotExistAsync(childRange.Id, continuationToken));
TraceLog.Informational(string.Format("Creating lease for partition '{0}' as child of partition '{1}', continuation '{2}'", childRange.Id, partitionKeyRangeId, continuationToken));
}
await Task.WhenAll(tasks);
await this.leaseManager.DeleteAsync(new DocumentServiceLease { Id = leaseId });
TraceLog.Informational(string.Format("Deleted lease for gone (splitted) partition '{0}' continuation '{1}'", partitionKeyRangeId, continuationToken));
// Note: the rest is up to lease taker, that after waking up would consume these new leases.
return true;
}
private int GetSubStatusCode(DocumentClientException exception)
{
Debug.Assert(exception != null);
const string SubStatusHeaderName = "x-ms-substatus";
string valueSubStatus = exception.ResponseHeaders.Get(SubStatusHeaderName);
if (!string.IsNullOrEmpty(valueSubStatus))
{
int subStatusCode = 0;
if (int.TryParse(valueSubStatus, NumberStyles.Integer, CultureInfo.InvariantCulture, out subStatusCode))
{
return subStatusCode;
}
}
return -1;
}
private bool IsCheckpointNeeded(DocumentServiceLease lease, CheckpointStats checkpointStats)
{
Debug.Assert(lease != null);
Debug.Assert(checkpointStats != null);
if (checkpointStats.ProcessedDocCount == 0)
{
return false;
}
bool isCheckpointNeeded = true;
if (this.options.CheckpointFrequency != null &&
(this.options.CheckpointFrequency.ProcessedDocumentCount.HasValue || this.options.CheckpointFrequency.TimeInterval.HasValue))
{
// Note: if either condition is satisfied, we checkpoint.
isCheckpointNeeded = false;
if (this.options.CheckpointFrequency.ProcessedDocumentCount.HasValue)
{
isCheckpointNeeded = checkpointStats.ProcessedDocCount >= this.options.CheckpointFrequency.ProcessedDocumentCount.Value;
}
if (this.options.CheckpointFrequency.TimeInterval.HasValue)
{
isCheckpointNeeded = isCheckpointNeeded ||
DateTime.Now - checkpointStats.LastCheckpointTime >= this.options.CheckpointFrequency.TimeInterval.Value;
}
}
return isCheckpointNeeded;
}
private static long TryConvertToNumber(string number)
{
if (string.IsNullOrEmpty(number))
{
return 0;
}
long parsed = 0;
if (!long.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out parsed))
{
TraceLog.Warning(string.Format(CultureInfo.InvariantCulture, "Cannot parse number '{0}'.", number));
return 0;
}
return parsed;
}
private static string ParseAmountFromSessionToken(string sessionToken)
{
if (string.IsNullOrEmpty(sessionToken))
{
return string.Empty;
}
int separatorIndex = sessionToken.IndexOf(':');
return sessionToken.Substring(separatorIndex + 1);
}
private class WorkerData
{
public WorkerData(Task task, IChangeFeedObserver observer, ChangeFeedObserverContext context, CancellationTokenSource cancellation, DocumentServiceLease lease)
{
Debug.Assert(task != null);
Debug.Assert(observer != null);
Debug.Assert(context != null);
Debug.Assert(cancellation != null);
this.Task = task;
this.Observer = observer;
this.Context = context;
this.Cancellation = cancellation;
this.Lease = lease;
}
public Task Task { get; private set; }
public IChangeFeedObserver Observer { get; private set; }
public ChangeFeedObserverContext Context { get; private set; }
public CancellationTokenSource Cancellation { get; private set; }
public DocumentServiceLease Lease { get; set; }
internal SemaphoreSlim CheckpointInProgress = new SemaphoreSlim(1, 1); // Use semphore as it doesn't have thread affinity.
}
/// <summary>
/// Stats since last checkpoint.
/// </summary>
private class CheckpointStats
{
internal uint ProcessedDocCount { get; set; }
internal DateTime LastCheckpointTime { get; set; }
internal void Reset()
{
this.ProcessedDocCount = 0;
this.LastCheckpointTime = DateTime.Now;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ParameterModelBase.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/RicoSuter/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, [email protected]</author>
//-----------------------------------------------------------------------
using System;
using NJsonSchema;
using NJsonSchema.CodeGeneration;
using System.Collections.Generic;
using System.Linq;
namespace NSwag.CodeGeneration.Models
{
/// <summary>The parameter template model.</summary>
public abstract class ParameterModelBase
{
private readonly OpenApiParameter _parameter;
private readonly IList<OpenApiParameter> _allParameters;
private readonly CodeGeneratorSettingsBase _settings;
private readonly IClientGenerator _generator;
private readonly TypeResolverBase _typeResolver;
private readonly IEnumerable<PropertyModel> _properties;
/// <summary>Initializes a new instance of the <see cref="ParameterModelBase" /> class.</summary>
/// <param name="parameterName">Name of the parameter.</param>
/// <param name="variableName">Name of the variable.</param>
/// <param name="typeName">The type name.</param>
/// <param name="parameter">The parameter.</param>
/// <param name="allParameters">All parameters.</param>
/// <param name="settings">The settings.</param>
/// <param name="generator">The client generator base.</param>
/// <param name="typeResolver">The type resolver.</param>
protected ParameterModelBase(string parameterName, string variableName, string typeName,
OpenApiParameter parameter, IList<OpenApiParameter> allParameters, CodeGeneratorSettingsBase settings,
IClientGenerator generator, TypeResolverBase typeResolver)
{
_allParameters = allParameters;
_parameter = parameter;
_settings = settings;
_generator = generator;
_typeResolver = typeResolver;
Type = typeName;
Name = parameterName;
VariableName = variableName;
var propertyNameGenerator = settings?.PropertyNameGenerator ?? throw new InvalidOperationException("PropertyNameGenerator not set.");
_properties = _parameter.ActualSchema.ActualProperties
.Select(p => new PropertyModel(p.Key, p.Value, propertyNameGenerator.Generate(p.Value)))
.ToList();
}
/// <summary>Gets the type of the parameter.</summary>
public string Type { get; }
/// <summary>Gets the name.</summary>
public string Name { get; }
/// <summary>Gets the variable name in (usually lowercase).</summary>
public string VariableName { get; }
/// <summary>Gets a value indicating whether a default value is available.</summary>
public bool HasDefault => Default != null;
/// <summary>The default value for the variable.</summary>
public string Default
{
get
{
if (_settings.SchemaType == SchemaType.Swagger2)
{
return !_parameter.IsRequired && _parameter.Default != null ?
_settings.ValueGenerator?.GetDefaultValue(_parameter, false, _parameter.ActualTypeSchema.Id, null, true, _typeResolver) :
null;
}
else
{
return !_parameter.IsRequired && _parameter.ActualSchema.Default != null ?
_settings.ValueGenerator?.GetDefaultValue(_parameter.ActualSchema, false, _parameter.ActualTypeSchema.Id, null, true, _typeResolver) :
null;
}
}
}
/// <summary>Gets the parameter kind.</summary>
public OpenApiParameterKind Kind => _parameter.Kind;
/// <summary>Gets the parameter style.</summary>
public OpenApiParameterStyle Style => _parameter.Style;
/// <summary>Gets the the value indicating if the parameter values should be exploded when included in the query string.</summary>
public bool Explode => _parameter.Explode;
/// <summary>Gets a value indicating whether the parameter is a deep object (OpenAPI 3).</summary>
public bool IsDeepObject => _parameter.Style == OpenApiParameterStyle.DeepObject;
/// <summary>Gets a value indicating whether the parameter has form style.</summary>
public bool IsForm => _parameter.Style == OpenApiParameterStyle.Form;
/// <summary>Gets the contained value property names (OpenAPI 3).</summary>
public IEnumerable<PropertyModel> PropertyNames
{
get
{
return _properties.Where(p => !p.IsCollection);
}
}
/// <summary>Gets the contained collection property names (OpenAPI 3).</summary>
public IEnumerable<PropertyModel> CollectionPropertyNames
{
get
{
return _properties.Where(p => p.IsCollection);
}
}
/// <summary>Gets a value indicating whether the parameter has a description.</summary>
public bool HasDescription => !string.IsNullOrEmpty(Description);
/// <summary>Gets the parameter description.</summary>
public string Description => ConversionUtilities.TrimWhiteSpaces(_parameter.Description);
/// <summary>Gets the schema.</summary>
public JsonSchema Schema => _parameter.ActualSchema;
/// <summary>Gets a value indicating whether the parameter is required.</summary>
public bool IsRequired => _parameter.IsRequired;
/// <summary>Gets a value indicating whether the parameter is nullable.</summary>
public bool IsNullable => _parameter.IsNullable(_settings.SchemaType);
/// <summary>Gets a value indicating whether the parameter is optional (i.e. not required).</summary>
public bool IsOptional => _parameter.IsRequired == false;
/// <summary>Gets a value indicating whether the parameter has a description or is optional.</summary>
public bool HasDescriptionOrIsOptional => HasDescription || !IsRequired;
/// <summary>Gets a value indicating whether the parameter is the last parameter of the operation.</summary>
public bool IsLast => _allParameters.LastOrDefault() == _parameter;
/// <summary>Gets a value indicating whether this is an XML body parameter.</summary>
public bool IsXmlBodyParameter => _parameter.IsXmlBodyParameter;
/// <summary>Gets a value indicating whether this is an binary body parameter.</summary>
public bool IsBinaryBodyParameter => _parameter.IsBinaryBodyParameter;
/// <summary>Gets a value indicating whether the parameter is of type date.</summary>
public bool IsDate =>
Schema.Format == JsonFormatStrings.Date &&
_generator.GetTypeName(Schema, IsNullable, null) != "string";
/// <summary>Gets a value indicating whether the parameter is of type date-time</summary>
public bool IsDateTime =>
Schema.Format == JsonFormatStrings.DateTime && _generator.GetTypeName(Schema, IsNullable, null) != "string";
/// <summary>Gets a value indicating whether the parameter is of type date-time or date</summary>
public bool IsDateOrDateTime => IsDate || IsDateTime;
/// <summary>Gets a value indicating whether the parameter is of type array.</summary>
public bool IsArray => Schema.Type.HasFlag(JsonObjectType.Array) || _parameter.CollectionFormat == OpenApiParameterCollectionFormat.Multi;
/// <summary>Gets a value indicating whether the parameter is a string array.</summary>
public bool IsStringArray => IsArray && Schema.Item?.ActualSchema.Type.HasFlag(JsonObjectType.String) == true;
/// <summary>Gets a value indicating whether this is a file parameter.</summary>
public bool IsFile => Schema.IsBinary || (IsArray && Schema?.Item?.IsBinary == true);
/// <summary>Gets a value indicating whether the parameter is a binary body parameter.</summary>
public bool IsBinaryBody => _parameter.IsBinaryBodyParameter;
/// <summary>Gets a value indicating whether a binary body parameter allows multiple mime types.</summary>
public bool HasBinaryBodyWithMultipleMimeTypes => _parameter.HasBinaryBodyWithMultipleMimeTypes;
/// <summary>Gets a value indicating whether the parameter is of type dictionary.</summary>
public bool IsDictionary => Schema.IsDictionary;
/// <summary>Gets a value indicating whether the parameter is of type date-time array.</summary>
public bool IsDateTimeArray =>
IsArray &&
Schema.Item?.ActualSchema.Format == JsonFormatStrings.DateTime &&
_generator.GetTypeName(Schema.Item.ActualSchema, IsNullable, null) != "string";
/// <summary>Gets a value indicating whether the parameter is of type date-time or date array.</summary>
public bool IsDateOrDateTimeArray => IsDateArray || IsDateTimeArray;
/// <summary>Gets a value indicating whether the parameter is of type date array.</summary>
public bool IsDateArray =>
IsArray &&
Schema.Item?.ActualSchema.Format == JsonFormatStrings.Date &&
_generator.GetTypeName(Schema.Item.ActualSchema, IsNullable, null) != "string";
/// <summary>Gets a value indicating whether the parameter is of type object array.</summary>
public bool IsObjectArray => IsArray &&
(Schema.Item?.ActualSchema.Type == JsonObjectType.Object ||
Schema.Item?.ActualSchema.IsAnyType == true);
/// <summary>Gets a value indicating whether the parameter is of type object</summary>
public bool IsObject => Schema.ActualSchema.Type == JsonObjectType.Object;
/// <summary>Gets a value indicating whether the parameter is of type object.</summary>
public bool IsBody => Kind == OpenApiParameterKind.Body;
/// <summary>Gets a value indicating whether the parameter is supplied as query parameter.</summary>
public bool IsQuery => Kind == OpenApiParameterKind.Query;
/// <summary>Gets a value indicating whether the parameter is supplied through the request headers.</summary>
public bool IsHeader => Kind == OpenApiParameterKind.Header;
/// <summary>Gets the operation extension data.</summary>
public IDictionary<string, object> ExtensionData => _parameter.ExtensionData;
}
}
| |
//-----------------------------------------------------------------------------
//Cortex
//Copyright (c) 2010-2015, Joshua Scoggins
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Cortex nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL Joshua Scoggins BE LIABLE FOR ANY
//DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using System.IO;
using System.Linq;
namespace Cortex.Grammar
{
public class AdvanceableRule : List<AdvanceableProduction>, ICloneable,
IEqualityComparer<AdvanceableRule>, IAdvanceableRule
{
private long oldHashCode = 0L;
private int oldLength = 0;
#if GATHERING_STATS
public static long InstanceCount = 0L, DeleteCount = 0L;
// public static HashSet<TimeSpan> Lifetimes = new HashSet<TimeSpan>();
// private DateTime bornOn;
#endif
private string name;
public string Name
{
get
{
return name;
}
protected set
{
name = value;
}
}
public AdvanceableRule(Rule r, int offset)
{
#if GATHERING_STATS
InstanceCount++;
// bornOn = DateTime.Now;
#endif
if(r != null)
{
name = r.Name;
for(int i = 0; i < r.Count; i++)
Add(r[i].MakeAdvanceable(offset));
}
}
public AdvanceableRule(Rule r) : this(r, 0) { }
public AdvanceableRule(string name)
{
#if GATHERING_STATS
InstanceCount++;
// bornOn = DateTime.Now;
#endif
this.name = name;
}
public AdvanceableRule(string name, params AdvanceableProduction[] prods)
: this(name)
{
for(int i = 0; i < prods.Length; i++)
Add(prods[i]);
}
public AdvanceableRule(string name, IEnumerable<AdvanceableProduction> prods)
: this(name)
{
foreach(var v in prods)
Add(v);
}
public AdvanceableRule(AdvanceableRule rule)
{
#if GATHERING_STATS
InstanceCount++;
// bornOn = DateTime.Now;
#endif
name = rule.name;
for(int i = 0; i < rule.Count; i++)
Add(rule[i]); //lets see what this does...
}
#if GATHERING_STATS
~AdvanceableRule()
{
DeleteCount++;
// Lifetimes.Add(DateTime.Now - bornOn);
}
#endif
IAdvanceableProduction IAdvanceableRule.this[int ind] { get { return (IAdvanceableProduction)this[ind]; } }
IProduction IRule.this[int ind] { get { return (IProduction)this[ind]; } }
IEnumerable<IProduction> IRule.GetEnumerableInterface()
{
return ((IAdvanceableRule)this).GetEnumerableInterface();
}
IEnumerable<IAdvanceableProduction> IAdvanceableRule.GetEnumerableInterface()
{
return ((IEnumerable<AdvanceableProduction>)this);
}
public object Clone()
{
return new AdvanceableRule(this);
}
protected bool Equals(AdvanceableRule rr)
{
if(!rr.name.Equals(name) || rr.Count != Count)
return false;
else
{
for(int i = 0; i < Count; i++)
if(!this[i].Equals(rr[i]))
return false;
return true;
}
}
bool IAdvanceableRule.Equals(object other)
{
AdvanceableRule rr = (AdvanceableRule)other;
return Equals(rr);
}
int IAdvanceableRule.GetHashCode()
{
return GetHashCode0();
}
public override bool Equals(object other)
{
AdvanceableRule rr = (AdvanceableRule)other;
return Equals(rr);
}
private int GetHashCode0()
{
if(oldLength != Count)
{
long total = name.GetHashCode();
for(int i = 0; i < Count; i++)
total += this[i].GetHashCode();
oldHashCode = total;
oldLength = Count;
}
return (int)oldHashCode;
}
bool IEqualityComparer<AdvanceableRule>.Equals(AdvanceableRule x, AdvanceableRule y)
{
return x.Equals(y);
}
int IEqualityComparer<AdvanceableRule>.GetHashCode(AdvanceableRule x)
{
return x.GetHashCode0();
}
public override int GetHashCode()
{
return GetHashCode0();
}
public AdvanceableRule FunctionalNext()
{
var clone = this.Clone() as AdvanceableRule;
clone.Next();
return clone;
}
public AdvanceableRule FunctionalPrevious()
{
var clone = this.Clone() as AdvanceableRule;
clone.Previous();
return clone;
}
public void Next()
{
for(int i = 0; i < Count ; i++)
if(this[i].HasNext)
this[i].Next();
}
public void Previous()
{
for(int i = 0; i < Count; i++)
if(this[i].HasPrevious)
this[i].Previous();
}
public void Reset()
{
for(int i = 0; i < Count; i++)
this[i].Reset();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < Count; i++)
sb.AppendFormat("[{0} => {1}]\n", name, this[i].ToString());
return sb.ToString();
}
public IEnumerable<AdvanceableRule> Subdivide()
{
for(int i = 0; i < Count; i++)
yield return new AdvanceableRule(name) { this[i] };
}
public void Repurpose(Rule target)
{
Repurpose(new AdvanceableRule(target));
}
public void Repurpose(AdvanceableRule target)
{
Clear();
Repurpose(target.name);
// if(!target.Name.Equals(Name))
// Name = target.Name;
for(int i = 0; i < target.Count; i++)
Add(target[i]);
}
public void Repurpose(string name, params AdvanceableProduction[] prods)
{
Repurpose(name);
Repurpose(prods);
}
public void Repurpose(params AdvanceableProduction[] prods)
{
Clear();
for(int i = 0; i < prods.Length; i++)
Add(prods[i]);
}
public void Repurpose(string name)
{
if(!name.Equals(this.name))
this.name = name;
}
}
}
| |
/*
* 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 machinelearning-2014-12-12.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.MachineLearning.Model
{
/// <summary>
/// Represents the output of <a>GetEvaluation</a> operation.
///
///
/// <para>
/// The content consists of the detailed metadata and data file information and the current
/// status of the <code>Evaluation</code>.
/// </para>
/// </summary>
public partial class Evaluation
{
private DateTime? _createdAt;
private string _createdByIamUser;
private string _evaluationDataSourceId;
private string _evaluationId;
private string _inputDataLocationS3;
private DateTime? _lastUpdatedAt;
private string _message;
private string _mlModelId;
private string _name;
private PerformanceMetrics _performanceMetrics;
private EntityStatus _status;
/// <summary>
/// Gets and sets the property CreatedAt.
/// <para>
/// The time that the <code>Evaluation</code> was created. The time is expressed in epoch
/// time.
/// </para>
/// </summary>
public DateTime CreatedAt
{
get { return this._createdAt.GetValueOrDefault(); }
set { this._createdAt = value; }
}
// Check to see if CreatedAt property is set
internal bool IsSetCreatedAt()
{
return this._createdAt.HasValue;
}
/// <summary>
/// Gets and sets the property CreatedByIamUser.
/// <para>
/// The AWS user account that invoked the evaluation. The account type can be either an
/// AWS root account or an AWS Identity and Access Management (IAM) user account.
/// </para>
/// </summary>
public string CreatedByIamUser
{
get { return this._createdByIamUser; }
set { this._createdByIamUser = value; }
}
// Check to see if CreatedByIamUser property is set
internal bool IsSetCreatedByIamUser()
{
return this._createdByIamUser != null;
}
/// <summary>
/// Gets and sets the property EvaluationDataSourceId.
/// <para>
/// The ID of the <code>DataSource</code> that is used to evaluate the <code>MLModel</code>.
/// </para>
/// </summary>
public string EvaluationDataSourceId
{
get { return this._evaluationDataSourceId; }
set { this._evaluationDataSourceId = value; }
}
// Check to see if EvaluationDataSourceId property is set
internal bool IsSetEvaluationDataSourceId()
{
return this._evaluationDataSourceId != null;
}
/// <summary>
/// Gets and sets the property EvaluationId.
/// <para>
/// The ID that is assigned to the <code>Evaluation</code> at creation.
/// </para>
/// </summary>
public string EvaluationId
{
get { return this._evaluationId; }
set { this._evaluationId = value; }
}
// Check to see if EvaluationId property is set
internal bool IsSetEvaluationId()
{
return this._evaluationId != null;
}
/// <summary>
/// Gets and sets the property InputDataLocationS3.
/// <para>
/// The location and name of the data in Amazon Simple Storage Server (Amazon S3) that
/// is used in the evaluation.
/// </para>
/// </summary>
public string InputDataLocationS3
{
get { return this._inputDataLocationS3; }
set { this._inputDataLocationS3 = value; }
}
// Check to see if InputDataLocationS3 property is set
internal bool IsSetInputDataLocationS3()
{
return this._inputDataLocationS3 != null;
}
/// <summary>
/// Gets and sets the property LastUpdatedAt.
/// <para>
/// The time of the most recent edit to the <code>Evaluation</code>. The time is expressed
/// in epoch time.
/// </para>
/// </summary>
public DateTime LastUpdatedAt
{
get { return this._lastUpdatedAt.GetValueOrDefault(); }
set { this._lastUpdatedAt = value; }
}
// Check to see if LastUpdatedAt property is set
internal bool IsSetLastUpdatedAt()
{
return this._lastUpdatedAt.HasValue;
}
/// <summary>
/// Gets and sets the property Message.
/// <para>
/// A description of the most recent details about evaluating the <code>MLModel</code>.
/// </para>
/// </summary>
public string Message
{
get { return this._message; }
set { this._message = value; }
}
// Check to see if Message property is set
internal bool IsSetMessage()
{
return this._message != null;
}
/// <summary>
/// Gets and sets the property MLModelId.
/// <para>
/// The ID of the <code>MLModel</code> that is the focus of the evaluation.
/// </para>
/// </summary>
public string MLModelId
{
get { return this._mlModelId; }
set { this._mlModelId = value; }
}
// Check to see if MLModelId property is set
internal bool IsSetMLModelId()
{
return this._mlModelId != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// A user-supplied name or description of the <code>Evaluation</code>.
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property PerformanceMetrics.
/// <para>
/// Measurements of how well the <code>MLModel</code> performed, using observations referenced
/// by the <code>DataSource</code>. One of the following metrics is returned, based on
/// the type of the MLModel:
/// </para>
/// <ul> <li>
/// <para>
/// BinaryAUC: A binary <code>MLModel</code> uses the Area Under the Curve (AUC) technique
/// to measure performance.
/// </para>
/// </li> <li>
/// <para>
/// RegressionRMSE: A regression <code>MLModel</code> uses the Root Mean Square Error
/// (RMSE) technique to measure performance. RMSE measures the difference between predicted
/// and actual values for a single variable.
/// </para>
/// </li> <li>
/// <para>
/// MulticlassAvgFScore: A multiclass <code>MLModel</code> uses the F1 score technique
/// to measure performance.
/// </para>
/// </li> </ul>
/// <para>
/// For more information about performance metrics, please see the <a href="http://docs.aws.amazon.com/machine-learning/latest/dg">Amazon
/// Machine Learning Developer Guide</a>.
/// </para>
/// </summary>
public PerformanceMetrics PerformanceMetrics
{
get { return this._performanceMetrics; }
set { this._performanceMetrics = value; }
}
// Check to see if PerformanceMetrics property is set
internal bool IsSetPerformanceMetrics()
{
return this._performanceMetrics != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// The status of the evaluation. This element can have one of the following values:
/// </para>
/// <ul> <li> <code>PENDING</code> - Amazon Machine Learning (Amazon ML) submitted a
/// request to evaluate an <code>MLModel</code>.</li> <li> <code>INPROGRESS</code> - The
/// evaluation is underway.</li> <li> <code>FAILED</code> - The request to evaluate an
/// <code>MLModel</code> did not run to completion. It is not usable.</li> <li> <code>COMPLETED</code>
/// - The evaluation process completed successfully.</li> <li> <code>DELETED</code> -
/// The <code>Evaluation</code> is marked as deleted. It is not usable.</li> </ul>
/// </summary>
public EntityStatus Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace System.IO
{
/// <summary>Provides an implementation of a file stream for Unix files.</summary>
internal sealed partial class UnixFileStream : FileStreamBase
{
/// <summary>The file descriptor wrapped in a file handle.</summary>
private readonly SafeFileHandle _fileHandle;
/// <summary>The path to the opened file.</summary>
private readonly string _path;
/// <summary>File mode.</summary>
private readonly FileMode _mode;
/// <summary>Whether the file is opened for reading, writing, or both.</summary>
private readonly FileAccess _access;
/// <summary>Advanced options requested when opening the file.</summary>
private readonly FileOptions _options;
/// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary>
private readonly long _appendStart = -1;
/// <summary>Whether asynchronous read/write/flush operations should be performed using async I/O.</summary>
private readonly bool _useAsyncIO;
/// <summary>The length of the _buffer.</summary>
private readonly int _bufferLength;
/// <summary>Lazily-initialized buffer data from Write waiting to be written to the underlying handle, or data read from the underlying handle and waiting to be Read.</summary>
private byte[] _buffer;
/// <summary>The number of valid bytes in _buffer.</summary>
private int _readLength;
/// <summary>The next available byte to be read from the _buffer.</summary>
private int _readPos;
/// <summary>The next location in which a write should occur to the buffer.</summary>
private int _writePos;
/// <summary>Lazily-initialized value for whether the file supports seeking.</summary>
private bool? _canSeek;
/// <summary>Whether the file stream's handle has been exposed.</summary>
private bool _exposedHandle;
/// <summary>
/// Currently cached position in the stream. This should always mirror the underlying file descriptor's actual position,
/// and should only ever be out of sync if another stream with access to this same file descriptor manipulates it, at which
/// point we attempt to error out.
/// </summary>
private long _filePosition;
/// <summary>Initializes a stream for reading or writing a Unix file.</summary>
/// <param name="path">The path to the file.</param>
/// <param name="mode">How the file should be opened.</param>
/// <param name="access">Whether the file will be read, written, or both.</param>
/// <param name="share">What other access to the file should be allowed. This is currently ignored.</param>
/// <param name="bufferSize">The size of the buffer to use when buffering.</param>
/// <param name="options">Additional options for working with the file.</param>
internal UnixFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
: base(parent)
{
// FileStream performs most of the general argument validation. We can assume here that the arguments
// are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.)
// Store the arguments
_path = path;
_access = access;
_mode = mode;
_options = options;
_bufferLength = bufferSize;
_useAsyncIO = (options & FileOptions.Asynchronous) != 0;
// Translate the arguments into arguments for an open call
Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, access, options); // FileShare currently ignored
Interop.Sys.Permissions openPermissions = Interop.Sys.Permissions.S_IRWXU; // creator has read/write/execute permissions; no permissions for anyone else
// Open the file and store the safe handle. Subsequent code in this method expects the safe handle to be initialized.
_fileHandle = SafeFileHandle.Open(path, openFlags, (int)openPermissions);
_fileHandle.IsAsync = _useAsyncIO;
// Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive
// lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory,
// and not atomic with file opening, it's better than nothing.
try
{
Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH;
SysCall<Interop.Sys.LockOperations, int>((fd, op, _) => Interop.Sys.FLock(fd, op), lockOperation | Interop.Sys.LockOperations.LOCK_NB);
}
catch
{
_fileHandle.Dispose();
throw;
}
// Perform additional configurations on the stream based on the provided FileOptions
PostOpenConfigureStreamFromOptions();
// Jump to the end of the file if opened as Append.
if (_mode == FileMode.Append)
{
_appendStart = SeekCore(0, SeekOrigin.End);
}
}
/// <summary>Performs additional configuration of the opened stream based on provided options.</summary>
partial void PostOpenConfigureStreamFromOptions();
/// <summary>Initializes a stream from an already open file handle (file descriptor).</summary>
/// <param name="handle">The handle to the file.</param>
/// <param name="access">Whether the file will be read, written, or both.</param>
/// <param name="bufferSize">The size of the buffer to use when buffering.</param>
/// <param name="useAsyncIO">Whether access to the stream is performed asynchronously.</param>
internal UnixFileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool useAsyncIO, FileStream parent)
: base(parent)
{
// Make sure the handle is open
if (handle.IsInvalid)
throw new ArgumentException(SR.Arg_InvalidHandle, "handle");
if (handle.IsClosed)
throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed);
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
throw new ArgumentOutOfRangeException("access", SR.ArgumentOutOfRange_Enum);
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
if (handle.IsAsync.HasValue && useAsyncIO != handle.IsAsync.Value)
throw new ArgumentException(SR.Arg_HandleNotAsync, "handle");
_fileHandle = handle;
_access = access;
_exposedHandle = true;
_bufferLength = bufferSize;
_useAsyncIO = useAsyncIO;
if (CanSeek)
{
SeekCore(0, SeekOrigin.Current);
}
}
/// <summary>Gets the array used for buffering reading and writing. If the array hasn't been allocated, this will lazily allocate it.</summary>
/// <returns>The buffer.</returns>
private byte[] GetBuffer()
{
Debug.Assert(_buffer == null || _buffer.Length == _bufferLength);
return _buffer ?? (_buffer = new byte[_bufferLength]);
}
/// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary>
/// <param name="mode">The FileMode provided to the stream's constructor.</param>
/// <param name="access">The FileAccess provided to the stream's constructor</param>
/// <param name="options">The FileOptions provided to the stream's constructor</param>
/// <returns>The flags value to be passed to the open system call.</returns>
private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileOptions options)
{
// Translate FileMode. Most of the values map cleanly to one or more options for open.
Interop.Sys.OpenFlags flags = default(Interop.Sys.OpenFlags);
switch (mode)
{
default:
case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed.
break;
case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later
case FileMode.OpenOrCreate:
flags |= Interop.Sys.OpenFlags.O_CREAT;
break;
case FileMode.Create:
flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_TRUNC);
break;
case FileMode.CreateNew:
flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL);
break;
case FileMode.Truncate:
flags |= Interop.Sys.OpenFlags.O_TRUNC;
break;
}
// Translate FileAccess. All possible values map cleanly to corresponding values for open.
switch (access)
{
case FileAccess.Read:
flags |= Interop.Sys.OpenFlags.O_RDONLY;
break;
case FileAccess.ReadWrite:
flags |= Interop.Sys.OpenFlags.O_RDWR;
break;
case FileAccess.Write:
flags |= Interop.Sys.OpenFlags.O_WRONLY;
break;
}
// Translate some FileOptions; some just aren't supported, and others will be handled after calling open.
switch (options)
{
case FileOptions.Asynchronous: // Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true
case FileOptions.DeleteOnClose: // DeleteOnClose doesn't have a Unix equivalent, but we approximate it in Dispose
case FileOptions.Encrypted: // Encrypted does not have an equivalent on Unix and is ignored.
case FileOptions.RandomAccess: // Implemented after open if posix_fadvise is available
case FileOptions.SequentialScan: // Implemented after open if posix_fadvise is available
break;
case FileOptions.WriteThrough:
flags |= Interop.Sys.OpenFlags.O_SYNC;
break;
}
return flags;
}
/// <summary>Gets a value indicating whether the current stream supports reading.</summary>
public override bool CanRead
{
[Pure]
get { return !_fileHandle.IsClosed && (_access & FileAccess.Read) != 0; }
}
/// <summary>Gets a value indicating whether the current stream supports writing.</summary>
public override bool CanWrite
{
[Pure]
get { return !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; }
}
/// <summary>Gets a value indicating whether the current stream supports seeking.</summary>
public override bool CanSeek
{
get
{
if (_fileHandle.IsClosed)
{
return false;
}
if (!_canSeek.HasValue)
{
// Lazily-initialize whether we're able to seek, tested by seeking to our current location.
_canSeek = SysCall<int, int>((fd, _, __) => Interop.Sys.LSeek(fd, 0, Interop.Sys.SeekWhence.SEEK_CUR), throwOnError: false) >= 0;
}
return _canSeek.Value;
}
}
/// <summary>Gets a value indicating whether the stream was opened for I/O to be performed synchronously or asynchronously.</summary>
public override bool IsAsync
{
get { return _useAsyncIO; }
}
/// <summary>Gets the length of the stream in bytes.</summary>
public override long Length
{
get
{
if (_fileHandle.IsClosed)
{
throw __Error.GetFileNotOpen();
}
if (!_parent.CanSeek)
{
throw __Error.GetSeekNotSupported();
}
// Get the length of the file as reported by the OS
long length = SysCall<int, int>((fd, _, __) =>
{
Interop.Sys.FileStatus status;
int result = Interop.Sys.FStat(fd, out status);
return result >= 0 ? status.Size : result;
});
// But we may have buffered some data to be written that puts our length
// beyond what the OS is aware of. Update accordingly.
if (_writePos > 0 && _filePosition + _writePos > length)
{
length = _writePos + _filePosition;
}
return length;
}
}
/// <summary>Gets the path that was passed to the constructor.</summary>
public override String Name { get { return _path ?? SR.IO_UnknownFileName; } }
/// <summary>Gets the SafeFileHandle for the file descriptor encapsulated in this stream.</summary>
public override SafeFileHandle SafeFileHandle
{
get
{
_parent.Flush();
_exposedHandle = true;
return _fileHandle;
}
}
/// <summary>Gets or sets the position within the current stream</summary>
public override long Position
{
get
{
if (_fileHandle.IsClosed)
{
throw __Error.GetFileNotOpen();
}
if (!_parent.CanSeek)
{
throw __Error.GetSeekNotSupported();
}
VerifyBufferInvariants();
VerifyOSHandlePosition();
// We may have read data into our buffer from the handle, such that the handle position
// is artificially further along than the consumer's view of the stream's position.
// Thus, when reading, our position is really starting from the handle position negatively
// offset by the number of bytes in the buffer and positively offset by the number of
// bytes into that buffer we've read. When writing, both the read length and position
// must be zero, and our position is just the handle position offset positive by how many
// bytes we've written into the buffer.
return (_filePosition - _readLength) + _readPos + _writePos;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum);
}
_parent.Seek(value, SeekOrigin.Begin);
}
}
/// <summary>Verifies that state relating to the read/write buffer is consistent.</summary>
[Conditional("DEBUG")]
private void VerifyBufferInvariants()
{
// Read buffer values must be in range: 0 <= _bufferReadPos <= _bufferReadLength <= _bufferLength
Debug.Assert(0 <= _readPos && _readPos <= _readLength && _readLength <= _bufferLength);
// Write buffer values must be in range: 0 <= _bufferWritePos <= _bufferLength
Debug.Assert(0 <= _writePos && _writePos <= _bufferLength);
// Read buffering and write buffering can't both be active
Debug.Assert((_readPos == 0 && _readLength == 0) || _writePos == 0);
}
/// <summary>
/// Verify that the actual position of the OS's handle equals what we expect it to.
/// This will fail if someone else moved the UnixFileStream's handle or if
/// our position updating code is incorrect.
/// </summary>
private void VerifyOSHandlePosition()
{
bool verifyPosition = _exposedHandle; // in release, only verify if we've given out the handle such that someone else could be manipulating it
#if DEBUG
verifyPosition = true; // in debug, always make sure our position matches what the OS says it should be
#endif
if (verifyPosition && _parent.CanSeek)
{
long oldPos = _filePosition; // SeekCore will override the current _position, so save it now
long curPos = SeekCore(0, SeekOrigin.Current);
if (oldPos != curPos)
{
// For reads, this is non-fatal but we still could have returned corrupted
// data in some cases, so discard the internal buffer. For writes,
// this is a problem; discard the buffer and error out.
_readPos = _readLength = 0;
if (_writePos > 0)
{
_writePos = 0;
throw new IOException(SR.IO_FileStreamHandlePosition);
}
}
}
}
/// <summary>Releases the unmanaged resources used by the stream.</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)
{
// Flush and close the file
try
{
if (_fileHandle != null && !_fileHandle.IsClosed)
{
FlushWriteBuffer();
// Unix doesn't directly support DeleteOnClose but we can mimick it.
if ((_options & FileOptions.DeleteOnClose) != 0)
{
// Since we still have the file open, this will end up deleting
// it (assuming we're the only link to it) once it's closed.
Interop.Sys.Unlink(_path); // ignore any error
}
}
}
finally
{
if (_fileHandle != null && !_fileHandle.IsClosed)
{
_fileHandle.Dispose();
}
base.Dispose(disposing);
}
}
/// <summary>Finalize the stream.</summary>
~UnixFileStream()
{
Dispose(false);
}
/// <summary>Clears buffers for this stream and causes any buffered data to be written to the file.</summary>
public override void Flush()
{
_parent.Flush(flushToDisk: false);
}
/// <summary>
/// Clears buffers for this stream, and if <param name="flushToDisk"/> is true,
/// causes any buffered data to be written to the file.
/// </summary>
public override void Flush(Boolean flushToDisk)
{
if (_fileHandle.IsClosed)
{
throw __Error.GetFileNotOpen();
}
FlushInternalBuffer();
if (flushToDisk && _parent.CanWrite)
{
FlushOSBuffer();
}
}
/// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary>
private void FlushOSBuffer()
{
SysCall<int, int>((fd, _, __) => Interop.Sys.FSync(fd));
}
/// <summary>
/// Flushes the internal read/write buffer for this stream. If write data has been buffered,
/// that data is written out to the underlying file. Or if data has been buffered for
/// reading from the stream, the data is dumped and our position in the underlying file
/// is rewound as necessary. This does not flush the OS buffer.
/// </summary>
private void FlushInternalBuffer()
{
VerifyBufferInvariants();
if (_writePos > 0)
{
FlushWriteBuffer();
}
else if (_readPos < _readLength && _parent.CanSeek)
{
FlushReadBuffer();
}
}
/// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary>
private void FlushWriteBuffer()
{
VerifyBufferInvariants();
if (_writePos > 0)
{
WriteCore(GetBuffer(), 0, _writePos);
_writePos = 0;
}
}
/// <summary>Dumps any read data in the buffer and rewinds our position in the stream, accordingly, as necessary.</summary>
private void FlushReadBuffer()
{
VerifyBufferInvariants();
int rewind = _readPos - _readLength;
if (rewind != 0)
{
SeekCore(rewind, SeekOrigin.Current);
}
_readPos = _readLength = 0;
}
/// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous flush operation.</returns>
public override Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
if (_fileHandle.IsClosed)
{
throw __Error.GetFileNotOpen();
}
// As with Win32FileStream, flush the buffers synchronously to avoid race conditions.
try
{
FlushInternalBuffer();
}
catch (Exception e)
{
return Task.FromException(e);
}
// We then separately flush to disk asynchronously. This is only
// necessary if we support writing; otherwise, we're done.
if (_parent.CanWrite)
{
return Task.Factory.StartNew(
state => ((UnixFileStream)state).FlushOSBuffer(),
this,
cancellationToken,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
}
else
{
return Task.CompletedTask;
}
}
/// <summary>Sets the length of this stream to the given value.</summary>
/// <param name="value">The new length of the stream.</param>
public override void SetLength(long value)
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (_fileHandle.IsClosed)
{
throw __Error.GetFileNotOpen();
}
if (!_parent.CanSeek)
{
throw __Error.GetSeekNotSupported();
}
if (!_parent.CanWrite)
{
throw __Error.GetWriteNotSupported();
}
FlushInternalBuffer();
if (_appendStart != -1 && value < _appendStart)
{
throw new IOException(SR.IO_SetLengthAppendTruncate);
}
long origPos = _filePosition;
VerifyOSHandlePosition();
if (_filePosition != value)
{
SeekCore(value, SeekOrigin.Begin);
}
SysCall<long, int>((fd, length, _) => Interop.libc.ftruncate(fd, length), value);
// Return file pointer to where it was before setting length
if (origPos != value)
{
if (origPos < value)
{
SeekCore(origPos, SeekOrigin.Begin);
}
else
{
SeekCore(0, SeekOrigin.End);
}
}
}
/// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary>
/// <param name="array">
/// When this method returns, contains the specified byte array with the values between offset and
/// (offset + count - 1) replaced by the bytes read from the current source.
/// </param>
/// <param name="offset">The byte offset in array at which the read bytes will be placed.</param>
/// <param name="count">The maximum number of bytes to read. </param>
/// <returns>
/// The total number of bytes read into the buffer. This might be less than the number of bytes requested
/// if that number of bytes are not currently available, or zero if the end of the stream is reached.
/// </returns>
public override int Read([In, Out] byte[] array, int offset, int count)
{
ValidateReadWriteArgs(array, offset, count);
PrepareForReading();
// Are there any bytes available in the read buffer? If yes,
// we can just return from the buffer. If the buffer is empty
// or has no more available data in it, we can either refill it
// (and then read from the buffer into the user's buffer) or
// we can just go directly into the user's buffer, if they asked
// for more data than we'd otherwise buffer.
int numBytesAvailable = _readLength - _readPos;
if (numBytesAvailable == 0)
{
// If we're not able to seek, then we're not able to rewind the stream (i.e. flushing
// a read buffer), in which case we don't want to use a read buffer. Similarly, if
// the user has asked for more data than we can buffer, we also want to skip the buffer.
if (!_parent.CanSeek || (count >= _bufferLength))
{
// Read directly into the user's buffer
int bytesRead = ReadCore(array, offset, count);
_readPos = _readLength = 0; // reset after the read just in case read experiences an exception
return bytesRead;
}
else
{
// Read into our buffer.
_readLength = numBytesAvailable = ReadCore(GetBuffer(), 0, _bufferLength);
_readPos = 0;
if (numBytesAvailable == 0)
{
return 0;
}
}
}
// Now that we know there's data in the buffer, read from it into
// the user's buffer.
int bytesToRead = Math.Min(numBytesAvailable, count);
Buffer.BlockCopy(GetBuffer(), _readPos, array, offset, bytesToRead);
_readPos += bytesToRead;
return bytesToRead;
}
/// <summary>Unbuffered, reads a block of bytes from the stream and writes the data in a given buffer.</summary>
/// <param name="array">
/// When this method returns, contains the specified byte array with the values between offset and
/// (offset + count - 1) replaced by the bytes read from the current source.
/// </param>
/// <param name="offset">The byte offset in array at which the read bytes will be placed.</param>
/// <param name="count">The maximum number of bytes to read. </param>
/// <returns>
/// The total number of bytes read into the buffer. This might be less than the number of bytes requested
/// if that number of bytes are not currently available, or zero if the end of the stream is reached.
/// </returns>
private unsafe int ReadCore(byte[] array, int offset, int count)
{
FlushWriteBuffer(); // we're about to read; dump the write buffer
VerifyOSHandlePosition();
int bytesRead;
fixed (byte* bufPtr = array)
{
bytesRead = (int)SysCall((fd, ptr, len) =>
{
long result = (long)Interop.libc.read(fd, (byte*)ptr, (IntPtr)len);
Debug.Assert(result <= len);
return result;
}, (IntPtr)(bufPtr + offset), count);
}
_filePosition += bytesRead;
return bytesRead;
}
/// <summary>
/// Asynchronously reads a sequence of bytes from the current stream and advances
/// the position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">The buffer to write the data into.</param>
/// <param name="offset">The byte offset in buffer at which to begin writing data from the stream.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous read operation.</returns>
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
if (_fileHandle.IsClosed)
throw __Error.GetFileNotOpen();
if (_useAsyncIO)
{
// TODO: Use async I/O instead of sync I/O
}
return base.ReadAsync(buffer, offset, count, cancellationToken);
}
/// <summary>
/// Reads a byte from the stream and advances the position within the stream
/// by one byte, or returns -1 if at the end of the stream.
/// </summary>
/// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns>
public override int ReadByte()
{
PrepareForReading();
byte[] buffer = GetBuffer();
if (_readPos == _readLength)
{
_readLength = ReadCore(buffer, 0, _bufferLength);
_readPos = 0;
if (_readLength == 0)
{
return -1;
}
}
return buffer[_readPos++];
}
/// <summary>Validates that we're ready to read from the stream.</summary>
private void PrepareForReading()
{
if (_fileHandle.IsClosed)
{
throw __Error.GetFileNotOpen();
}
if (_readLength == 0 && !_parent.CanRead)
{
throw __Error.GetReadNotSupported();
}
VerifyBufferInvariants();
}
/// <summary>Writes a block of bytes to the file stream.</summary>
/// <param name="array">The buffer containing data to write to the stream.</param>
/// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param>
/// <param name="count">The maximum number of bytes to write.</param>
public override void Write(byte[] array, int offset, int count)
{
ValidateReadWriteArgs(array, offset, count);
PrepareForWriting();
// If no data is being written, nothing more to do.
if (count == 0)
{
return;
}
// If there's already data in our write buffer, then we need to go through
// our buffer to ensure data isn't corrupted.
if (_writePos > 0)
{
// If there's space remaining in the buffer, then copy as much as
// we can from the user's buffer into ours.
int spaceRemaining = _bufferLength - _writePos;
if (spaceRemaining > 0)
{
int bytesToCopy = Math.Min(spaceRemaining, count);
Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, bytesToCopy);
_writePos += bytesToCopy;
// If we've successfully copied all of the user's data, we're done.
if (count == bytesToCopy)
{
return;
}
// Otherwise, keep track of how much more data needs to be handled.
offset += bytesToCopy;
count -= bytesToCopy;
}
// At this point, the buffer is full, so flush it out.
FlushWriteBuffer();
}
// Our buffer is now empty. If using the buffer would slow things down (because
// the user's looking to write more data than we can store in the buffer),
// skip the buffer. Otherwise, put the remaining data into the buffer.
Debug.Assert(_writePos == 0);
if (count >= _bufferLength)
{
WriteCore(array, offset, count);
}
else
{
Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, count);
_writePos = count;
}
}
/// <summary>Unbuffered, writes a block of bytes to the file stream.</summary>
/// <param name="array">The buffer containing data to write to the stream.</param>
/// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param>
/// <param name="count">The maximum number of bytes to write.</param>
private unsafe void WriteCore(byte[] array, int offset, int count)
{
VerifyOSHandlePosition();
fixed (byte* bufPtr = array)
{
while (count > 0)
{
int bytesWritten = (int)SysCall((fd, ptr, len) =>
{
long result = (long)Interop.libc.write(fd, (byte*)ptr, (IntPtr)len);
Debug.Assert(result <= len);
return result;
}, (IntPtr)(bufPtr + offset), count);
_filePosition += bytesWritten;
count -= bytesWritten;
offset += bytesWritten;
}
}
}
/// <summary>
/// Asynchronously writes a sequence of bytes to the current stream, advances
/// the current position within this stream by the number of bytes written, and
/// monitors cancellation requests.
/// </summary>
/// <param name="buffer">The buffer to write data from.</param>
/// <param name="offset">The zero-based byte offset in buffer from which to begin copying bytes to the stream.</param>
/// <param name="count">The maximum number of bytes to write.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
if (_fileHandle.IsClosed)
throw __Error.GetFileNotOpen();
if (_useAsyncIO)
{
// TODO: Use async I/O instead of sync I/O
}
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
/// <summary>
/// Writes a byte to the current position in the stream and advances the position
/// within the stream by one byte.
/// </summary>
/// <param name="value">The byte to write to the stream.</param>
public override void WriteByte(byte value) // avoids an array allocation in the base implementation
{
PrepareForWriting();
// Flush the write buffer if it's full
if (_writePos == _bufferLength)
{
FlushWriteBuffer();
}
// We now have space in the buffer. Store the byte.
GetBuffer()[_writePos++] = value;
}
/// <summary>
/// Validates that we're ready to write to the stream,
/// including flushing a read buffer if necessary.
/// </summary>
private void PrepareForWriting()
{
if (_fileHandle.IsClosed)
{
throw __Error.GetFileNotOpen();
}
// Make sure we're good to write. We only need to do this if there's nothing already
// in our write buffer, since if there is something in the buffer, we've already done
// this checking and flushing.
if (_writePos == 0)
{
if (!_parent.CanWrite) throw __Error.GetWriteNotSupported();
FlushReadBuffer();
}
}
/// <summary>Validates arguments to Read and Write and throws resulting exceptions.</summary>
/// <param name="array">The buffer to read from or write to.</param>
/// <param name="offset">The zero-based offset into the array.</param>
/// <param name="count">The maximum number of bytes to read or write.</param>
private void ValidateReadWriteArgs(byte[] array, int offset, int count)
{
if (array == null)
{
throw new ArgumentNullException("array", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/);
}
if (_fileHandle.IsClosed)
{
throw __Error.GetFileNotOpen();
}
}
/// <summary>Sets the current position of this stream to the given value.</summary>
/// <param name="offset">The point relative to origin from which to begin seeking. </param>
/// <param name="origin">
/// Specifies the beginning, the end, or the current position as a reference
/// point for offset, using a value of type SeekOrigin.
/// </param>
/// <returns>The new position in the stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
if (origin < SeekOrigin.Begin || origin > SeekOrigin.End)
{
throw new ArgumentException(SR.Argument_InvalidSeekOrigin, "origin");
}
if (_fileHandle.IsClosed)
{
throw __Error.GetFileNotOpen();
}
if (!_parent.CanSeek)
{
throw __Error.GetSeekNotSupported();
}
VerifyOSHandlePosition();
// Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos.
// We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're
// about to seek and update our position, we can simply update the offset as necessary and reset our read
// position and length to 0. (In the future, for some simple cases we could potentially add an optimization
// here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.)
FlushWriteBuffer();
if (origin == SeekOrigin.Current)
{
offset -= (_readLength - _readPos);
}
_readPos = _readLength = 0;
// Keep track of where we were, in case we're in append mode and need to verify
long oldPos = 0;
if (_appendStart >= 0)
{
oldPos = SeekCore(0, SeekOrigin.Current);
}
// Jump to the new location
long pos = SeekCore(offset, origin);
// Prevent users from overwriting data in a file that was opened in append mode.
if (_appendStart != -1 && pos < _appendStart)
{
SeekCore(oldPos, SeekOrigin.Begin);
throw new IOException(SR.IO_SeekAppendOverwrite);
}
// Return the new position
return pos;
}
/// <summary>Sets the current position of this stream to the given value.</summary>
/// <param name="offset">The point relative to origin from which to begin seeking. </param>
/// <param name="origin">
/// Specifies the beginning, the end, or the current position as a reference
/// point for offset, using a value of type SeekOrigin.
/// </param>
/// <returns>The new position in the stream.</returns>
private long SeekCore(long offset, SeekOrigin origin)
{
Debug.Assert(!_fileHandle.IsClosed && CanSeek);
Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End);
long pos = SysCall((fd, off, or) => Interop.Sys.LSeek(fd, off, or), offset, (Interop.Sys.SeekWhence)(int)origin); // SeekOrigin values are the same as Interop.libc.SeekWhence values
_filePosition = pos;
return pos;
}
/// <summary>
/// Helper for making system calls that involve the stream's file descriptor.
/// System calls are expected to return greather than or equal to zero on success,
/// and less than zero on failure. In the case of failure, errno is expected to
/// be set to the relevant error code.
/// </summary>
/// <typeparam name="TArg1">Specifies the type of an argument to the system call.</typeparam>
/// <typeparam name="TArg2">Specifies the type of another argument to the system call.</typeparam>
/// <param name="sysCall">A delegate that invokes the system call.</param>
/// <param name="arg1">The first argument to be passed to the system call, after the file descriptor.</param>
/// <param name="arg2">The second argument to be passed to the system call.</param>
/// <param name="throwOnError">true to throw an exception if a non-interuption error occurs; otherwise, false.</param>
/// <returns>The return value of the system call.</returns>
/// <remarks>
/// Arguments are expected to be passed via <paramref name="arg1"/> and <paramref name="arg2"/>
/// so as to avoid delegate and closure allocations at the call sites.
/// </remarks>
private long SysCall<TArg1, TArg2>(
Func<int, TArg1, TArg2, long> sysCall,
TArg1 arg1 = default(TArg1), TArg2 arg2 = default(TArg2),
bool throwOnError = true)
{
SafeFileHandle handle = _fileHandle;
Debug.Assert(sysCall != null);
Debug.Assert(handle != null);
bool gotRefOnHandle = false;
try
{
// Get the file descriptor from the handle. We increment the ref count to help
// ensure it's not closed out from under us.
handle.DangerousAddRef(ref gotRefOnHandle);
Debug.Assert(gotRefOnHandle);
int fd = (int)handle.DangerousGetHandle();
Debug.Assert(fd >= 0);
// System calls may fail due to EINTR (signal interruption). We need to retry in those cases.
while (true)
{
long result = sysCall(fd, arg1, arg2);
if (result < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EINTR)
{
continue;
}
else if (throwOnError)
{
throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false);
}
}
return result;
}
}
finally
{
if (gotRefOnHandle)
{
handle.DangerousRelease();
}
else
{
throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed);
}
}
}
}
}
| |
//
// Alerts sample in C#
//
using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using System.Drawing;
namespace MonoCatalog {
public partial class AlertsViewController : UITableViewController {
// Load our definition from the NIB file
public AlertsViewController () : base ("AlertsViewController", null)
{
}
struct AlertSample {
public string Title, Label, Source;
public AlertSample (string t, string l, string s)
{
Title = t;
Label = l;
Source = s;
}
}
static AlertSample [] samples;
static AlertsViewController ()
{
samples = new AlertSample [] {
new AlertSample ("UIActionSheet", "Show simple", "alert.cs: DialogSimpleAction ()"),
new AlertSample ("UIActionSheet", "Show OK Cancel", "alert.cs: DialogOkCancelAction ()"),
new AlertSample ("UIActionSheet", "Show Customized", "alert.cs: DialogOtherAction ()"),
new AlertSample ("UIAlertView", "Show simple", "alert.cs: AlertSimpleAction ()"),
new AlertSample ("UIAlertView", "Show OK Cancel", "alert.cs: AlertOkCancelAction ()"),
new AlertSample ("UIAlertView", "Show Customized ", "alert.cs: AlertOtherAction ()"),
};
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
Title = "Alerts";
TableView.DataSource = new DataSource ();
TableView.Delegate = new TableDelegate (this);
}
void DialogSimpleAction ()
{
var actionSheet = new UIActionSheet ("UIActionSheet <title>", null, null, "OK", null){
Style = UIActionSheetStyle.Default
};
actionSheet.Clicked += delegate (object sender, UIButtonEventArgs args){
Console.WriteLine ("Clicked on item {0}", args.ButtonIndex);
};
actionSheet.ShowInView (View);
}
void DialogOkCancelAction ()
{
var actionSheet = new UIActionSheet ("UIActionSheet <title>", null, "Cancel", "OK", null){
Style = UIActionSheetStyle.Default
};
actionSheet.Clicked += delegate (object sender, UIButtonEventArgs args){
Console.WriteLine ("Clicked on item {0}", args.ButtonIndex);
};
actionSheet.ShowInView (View);
}
void DialogOtherAction ()
{
var actionSheet = new UIActionSheet ("UIActionSheet <title>", null, "Cancel", "OK", "Other1"){
Style = UIActionSheetStyle.Default
};
actionSheet.Clicked += delegate (object sender, UIButtonEventArgs args){
Console.WriteLine ("Clicked on item {0}", args.ButtonIndex);
};
actionSheet.ShowInView (View);
}
void AlertSimpleAction ()
{
using (var alert = new UIAlertView ("UIAlertView", "<Alert Message>", null, "OK", null))
alert.Show ();
}
void AlertOkCancelAction ()
{
using (var alert = new UIAlertView ("UIAlertView", "<Alert Message>", null, "Cancel", "OK"))
alert.Show ();
}
void AlertOtherAction ()
{
using (var alert = new UIAlertView ("UIAlertView", "<Alert Message>", null, "Cancel", "Button1", "Button2"))
alert.Show ();
}
#region Delegates for the table
class DataSource : UITableViewDataSource {
static NSString kDisplayCell_ID = new NSString ("AlertCellID");
static NSString kSourceCell_ID = new NSString ("SourceCellID");
public override int NumberOfSections (UITableView tableView)
{
return samples.Length;
}
public override string TitleForHeader (UITableView tableView, int section)
{
return samples [section].Title;
}
public override int RowsInSection (UITableView tableView, int section)
{
return 2;
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell;
if (indexPath.Row == 0){
cell = tableView.DequeueReusableCell (kDisplayCell_ID);
if (cell == null)
cell = new UITableViewCell (UITableViewCellStyle.Default, kDisplayCell_ID);
cell.TextLabel.Text = samples [indexPath.Section].Label;
} else {
cell = tableView.DequeueReusableCell (kSourceCell_ID);
if (cell == null){
cell = new UITableViewCell (UITableViewCellStyle.Default, kSourceCell_ID){
SelectionStyle = UITableViewCellSelectionStyle.None
};
var label = cell.TextLabel;
label.Opaque = false;
label.TextAlignment = UITextAlignment.Center;
label.TextColor = UIColor.Gray;
label.Lines = 2;
label.Font = UIFont.SystemFontOfSize (12f);
}
cell.TextLabel.Text = samples [indexPath.Section].Source;
}
return cell;
}
}
class TableDelegate : UITableViewDelegate {
AlertsViewController avc;
public TableDelegate (AlertsViewController avc)
{
this.avc = avc;
}
public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
{
return indexPath.Row == 0 ? 50f : 22f;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
// deselect current row
tableView.DeselectRow (tableView.IndexPathForSelectedRow, true);
if (indexPath.Row == 0){
switch (indexPath.Section){
case 0:
avc.DialogSimpleAction ();
break;
case 1:
avc.DialogOkCancelAction ();
break;
case 2:
avc.DialogOtherAction ();
break;
case 3:
avc.AlertSimpleAction ();
break;
case 4:
avc.AlertOkCancelAction ();
break;
case 5:
avc.AlertOtherAction ();
break;
}
}
}
}
#endregion
}
}
| |
//
// ReplicationTest.cs
//
// Author:
// Zachary Gramana <[email protected]>
//
// Copyright (c) 2013, 2014 Xamarin Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
/**
* Original iOS version by Jens Alfke
* Ported to Android by Marty Schoch, Traun Leyden
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Apache.Http;
using Apache.Http.Client;
using Apache.Http.Client.Methods;
using Apache.Http.Entity;
using Apache.Http.Impl.Client;
using Apache.Http.Message;
using Couchbase.Lite;
using Couchbase.Lite.Auth;
using Couchbase.Lite.Internal;
using Couchbase.Lite.Replicator;
using Couchbase.Lite.Support;
using Couchbase.Lite.Threading;
using Couchbase.Lite.Util;
using NUnit.Framework;
using Org.Apache.Commons.IO;
using Org.Apache.Commons.IO.Output;
using Sharpen;
namespace Couchbase.Lite.Replicator
{
public class ReplicationTest : LiteTestCase
{
public const string Tag = "Replicator";
/// <exception cref="System.Exception"></exception>
public virtual void TestPusher()
{
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
Uri remote = GetReplicationURL();
string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis());
// Create some documents:
IDictionary<string, object> documentProperties = new Dictionary<string, object>();
string doc1Id = string.Format("doc1-%s", docIdTimestamp);
documentProperties.Put("_id", doc1Id);
documentProperties.Put("foo", 1);
documentProperties.Put("bar", false);
Body body = new Body(documentProperties);
RevisionInternal rev1 = new RevisionInternal(body, database);
Status status = new Status();
rev1 = database.PutRevision(rev1, null, false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
documentProperties.Put("_rev", rev1.GetRevId());
documentProperties.Put("UPDATED", true);
RevisionInternal rev2 = database.PutRevision(new RevisionInternal(documentProperties
, database), rev1.GetRevId(), false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
documentProperties = new Dictionary<string, object>();
string doc2Id = string.Format("doc2-%s", docIdTimestamp);
documentProperties.Put("_id", doc2Id);
documentProperties.Put("baz", 666);
documentProperties.Put("fnord", true);
database.PutRevision(new RevisionInternal(documentProperties, database), null, false
, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
bool continuous = false;
Replication repl = database.CreatePushReplication(remote);
repl.SetContinuous(continuous);
repl.SetCreateTarget(true);
// Check the replication's properties:
NUnit.Framework.Assert.AreEqual(database, repl.GetLocalDatabase());
NUnit.Framework.Assert.AreEqual(remote, repl.GetRemoteUrl());
NUnit.Framework.Assert.IsFalse(repl.IsPull());
NUnit.Framework.Assert.IsFalse(repl.IsContinuous());
NUnit.Framework.Assert.IsTrue(repl.ShouldCreateTarget());
NUnit.Framework.Assert.IsNull(repl.GetFilter());
NUnit.Framework.Assert.IsNull(repl.GetFilterParams());
// TODO: CAssertNil(r1.doc_ids);
// TODO: CAssertNil(r1.headers);
// Check that the replication hasn't started running:
NUnit.Framework.Assert.IsFalse(repl.IsRunning());
NUnit.Framework.Assert.AreEqual(Replication.ReplicationStatus.ReplicationStopped,
repl.GetStatus());
NUnit.Framework.Assert.AreEqual(0, repl.GetCompletedChangesCount());
NUnit.Framework.Assert.AreEqual(0, repl.GetChangesCount());
NUnit.Framework.Assert.IsNull(repl.GetLastError());
RunReplication(repl);
// make sure doc1 is there
// TODO: make sure doc2 is there (refactoring needed)
Uri replicationUrlTrailing = new Uri(string.Format("%s/", remote.ToExternalForm()
));
Uri pathToDoc = new Uri(replicationUrlTrailing, doc1Id);
Log.D(Tag, "Send http request to " + pathToDoc);
CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
BackgroundTask getDocTask = new _BackgroundTask_122(pathToDoc, doc1Id, httpRequestDoneSignal
);
//Closes the connection.
getDocTask.Execute();
Log.D(Tag, "Waiting for http request to finish");
try
{
httpRequestDoneSignal.Await(300, TimeUnit.Seconds);
Log.D(Tag, "http request finished");
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
Log.D(Tag, "testPusher() finished");
}
private sealed class _BackgroundTask_122 : BackgroundTask
{
public _BackgroundTask_122(Uri pathToDoc, string doc1Id, CountDownLatch httpRequestDoneSignal
)
{
this.pathToDoc = pathToDoc;
this.doc1Id = doc1Id;
this.httpRequestDoneSignal = httpRequestDoneSignal;
}
public override void Run()
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
string responseString = null;
try
{
response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm()));
StatusLine statusLine = response.GetStatusLine();
NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScOk);
if (statusLine.GetStatusCode() == HttpStatus.ScOk)
{
ByteArrayOutputStream @out = new ByteArrayOutputStream();
response.GetEntity().WriteTo(@out);
@out.Close();
responseString = @out.ToString();
NUnit.Framework.Assert.IsTrue(responseString.Contains(doc1Id));
Log.D(ReplicationTest.Tag, "result: " + responseString);
}
else
{
response.GetEntity().GetContent().Close();
throw new IOException(statusLine.GetReasonPhrase());
}
}
catch (ClientProtocolException e)
{
NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
(), e);
}
catch (IOException e)
{
NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
}
httpRequestDoneSignal.CountDown();
}
private readonly Uri pathToDoc;
private readonly string doc1Id;
private readonly CountDownLatch httpRequestDoneSignal;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestPusherDeletedDoc()
{
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
Uri remote = GetReplicationURL();
string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis());
// Create some documents:
IDictionary<string, object> documentProperties = new Dictionary<string, object>();
string doc1Id = string.Format("doc1-%s", docIdTimestamp);
documentProperties.Put("_id", doc1Id);
documentProperties.Put("foo", 1);
documentProperties.Put("bar", false);
Body body = new Body(documentProperties);
RevisionInternal rev1 = new RevisionInternal(body, database);
Status status = new Status();
rev1 = database.PutRevision(rev1, null, false, status);
NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode());
documentProperties.Put("_rev", rev1.GetRevId());
documentProperties.Put("UPDATED", true);
documentProperties.Put("_deleted", true);
RevisionInternal rev2 = database.PutRevision(new RevisionInternal(documentProperties
, database), rev1.GetRevId(), false, status);
NUnit.Framework.Assert.IsTrue(status.GetCode() >= 200 && status.GetCode() < 300);
Replication repl = database.CreatePushReplication(remote);
((Pusher)repl).SetCreateTarget(true);
RunReplication(repl);
// make sure doc1 is deleted
Uri replicationUrlTrailing = new Uri(string.Format("%s/", remote.ToExternalForm()
));
Uri pathToDoc = new Uri(replicationUrlTrailing, doc1Id);
Log.D(Tag, "Send http request to " + pathToDoc);
CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
BackgroundTask getDocTask = new _BackgroundTask_216(pathToDoc, httpRequestDoneSignal
);
getDocTask.Execute();
Log.D(Tag, "Waiting for http request to finish");
try
{
httpRequestDoneSignal.Await(300, TimeUnit.Seconds);
Log.D(Tag, "http request finished");
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
Log.D(Tag, "testPusherDeletedDoc() finished");
}
private sealed class _BackgroundTask_216 : BackgroundTask
{
public _BackgroundTask_216(Uri pathToDoc, CountDownLatch httpRequestDoneSignal)
{
this.pathToDoc = pathToDoc;
this.httpRequestDoneSignal = httpRequestDoneSignal;
}
public override void Run()
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
string responseString = null;
try
{
response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm()));
StatusLine statusLine = response.GetStatusLine();
Log.D(ReplicationTest.Tag, "statusLine " + statusLine);
NUnit.Framework.Assert.AreEqual(HttpStatus.ScNotFound, statusLine.GetStatusCode()
);
}
catch (ClientProtocolException e)
{
NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
(), e);
}
catch (IOException e)
{
NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
}
finally
{
httpRequestDoneSignal.CountDown();
}
}
private readonly Uri pathToDoc;
private readonly CountDownLatch httpRequestDoneSignal;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestPuller()
{
string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis());
string doc1Id = string.Format("doc1-%s", docIdTimestamp);
string doc2Id = string.Format("doc2-%s", docIdTimestamp);
AddDocWithId(doc1Id, "attachment.png");
AddDocWithId(doc2Id, "attachment2.png");
// workaround for https://github.com/couchbase/sync_gateway/issues/228
Sharpen.Thread.Sleep(1000);
DoPullReplication();
Log.D(Tag, "Fetching doc1 via id: " + doc1Id);
RevisionInternal doc1 = database.GetDocumentWithIDAndRev(doc1Id, null, EnumSet.NoneOf
<Database.TDContentOptions>());
NUnit.Framework.Assert.IsNotNull(doc1);
NUnit.Framework.Assert.IsTrue(doc1.GetRevId().StartsWith("1-"));
NUnit.Framework.Assert.AreEqual(1, doc1.GetProperties().Get("foo"));
Log.D(Tag, "Fetching doc2 via id: " + doc2Id);
RevisionInternal doc2 = database.GetDocumentWithIDAndRev(doc2Id, null, EnumSet.NoneOf
<Database.TDContentOptions>());
NUnit.Framework.Assert.IsNotNull(doc2);
NUnit.Framework.Assert.IsTrue(doc2.GetRevId().StartsWith("1-"));
NUnit.Framework.Assert.AreEqual(1, doc2.GetProperties().Get("foo"));
Log.D(Tag, "testPuller() finished");
}
/// <exception cref="System.Exception"></exception>
public virtual void TestPullerWithLiveQuery()
{
// This is essentially a regression test for a deadlock
// that was happening when the LiveQuery#onDatabaseChanged()
// was calling waitForUpdateThread(), but that thread was
// waiting on connection to be released by the thread calling
// waitForUpdateThread(). When the deadlock bug was present,
// this test would trigger the deadlock and never finish.
Log.D(Database.Tag, "testPullerWithLiveQuery");
string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis());
string doc1Id = string.Format("doc1-%s", docIdTimestamp);
string doc2Id = string.Format("doc2-%s", docIdTimestamp);
AddDocWithId(doc1Id, "attachment2.png");
AddDocWithId(doc2Id, "attachment2.png");
int numDocsBeforePull = database.GetDocumentCount();
View view = database.GetView("testPullerWithLiveQueryView");
view.SetMapAndReduce(new _Mapper_307(), null, "1");
LiveQuery allDocsLiveQuery = view.CreateQuery().ToLiveQuery();
allDocsLiveQuery.AddChangeListener(new _ChangeListener_317(numDocsBeforePull));
// the first time this is called back, the rows will be empty.
// but on subsequent times we should expect to get a non empty
// row set.
allDocsLiveQuery.Start();
DoPullReplication();
}
private sealed class _Mapper_307 : Mapper
{
public _Mapper_307()
{
}
public void Map(IDictionary<string, object> document, Emitter emitter)
{
if (document.Get("_id") != null)
{
emitter.Emit(document.Get("_id"), null);
}
}
}
private sealed class _ChangeListener_317 : LiveQuery.ChangeListener
{
public _ChangeListener_317(int numDocsBeforePull)
{
this.numDocsBeforePull = numDocsBeforePull;
}
public void Changed(LiveQuery.ChangeEvent @event)
{
int numTimesCalled = 0;
if (@event.GetError() != null)
{
throw new RuntimeException(@event.GetError());
}
if (numTimesCalled++ > 0)
{
NUnit.Framework.Assert.IsTrue(@event.GetRows().GetCount() > numDocsBeforePull);
}
Log.D(Database.Tag, "rows " + @event.GetRows());
}
private readonly int numDocsBeforePull;
}
private void DoPullReplication()
{
Uri remote = GetReplicationURL();
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
Replication repl = (Replication)database.CreatePullReplication(remote);
repl.SetContinuous(false);
RunReplication(repl);
}
/// <exception cref="System.IO.IOException"></exception>
private void AddDocWithId(string docId, string attachmentName)
{
string docJson;
if (attachmentName != null)
{
// add attachment to document
InputStream attachmentStream = GetAsset(attachmentName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.Copy(attachmentStream, baos);
string attachmentBase64 = Base64.EncodeBytes(baos.ToByteArray());
docJson = string.Format("{\"foo\":1,\"bar\":false, \"_attachments\": { \"i_use_couchdb.png\": { \"content_type\": \"image/png\", \"data\": \"%s\" } } }"
, attachmentBase64);
}
else
{
docJson = "{\"foo\":1,\"bar\":false}";
}
// push a document to server
Uri replicationUrlTrailingDoc1 = new Uri(string.Format("%s/%s", GetReplicationURL
().ToExternalForm(), docId));
Uri pathToDoc1 = new Uri(replicationUrlTrailingDoc1, docId);
Log.D(Tag, "Send http request to " + pathToDoc1);
CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
BackgroundTask getDocTask = new _BackgroundTask_376(pathToDoc1, docJson, httpRequestDoneSignal
);
getDocTask.Execute();
Log.D(Tag, "Waiting for http request to finish");
try
{
httpRequestDoneSignal.Await(300, TimeUnit.Seconds);
Log.D(Tag, "http request finished");
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
}
private sealed class _BackgroundTask_376 : BackgroundTask
{
public _BackgroundTask_376(Uri pathToDoc1, string docJson, CountDownLatch httpRequestDoneSignal
)
{
this.pathToDoc1 = pathToDoc1;
this.docJson = docJson;
this.httpRequestDoneSignal = httpRequestDoneSignal;
}
public override void Run()
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
string responseString = null;
try
{
HttpPut post = new HttpPut(pathToDoc1.ToExternalForm());
StringEntity se = new StringEntity(docJson.ToString());
se.SetContentType(new BasicHeader("content_type", "application/json"));
post.SetEntity(se);
response = httpclient.Execute(post);
StatusLine statusLine = response.GetStatusLine();
Log.D(ReplicationTest.Tag, "Got response: " + statusLine);
NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScCreated);
}
catch (ClientProtocolException e)
{
NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage
(), e);
}
catch (IOException e)
{
NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e);
}
httpRequestDoneSignal.CountDown();
}
private readonly Uri pathToDoc1;
private readonly string docJson;
private readonly CountDownLatch httpRequestDoneSignal;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestGetReplicator()
{
IDictionary<string, object> properties = new Dictionary<string, object>();
properties.Put("source", DefaultTestDb);
properties.Put("target", GetReplicationURL().ToExternalForm());
Replication replicator = manager.GetReplicator(properties);
NUnit.Framework.Assert.IsNotNull(replicator);
NUnit.Framework.Assert.AreEqual(GetReplicationURL().ToExternalForm(), replicator.
GetRemoteUrl().ToExternalForm());
NUnit.Framework.Assert.IsTrue(!replicator.IsPull());
NUnit.Framework.Assert.IsFalse(replicator.IsContinuous());
NUnit.Framework.Assert.IsFalse(replicator.IsRunning());
// start the replicator
replicator.Start();
// now lets lookup existing replicator and stop it
properties.Put("cancel", true);
Replication activeReplicator = manager.GetReplicator(properties);
activeReplicator.Stop();
NUnit.Framework.Assert.IsFalse(activeReplicator.IsRunning());
}
/// <exception cref="System.Exception"></exception>
public virtual void TestGetReplicatorWithAuth()
{
IDictionary<string, object> properties = GetPushReplicationParsedJson();
Replication replicator = manager.GetReplicator(properties);
NUnit.Framework.Assert.IsNotNull(replicator);
NUnit.Framework.Assert.IsNotNull(replicator.GetAuthorizer());
NUnit.Framework.Assert.IsTrue(replicator.GetAuthorizer() is FacebookAuthorizer);
}
private void RunReplication(Replication replication)
{
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
ReplicationTest.ReplicationObserver replicationObserver = new ReplicationTest.ReplicationObserver
(this, replicationDoneSignal);
replication.AddChangeListener(replicationObserver);
replication.Start();
CountDownLatch replicationDoneSignalPolling = ReplicationWatcherThread(replication
);
Log.D(Tag, "Waiting for replicator to finish");
try
{
bool success = replicationDoneSignal.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(success);
success = replicationDoneSignalPolling.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(success);
Log.D(Tag, "replicator finished");
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
}
private CountDownLatch ReplicationWatcherThread(Replication replication)
{
CountDownLatch doneSignal = new CountDownLatch(1);
new Sharpen.Thread(new _Runnable_482(replication, doneSignal)).Start();
return doneSignal;
}
private sealed class _Runnable_482 : Runnable
{
public _Runnable_482(Replication replication, CountDownLatch doneSignal)
{
this.replication = replication;
this.doneSignal = doneSignal;
}
public void Run()
{
bool started = false;
bool done = false;
while (!done)
{
if (replication.IsRunning())
{
started = true;
}
bool statusIsDone = (replication.GetStatus() == Replication.ReplicationStatus.ReplicationStopped
|| replication.GetStatus() == Replication.ReplicationStatus.ReplicationIdle);
if (started && statusIsDone)
{
done = true;
}
try
{
Sharpen.Thread.Sleep(500);
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
}
doneSignal.CountDown();
}
private readonly Replication replication;
private readonly CountDownLatch doneSignal;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestRunReplicationWithError()
{
HttpClientFactory mockHttpClientFactory = new _HttpClientFactory_516();
string dbUrlString = "http://fake.test-url.com:4984/fake/";
Uri remote = new Uri(dbUrlString);
bool continuous = false;
Replication r1 = new Puller(database, remote, continuous, mockHttpClientFactory,
manager.GetWorkExecutor());
NUnit.Framework.Assert.IsFalse(r1.IsContinuous());
RunReplication(r1);
// It should have failed with a 404:
NUnit.Framework.Assert.AreEqual(Replication.ReplicationStatus.ReplicationStopped,
r1.GetStatus());
NUnit.Framework.Assert.AreEqual(0, r1.GetCompletedChangesCount());
NUnit.Framework.Assert.AreEqual(0, r1.GetChangesCount());
NUnit.Framework.Assert.IsNotNull(r1.GetLastError());
}
private sealed class _HttpClientFactory_516 : HttpClientFactory
{
public _HttpClientFactory_516()
{
}
public HttpClient GetHttpClient()
{
CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient();
int statusCode = 500;
mockHttpClient.AddResponderFailAllRequests(statusCode);
return mockHttpClient;
}
}
/// <exception cref="System.Exception"></exception>
public virtual void TestReplicatorErrorStatus()
{
Assert.Fail(); // NOTE.ZJG: Need to remove FB & Persona login stuff.
// register bogus fb token
IDictionary<string, object> facebookTokenInfo = new Dictionary<string, object>();
facebookTokenInfo.Put("email", "[email protected]");
facebookTokenInfo.Put("remote_url", GetReplicationURL().ToExternalForm());
facebookTokenInfo.Put("access_token", "fake_access_token");
string destUrl = string.Format("/_facebook_token", DefaultTestDb);
IDictionary<string, object> result = (IDictionary<string, object>)SendBody("POST"
, destUrl, facebookTokenInfo, Status.Ok, null);
Log.V(Tag, string.Format("result %s", result));
// start a replicator
IDictionary<string, object> properties = GetPullReplicationParsedJson();
Replication replicator = manager.GetReplicator(properties);
replicator.Start();
bool foundError = false;
for (int i = 0; i < 10; i++)
{
// wait a few seconds
Sharpen.Thread.Sleep(5 * 1000);
// expect an error since it will try to contact the sync gateway with this bogus login,
// and the sync gateway will reject it.
AList<object> activeTasks = (AList<object>)Send("GET", "/_active_tasks", Status.Ok
, null);
Log.D(Tag, "activeTasks: " + activeTasks);
IDictionary<string, object> activeTaskReplication = (IDictionary<string, object>)
activeTasks[0];
foundError = (activeTaskReplication.Get("error") != null);
if (foundError == true)
{
break;
}
}
NUnit.Framework.Assert.IsTrue(foundError);
}
/// <exception cref="System.Exception"></exception>
public virtual void TestFetchRemoteCheckpointDoc()
{
HttpClientFactory mockHttpClientFactory = new _HttpClientFactory_583();
Log.D("TEST", "testFetchRemoteCheckpointDoc() called");
string dbUrlString = "http://fake.test-url.com:4984/fake/";
Uri remote = new Uri(dbUrlString);
database.SetLastSequence("1", remote, true);
// otherwise fetchRemoteCheckpoint won't contact remote
Replication replicator = new Pusher(database, remote, false, mockHttpClientFactory
, manager.GetWorkExecutor());
CountDownLatch doneSignal = new CountDownLatch(1);
ReplicationTest.ReplicationObserver replicationObserver = new ReplicationTest.ReplicationObserver
(this, doneSignal);
replicator.AddChangeListener(replicationObserver);
replicator.FetchRemoteCheckpointDoc();
Log.D(Tag, "testFetchRemoteCheckpointDoc() Waiting for replicator to finish");
try
{
bool succeeded = doneSignal.Await(300, TimeUnit.Seconds);
NUnit.Framework.Assert.IsTrue(succeeded);
Log.D(Tag, "testFetchRemoteCheckpointDoc() replicator finished");
}
catch (Exception e)
{
Sharpen.Runtime.PrintStackTrace(e);
}
string errorMessage = "Since we are passing in a mock http client that always throws "
+ "errors, we expect the replicator to be in an error state";
NUnit.Framework.Assert.IsNotNull(errorMessage, replicator.GetLastError());
}
private sealed class _HttpClientFactory_583 : HttpClientFactory
{
public _HttpClientFactory_583()
{
}
public HttpClient GetHttpClient()
{
CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient();
mockHttpClient.AddResponderThrowExceptionAllRequests();
return mockHttpClient;
}
}
/// <exception cref="System.Exception"></exception>
public virtual void TestGoOffline()
{
Uri remote = GetReplicationURL();
CountDownLatch replicationDoneSignal = new CountDownLatch(1);
Replication repl = database.CreatePullReplication(remote);
repl.SetContinuous(true);
repl.Start();
repl.GoOffline();
NUnit.Framework.Assert.IsTrue(repl.GetStatus() == Replication.ReplicationStatus.ReplicationOffline
);
}
internal class ReplicationObserver : Replication.ChangeListener
{
public bool replicationFinished = false;
private CountDownLatch doneSignal;
internal ReplicationObserver(ReplicationTest _enclosing, CountDownLatch doneSignal
)
{
this._enclosing = _enclosing;
this.doneSignal = doneSignal;
}
public virtual void Changed(Replication.ChangeEvent @event)
{
Replication replicator = @event.GetSource();
if (!replicator.IsRunning())
{
this.replicationFinished = true;
string msg = string.Format("myobserver.update called, set replicationFinished to: %b"
, this.replicationFinished);
Log.D(ReplicationTest.Tag, msg);
this.doneSignal.CountDown();
}
else
{
string msg = string.Format("myobserver.update called, but replicator still running, so ignore it"
);
Log.D(ReplicationTest.Tag, msg);
}
}
internal virtual bool IsReplicationFinished()
{
return this.replicationFinished;
}
private readonly ReplicationTest _enclosing;
}
/// <exception cref="System.Exception"></exception>
public virtual void TestBuildRelativeURLString()
{
string dbUrlString = "http://10.0.0.3:4984/todos/";
Replication replicator = new Pusher(null, new Uri(dbUrlString), false, null);
string relativeUrlString = replicator.BuildRelativeURLString("foo");
string expected = "http://10.0.0.3:4984/todos/foo";
NUnit.Framework.Assert.AreEqual(expected, relativeUrlString);
}
/// <exception cref="System.Exception"></exception>
public virtual void TestBuildRelativeURLStringWithLeadingSlash()
{
string dbUrlString = "http://10.0.0.3:4984/todos/";
Replication replicator = new Pusher(null, new Uri(dbUrlString), false, null);
string relativeUrlString = replicator.BuildRelativeURLString("/foo");
string expected = "http://10.0.0.3:4984/todos/foo";
NUnit.Framework.Assert.AreEqual(expected, relativeUrlString);
}
/// <exception cref="System.Exception"></exception>
public virtual void TestChannels()
{
Uri remote = GetReplicationURL();
Replication replicator = database.CreatePullReplication(remote);
IList<string> channels = new AList<string>();
channels.AddItem("chan1");
channels.AddItem("chan2");
replicator.SetChannels(channels);
NUnit.Framework.Assert.AreEqual(channels, replicator.GetChannels());
replicator.SetChannels(null);
NUnit.Framework.Assert.IsTrue(replicator.GetChannels().IsEmpty());
}
/// <exception cref="System.UriFormatException"></exception>
public virtual void TestChannelsMore()
{
Database db = StartDatabase();
Uri fakeRemoteURL = new Uri("http://couchbase.com/no_such_db");
Replication r1 = db.CreatePullReplication(fakeRemoteURL);
NUnit.Framework.Assert.IsTrue(r1.GetChannels().IsEmpty());
r1.SetFilter("foo/bar");
NUnit.Framework.Assert.IsTrue(r1.GetChannels().IsEmpty());
IDictionary<string, object> filterParams = new Dictionary<string, object>();
filterParams.Put("a", "b");
r1.SetFilterParams(filterParams);
NUnit.Framework.Assert.IsTrue(r1.GetChannels().IsEmpty());
r1.SetChannels(null);
NUnit.Framework.Assert.AreEqual("foo/bar", r1.GetFilter());
NUnit.Framework.Assert.AreEqual(filterParams, r1.GetFilterParams());
IList<string> channels = new AList<string>();
channels.AddItem("NBC");
channels.AddItem("MTV");
r1.SetChannels(channels);
NUnit.Framework.Assert.AreEqual(channels, r1.GetChannels());
NUnit.Framework.Assert.AreEqual("sync_gateway/bychannel", r1.GetFilter());
filterParams = new Dictionary<string, object>();
filterParams.Put("channels", "NBC,MTV");
NUnit.Framework.Assert.AreEqual(filterParams, r1.GetFilterParams());
r1.SetChannels(null);
NUnit.Framework.Assert.AreEqual(r1.GetFilter(), null);
NUnit.Framework.Assert.AreEqual(null, r1.GetFilterParams());
}
/// <exception cref="System.Exception"></exception>
public virtual void TestHeaders()
{
CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient();
mockHttpClient.AddResponderThrowExceptionAllRequests();
HttpClientFactory mockHttpClientFactory = new _HttpClientFactory_741(mockHttpClient
);
Uri remote = GetReplicationURL();
manager.SetDefaultHttpClientFactory(mockHttpClientFactory);
Replication puller = database.CreatePullReplication(remote);
IDictionary<string, object> headers = new Dictionary<string, object>();
headers.Put("foo", "bar");
puller.SetHeaders(headers);
puller.Start();
Sharpen.Thread.Sleep(2000);
puller.Stop();
bool foundFooHeader = false;
IList<HttpWebRequest> requests = mockHttpClient.GetCapturedRequests();
foreach (HttpWebRequest request in requests)
{
Header[] requestHeaders = request.GetHeaders("foo");
foreach (Header requestHeader in requestHeaders)
{
foundFooHeader = true;
NUnit.Framework.Assert.AreEqual("bar", requestHeader.GetValue());
}
}
NUnit.Framework.Assert.IsTrue(foundFooHeader);
manager.SetDefaultHttpClientFactory(null);
}
private sealed class _HttpClientFactory_741 : HttpClientFactory
{
public _HttpClientFactory_741(CustomizableMockHttpClient mockHttpClient)
{
this.mockHttpClient = mockHttpClient;
}
public HttpClient GetHttpClient()
{
return mockHttpClient;
}
private readonly CustomizableMockHttpClient mockHttpClient;
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// SkinningSample.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using SkinnedModel;
#endregion
namespace SkinningSample
{
/// <summary>
/// Sample game showing how to display skinned character animation.
/// </summary>
public class SkinningSampleGame : Microsoft.Xna.Framework.Game
{
#region Fields
GraphicsDeviceManager graphics;
KeyboardState currentKeyboardState = new KeyboardState();
GamePadState currentGamePadState = new GamePadState();
Model currentModel;
AnimationPlayer animationPlayer;
float cameraArc = 0;
float cameraRotation = 0;
float cameraDistance = 100;
#endregion
#region Initialization
public SkinningSampleGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
#if WINDOWS_PHONE
// Frame rate is 30 fps by default for Windows Phone.
TargetElapsedTime = TimeSpan.FromTicks(333333);
graphics.IsFullScreen = true;
#endif
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
// Load the model.
currentModel = Content.Load<Model>("dude");
// Look up our custom skinning information.
SkinningData skinningData = currentModel.Tag as SkinningData;
if (skinningData == null)
throw new InvalidOperationException
("This model does not contain a SkinningData tag.");
// Create an animation player, and start decoding an animation clip.
animationPlayer = new AnimationPlayer(skinningData);
AnimationClip clip = skinningData.AnimationClips["Take 001"];
animationPlayer.StartClip(clip);
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the game to run logic.
/// </summary>
protected override void Update(GameTime gameTime)
{
HandleInput();
UpdateCamera(gameTime);
animationPlayer.Update(gameTime.ElapsedGameTime, true, Matrix.Identity);
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice device = graphics.GraphicsDevice;
device.Clear(Color.CornflowerBlue);
Matrix[] bones = animationPlayer.GetSkinTransforms();
// Compute camera matrices.
Matrix view = Matrix.CreateTranslation(0, -40, 0) *
Matrix.CreateRotationY(MathHelper.ToRadians(cameraRotation)) *
Matrix.CreateRotationX(MathHelper.ToRadians(cameraArc)) *
Matrix.CreateLookAt(new Vector3(0, 0, -cameraDistance),
new Vector3(0, 0, 0), Vector3.Up);
Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
device.Viewport.AspectRatio,
1,
10000);
// Render the skinned mesh.
foreach (ModelMesh mesh in currentModel.Meshes)
{
foreach (SkinnedEffect effect in mesh.Effects)
{
effect.SetBoneTransforms(bones);
effect.View = view;
effect.Projection = projection;
effect.EnableDefaultLighting();
effect.SpecularColor = new Vector3(0.25f);
effect.SpecularPower = 16;
}
mesh.Draw();
}
base.Draw(gameTime);
}
#endregion
#region Handle Input
/// <summary>
/// Handles input for quitting the game.
/// </summary>
private void HandleInput()
{
currentKeyboardState = Keyboard.GetState();
currentGamePadState = GamePad.GetState(PlayerIndex.One);
// Check for exit.
if (currentKeyboardState.IsKeyDown(Keys.Escape) ||
currentGamePadState.Buttons.Back == ButtonState.Pressed)
{
Exit();
}
}
/// <summary>
/// Handles camera input.
/// </summary>
private void UpdateCamera(GameTime gameTime)
{
float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;
// Check for input to rotate the camera up and down around the model.
if (currentKeyboardState.IsKeyDown(Keys.Up) ||
currentKeyboardState.IsKeyDown(Keys.W))
{
cameraArc += time * 0.1f;
}
if (currentKeyboardState.IsKeyDown(Keys.Down) ||
currentKeyboardState.IsKeyDown(Keys.S))
{
cameraArc -= time * 0.1f;
}
cameraArc += currentGamePadState.ThumbSticks.Right.Y * time * 0.25f;
// Limit the arc movement.
if (cameraArc > 90.0f)
cameraArc = 90.0f;
else if (cameraArc < -90.0f)
cameraArc = -90.0f;
// Check for input to rotate the camera around the model.
if (currentKeyboardState.IsKeyDown(Keys.Right) ||
currentKeyboardState.IsKeyDown(Keys.D))
{
cameraRotation += time * 0.1f;
}
if (currentKeyboardState.IsKeyDown(Keys.Left) ||
currentKeyboardState.IsKeyDown(Keys.A))
{
cameraRotation -= time * 0.1f;
}
cameraRotation += currentGamePadState.ThumbSticks.Right.X * time * 0.25f;
// Check for input to zoom camera in and out.
if (currentKeyboardState.IsKeyDown(Keys.Z))
cameraDistance += time * 0.25f;
if (currentKeyboardState.IsKeyDown(Keys.X))
cameraDistance -= time * 0.25f;
cameraDistance += currentGamePadState.Triggers.Left * time * 0.5f;
cameraDistance -= currentGamePadState.Triggers.Right * time * 0.5f;
// Limit the camera distance.
if (cameraDistance > 500.0f)
cameraDistance = 500.0f;
else if (cameraDistance < 10.0f)
cameraDistance = 10.0f;
if (currentGamePadState.Buttons.RightStick == ButtonState.Pressed ||
currentKeyboardState.IsKeyDown(Keys.R))
{
cameraArc = 0;
cameraRotation = 0;
cameraDistance = 100;
}
}
#endregion
}
#region Entry Point
/// <summary>
/// The main entry point for the application.
/// </summary>
static class Program
{
static void Main()
{
using (SkinningSampleGame game = new SkinningSampleGame())
{
game.Run();
}
}
}
#endregion
}
| |
using Microsoft.PowerShell.Activities;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerShell.Activities
{
/// <summary>
/// Activity to invoke the CimCmdlets\New-CimSessionOption command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class NewCimSessionOption : GenericCimCmdletActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public NewCimSessionOption()
{
this.DisplayName = "New-CimSessionOption";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "CimCmdlets\\New-CimSessionOption"; } }
/// <summary>
/// The .NET type implementing the cmdlet to invoke.
/// </summary>
public override System.Type TypeImplementingCmdlet { get { return typeof(Microsoft.Management.Infrastructure.CimCmdlets.NewCimSessionOptionCommand); } }
// Arguments
/// <summary>
/// Provides access to the NoEncryption parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> NoEncryption { get; set; }
/// <summary>
/// Provides access to the CertificateCACheck parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> CertificateCACheck { get; set; }
/// <summary>
/// Provides access to the CertificateCNCheck parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> CertificateCNCheck { get; set; }
/// <summary>
/// Provides access to the CertRevocationCheck parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> CertRevocationCheck { get; set; }
/// <summary>
/// Provides access to the EncodePortInServicePrincipalName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> EncodePortInServicePrincipalName { get; set; }
/// <summary>
/// Provides access to the Encoding parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.Management.Infrastructure.Options.PacketEncoding> Encoding { get; set; }
/// <summary>
/// Provides access to the HttpPrefix parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Uri> HttpPrefix { get; set; }
/// <summary>
/// Provides access to the MaxEnvelopeSizeKB parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.UInt32> MaxEnvelopeSizeKB { get; set; }
/// <summary>
/// Provides access to the ProxyAuthentication parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.Management.Infrastructure.Options.PasswordAuthenticationMechanism> ProxyAuthentication { get; set; }
/// <summary>
/// Provides access to the ProxyCertificateThumbprint parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ProxyCertificateThumbprint { get; set; }
/// <summary>
/// Provides access to the ProxyCredential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> ProxyCredential { get; set; }
/// <summary>
/// Provides access to the ProxyType parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.Management.Infrastructure.Options.ProxyType> ProxyType { get; set; }
/// <summary>
/// Provides access to the UseSsl parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> UseSsl { get; set; }
/// <summary>
/// Provides access to the Impersonation parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.Management.Infrastructure.Options.ImpersonationType> Impersonation { get; set; }
/// <summary>
/// Provides access to the PacketIntegrity parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> PacketIntegrity { get; set; }
/// <summary>
/// Provides access to the PacketPrivacy parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> PacketPrivacy { get; set; }
/// <summary>
/// Provides access to the Protocol parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.Management.Infrastructure.CimCmdlets.ProtocolType> Protocol { get; set; }
/// <summary>
/// Provides access to the UICulture parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Globalization.CultureInfo> UICulture { get; set; }
/// <summary>
/// Provides access to the Culture parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Globalization.CultureInfo> Culture { get; set; }
/// <summary>
/// Script module contents for this activity`n/// </summary>
protected override string PSDefiningModule { get { return null; } }
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(NoEncryption.Expression != null)
{
targetCommand.AddParameter("NoEncryption", NoEncryption.Get(context));
}
if(CertificateCACheck.Expression != null)
{
targetCommand.AddParameter("CertificateCACheck", CertificateCACheck.Get(context));
}
if(CertificateCNCheck.Expression != null)
{
targetCommand.AddParameter("CertificateCNCheck", CertificateCNCheck.Get(context));
}
if(CertRevocationCheck.Expression != null)
{
targetCommand.AddParameter("CertRevocationCheck", CertRevocationCheck.Get(context));
}
if(EncodePortInServicePrincipalName.Expression != null)
{
targetCommand.AddParameter("EncodePortInServicePrincipalName", EncodePortInServicePrincipalName.Get(context));
}
if(Encoding.Expression != null)
{
targetCommand.AddParameter("Encoding", Encoding.Get(context));
}
if(HttpPrefix.Expression != null)
{
targetCommand.AddParameter("HttpPrefix", HttpPrefix.Get(context));
}
if(MaxEnvelopeSizeKB.Expression != null)
{
targetCommand.AddParameter("MaxEnvelopeSizeKB", MaxEnvelopeSizeKB.Get(context));
}
if(ProxyAuthentication.Expression != null)
{
targetCommand.AddParameter("ProxyAuthentication", ProxyAuthentication.Get(context));
}
if(ProxyCertificateThumbprint.Expression != null)
{
targetCommand.AddParameter("ProxyCertificateThumbprint", ProxyCertificateThumbprint.Get(context));
}
if(ProxyCredential.Expression != null)
{
targetCommand.AddParameter("ProxyCredential", ProxyCredential.Get(context));
}
if(ProxyType.Expression != null)
{
targetCommand.AddParameter("ProxyType", ProxyType.Get(context));
}
if(UseSsl.Expression != null)
{
targetCommand.AddParameter("UseSsl", UseSsl.Get(context));
}
if(Impersonation.Expression != null)
{
targetCommand.AddParameter("Impersonation", Impersonation.Get(context));
}
if(PacketIntegrity.Expression != null)
{
targetCommand.AddParameter("PacketIntegrity", PacketIntegrity.Get(context));
}
if(PacketPrivacy.Expression != null)
{
targetCommand.AddParameter("PacketPrivacy", PacketPrivacy.Get(context));
}
if(Protocol.Expression != null)
{
targetCommand.AddParameter("Protocol", Protocol.Get(context));
}
if(UICulture.Expression != null)
{
targetCommand.AddParameter("UICulture", UICulture.Get(context));
}
if(Culture.Expression != null)
{
targetCommand.AddParameter("Culture", Culture.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
public static class PathTests
{
[Theory]
[InlineData(null, null, null)]
[InlineData(null, null, "exe")]
[InlineData("", "", "")]
[InlineData("file", "file.exe", null)]
[InlineData("file.", "file.exe", "")]
[InlineData("file.exe", "file", "exe")]
[InlineData("file.exe", "file", ".exe")]
[InlineData("file.exe", "file.txt", "exe")]
[InlineData("file.exe", "file.txt", ".exe")]
[InlineData("file.txt.exe", "file.txt.bin", "exe")]
[InlineData("dir/file.exe", "dir/file.t", "exe")]
[InlineData("dir/file.t", "dir/file.exe", "t")]
[InlineData("dir/file.exe", "dir/file", "exe")]
public static void ChangeExtension(string expected, string path, string newExtension)
{
if (expected != null)
expected = expected.Replace('/', Path.DirectorySeparatorChar);
if (path != null)
path = path.Replace('/', Path.DirectorySeparatorChar);
Assert.Equal(expected, Path.ChangeExtension(path, newExtension));
}
[Fact]
public static void GetDirectoryName()
{
Assert.Null(Path.GetDirectoryName(null));
Assert.Null(Path.GetDirectoryName(string.Empty));
Assert.Equal(string.Empty, Path.GetDirectoryName("."));
Assert.Equal(string.Empty, Path.GetDirectoryName(".."));
Assert.Equal(string.Empty, Path.GetDirectoryName("baz"));
Assert.Equal("dir", Path.GetDirectoryName(Path.Combine("dir", "baz")));
Assert.Equal(Path.Combine("dir", "baz"), Path.GetDirectoryName(Path.Combine("dir", "baz", "bar")));
string curDir = Directory.GetCurrentDirectory();
Assert.Equal(curDir, Path.GetDirectoryName(Path.Combine(curDir, "baz")));
Assert.Equal(null, Path.GetDirectoryName(Path.GetPathRoot(curDir)));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetDirectoryName_Unix()
{
Assert.Equal(new string('\t', 1), Path.GetDirectoryName(Path.Combine(new string('\t', 1), "file")));
Assert.Equal(new string('\b', 2), Path.GetDirectoryName(Path.Combine(new string('\b', 2), "fi le")));
Assert.Equal(new string('\v', 3), Path.GetDirectoryName(Path.Combine(new string('\v', 3), "fi\nle")));
Assert.Equal(new string('\n', 4), Path.GetDirectoryName(Path.Combine(new string('\n', 4), "fi\rle")));
}
[Theory]
[InlineData(".exe", "file.exe")]
[InlineData("", "file")]
[InlineData(null, null)]
[InlineData("", "file.")]
[InlineData(".s", "file.s")]
[InlineData("", "test/file")]
[InlineData(".extension", "test/file.extension")]
public static void GetExtension(string expected, string path)
{
if (path != null)
{
path = path.Replace('/', Path.DirectorySeparatorChar);
}
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData(".e xe", "file.e xe")]
[InlineData(". ", "file. ")]
[InlineData(". ", " file. ")]
[InlineData(".extension", " file.extension")]
[InlineData(".exten\tsion", "file.exten\tsion")]
public static void GetExtension_Unix(string expected, string path)
{
Assert.Equal(expected, Path.GetExtension(path));
Assert.Equal(!string.IsNullOrEmpty(expected), Path.HasExtension(path));
}
[Fact]
public static void GetFileName()
{
Assert.Equal(null, Path.GetFileName(null));
Assert.Equal(string.Empty, Path.GetFileName(string.Empty));
Assert.Equal(".", Path.GetFileName("."));
Assert.Equal("..", Path.GetFileName(".."));
Assert.Equal("file", Path.GetFileName("file"));
Assert.Equal("file.", Path.GetFileName("file."));
Assert.Equal("file.exe", Path.GetFileName("file.exe"));
Assert.Equal("file.exe", Path.GetFileName(Path.Combine("baz", "file.exe")));
Assert.Equal("file.exe", Path.GetFileName(Path.Combine("bar", "baz", "file.exe")));
Assert.Equal(string.Empty, Path.GetFileName(Path.Combine("bar", "baz") + Path.DirectorySeparatorChar));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetFileName_Unix()
{
Assert.Equal(" . ", Path.GetFileName(" . "));
Assert.Equal(" .. ", Path.GetFileName(" .. "));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName("fi le"));
Assert.Equal("fi le", Path.GetFileName(Path.Combine("b \r\n ar", "fi le")));
}
[Fact]
public static void GetFileNameWithoutExtension()
{
Assert.Equal(null, Path.GetFileNameWithoutExtension(null));
Assert.Equal(string.Empty, Path.GetFileNameWithoutExtension(string.Empty));
Assert.Equal("file", Path.GetFileNameWithoutExtension("file"));
Assert.Equal("file", Path.GetFileNameWithoutExtension("file.exe"));
Assert.Equal("file", Path.GetFileNameWithoutExtension(Path.Combine("bar", "baz", "file.exe")));
Assert.Equal(string.Empty, Path.GetFileNameWithoutExtension(Path.Combine("bar", "baz") + Path.DirectorySeparatorChar));
}
[Fact]
public static void GetPathRoot()
{
Assert.Null(Path.GetPathRoot(null));
Assert.Equal(string.Empty, Path.GetPathRoot(string.Empty));
string cwd = Directory.GetCurrentDirectory();
Assert.Equal(cwd.Substring(0, cwd.IndexOf(Path.DirectorySeparatorChar) + 1), Path.GetPathRoot(cwd));
Assert.True(Path.IsPathRooted(cwd));
Assert.Equal(string.Empty, Path.GetPathRoot(@"file.exe"));
Assert.False(Path.IsPathRooted("file.exe"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\test\unc\path\to\something", @"\\test\unc")]
[InlineData(@"\\a\b\c\d\e", @"\\a\b")]
[InlineData(@"\\a\b\", @"\\a\b")]
[InlineData(@"\\a\b", @"\\a\b")]
[InlineData(@"\\test\unc", @"\\test\unc")]
[InlineData(@"\\?\UNC\test\unc\path\to\something", @"\\?\UNC\test\unc")]
[InlineData(@"\\?\UNC\test\unc", @"\\?\UNC\test\unc")]
[InlineData(@"\\?\UNC\a\b", @"\\?\UNC\a\b")]
[InlineData(@"\\?\UNC\a\b\", @"\\?\UNC\a\b")]
[InlineData(@"\\?\C:\foo\bar.txt", @"\\?\C:\")]
public static void GetPathRoot_Windows_UncAndExtended(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:", @"C:")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\\", @"C:\")]
[InlineData(@"C://", @"C:\")]
[InlineData(@"C:\foo", @"C:\")]
[InlineData(@"C:\\foo", @"C:\")]
[InlineData(@"C://foo", @"C:\")]
public static void GetPathRoot_Windows(string value, string expected)
{
Assert.True(Path.IsPathRooted(value));
Assert.Equal(expected, Path.GetPathRoot(value));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetPathRoot_Unix()
{
// slashes are normal filename characters
string uncPath = @"\\test\unc\path\to\something";
Assert.False(Path.IsPathRooted(uncPath));
Assert.Equal(string.Empty, Path.GetPathRoot(uncPath));
}
[Fact]
public static void GetRandomFileName()
{
char[] invalidChars = Path.GetInvalidFileNameChars();
var fileNames = new HashSet<string>();
for (int i = 0; i < 100; i++)
{
string s = Path.GetRandomFileName();
Assert.Equal(s.Length, 8 + 1 + 3);
Assert.Equal(s[8], '.');
Assert.Equal(-1, s.IndexOfAny(invalidChars));
Assert.True(fileNames.Add(s));
}
}
[Fact]
public static void GetInvalidPathChars()
{
Assert.NotNull(Path.GetInvalidPathChars());
Assert.NotSame(Path.GetInvalidPathChars(), Path.GetInvalidPathChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidPathChars(), (IEnumerable<char>)Path.GetInvalidPathChars());
Assert.True(Path.GetInvalidPathChars().Length > 0);
Assert.All(Path.GetInvalidPathChars(), c =>
{
string bad = c.ToString();
Assert.Throws<ArgumentException>(() => Path.ChangeExtension(bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine(bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine("ok", "ok", bad));
Assert.Throws<ArgumentException>(() => Path.Combine("ok", "ok", bad, "ok"));
Assert.Throws<ArgumentException>(() => Path.Combine(bad, bad, bad, bad, bad));
Assert.Throws<ArgumentException>(() => Path.GetDirectoryName(bad));
Assert.Throws<ArgumentException>(() => Path.GetExtension(bad));
Assert.Throws<ArgumentException>(() => Path.GetFileName(bad));
Assert.Throws<ArgumentException>(() => Path.GetFileNameWithoutExtension(bad));
Assert.Throws<ArgumentException>(() => Path.GetFullPath(bad));
Assert.Throws<ArgumentException>(() => Path.GetPathRoot(bad));
Assert.Throws<ArgumentException>(() => Path.IsPathRooted(bad));
});
}
[Fact]
public static void GetInvalidFileNameChars()
{
Assert.NotNull(Path.GetInvalidFileNameChars());
Assert.NotSame(Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.Equal((IEnumerable<char>)Path.GetInvalidFileNameChars(), Path.GetInvalidFileNameChars());
Assert.True(Path.GetInvalidFileNameChars().Length > 0);
}
[Fact]
[OuterLoop]
public static void GetInvalidFileNameChars_OtherCharsValid()
{
string curDir = Directory.GetCurrentDirectory();
var invalidChars = new HashSet<char>(Path.GetInvalidFileNameChars());
for (int i = 0; i < char.MaxValue; i++)
{
char c = (char)i;
if (!invalidChars.Contains(c))
{
string name = "file" + c + ".txt";
Assert.Equal(Path.Combine(curDir, name), Path.GetFullPath(name));
}
}
}
[Fact]
public static void GetTempPath_Default()
{
string tmpPath = Path.GetTempPath();
Assert.False(string.IsNullOrEmpty(tmpPath));
Assert.Equal(tmpPath, Path.GetTempPath());
Assert.Equal(Path.DirectorySeparatorChar, tmpPath[tmpPath.Length - 1]);
Assert.True(Directory.Exists(tmpPath));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp")]
[InlineData(@"C:\Users\someuser\AppData\Local\Temp\", @"C:\Users\someuser\AppData\Local\Temp\")]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\tmp\", @"C:\tmp")]
[InlineData(@"C:\tmp\", @"C:\tmp\")]
public static void GetTempPath_SetEnvVar_Windows(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMP", expected, newTempPath);
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData("/tmp/", "/tmp")]
[InlineData("/tmp/", "/tmp/")]
[InlineData("/", "/")]
[InlineData("/var/tmp/", "/var/tmp")]
[InlineData("/var/tmp/", "/var/tmp/")]
[InlineData("~/", "~")]
[InlineData("~/", "~/")]
[InlineData(".tmp/", ".tmp")]
[InlineData("./tmp/", "./tmp")]
[InlineData("/home/someuser/sometempdir/", "/home/someuser/sometempdir/")]
[InlineData("/home/someuser/some tempdir/", "/home/someuser/some tempdir/")]
[InlineData("/tmp/", null)]
public static void GetTempPath_SetEnvVar_Unix(string expected, string newTempPath)
{
GetTempPath_SetEnvVar("TMPDIR", expected, newTempPath);
}
private static void GetTempPath_SetEnvVar(string envVar, string expected, string newTempPath)
{
string original = Path.GetTempPath();
Assert.NotNull(original);
try
{
Environment.SetEnvironmentVariable(envVar, newTempPath);
Assert.Equal(
Path.GetFullPath(expected),
Path.GetFullPath(Path.GetTempPath()));
}
finally
{
Environment.SetEnvironmentVariable(envVar, original);
Assert.Equal(original, Path.GetTempPath());
}
}
[Fact]
public static void GetTempFileName()
{
string tmpFile = Path.GetTempFileName();
try
{
Assert.True(File.Exists(tmpFile));
Assert.Equal(".tmp", Path.GetExtension(tmpFile), ignoreCase: true, ignoreLineEndingDifferences: false, ignoreWhiteSpaceDifferences: false);
Assert.Equal(-1, tmpFile.IndexOfAny(Path.GetInvalidPathChars()));
using (FileStream fs = File.OpenRead(tmpFile))
{
Assert.Equal(0, fs.Length);
}
Assert.Equal(Path.Combine(Path.GetTempPath(), Path.GetFileName(tmpFile)), tmpFile);
}
finally
{
File.Delete(tmpFile);
}
}
[Fact]
public static void GetFullPath_InvalidArgs()
{
Assert.Throws<ArgumentNullException>(() => Path.GetFullPath(null));
Assert.Throws<ArgumentException>(() => Path.GetFullPath(string.Empty));
}
[Fact]
public static void GetFullPath_BasicExpansions()
{
string curDir = Directory.GetCurrentDirectory();
// Current directory => current directory
Assert.Equal(curDir, Path.GetFullPath(curDir));
// "." => current directory
Assert.Equal(curDir, Path.GetFullPath("."));
// ".." => up a directory
Assert.Equal(Path.GetDirectoryName(curDir), Path.GetFullPath(".."));
// "dir/./././." => "dir"
Assert.Equal(curDir, Path.GetFullPath(Path.Combine(curDir, ".", ".", ".", ".", ".")));
// "dir///." => "dir"
Assert.Equal(curDir, Path.GetFullPath(curDir + new string(Path.DirectorySeparatorChar, 3) + "."));
// "dir/../dir/./../dir" => "dir"
Assert.Equal(curDir, Path.GetFullPath(Path.Combine(curDir, "..", Path.GetFileName(curDir), ".", "..", Path.GetFileName(curDir))));
// "C:\somedir\.." => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.Combine(Path.GetPathRoot(curDir), "somedir", "..")));
// "C:\." => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.Combine(Path.GetPathRoot(curDir), ".")));
// "C:\..\..\..\.." => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.Combine(Path.GetPathRoot(curDir), "..", "..", "..", "..")));
// "C:\\\" => "C:\"
Assert.Equal(Path.GetPathRoot(curDir), Path.GetFullPath(Path.GetPathRoot(curDir) + new string(Path.DirectorySeparatorChar, 3)));
// Path longer than MaxPath that normalizes down to less than MaxPath
const int Iters = 10000;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 2));
for (int i = 0; i < 10000; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('.');
}
Assert.Equal(curDir, Path.GetFullPath(longPath.ToString()));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Fact]
public static void GetFullPath_Unix_Whitespace()
{
string curDir = Directory.GetCurrentDirectory();
Assert.Equal("/ / ", Path.GetFullPath("/ // "));
Assert.Equal(Path.Combine(curDir, " "), Path.GetFullPath(" "));
Assert.Equal(Path.Combine(curDir, "\r\n"), Path.GetFullPath("\r\n"));
}
[PlatformSpecific(PlatformID.AnyUnix)]
[Theory]
[InlineData("http://www.microsoft.com")]
[InlineData("file://somefile")]
public static void GetFullPath_Unix_URIsAsFileNames(string uriAsFileName)
{
// URIs are valid filenames, though the multiple slashes will be consolidated in GetFullPath
Assert.Equal(
Path.Combine(Directory.GetCurrentDirectory(), uriAsFileName.Replace("//", "/")),
Path.GetFullPath(uriAsFileName));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_NormalizedLongPathTooLong()
{
// Try out a long path that normalizes down to more than MaxPath
string curDir = Directory.GetCurrentDirectory();
const int Iters = 260;
var longPath = new StringBuilder(curDir, curDir.Length + (Iters * 4));
for (int i = 0; i < Iters; i++)
{
longPath.Append(Path.DirectorySeparatorChar).Append('a').Append(Path.DirectorySeparatorChar).Append('.');
}
// Now no longer throws unless over ~32K
Assert.NotNull(Path.GetFullPath(longPath.ToString()));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_AlternateDataStreamsNotSupported()
{
// Throws via our invalid colon filtering
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"bad:path"));
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(@"C:\some\bad:path"));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_URIFormatNotSupported()
{
// Throws via our invalid colon filtering
Assert.Throws<NotSupportedException>(() => Path.GetFullPath("http://www.microsoft.com"));
Assert.Throws<NotSupportedException>(() => Path.GetFullPath("file://www.microsoft.com"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\?\GLOBALROOT\")]
[InlineData(@"\\?\")]
[InlineData(@"\\?\.")]
[InlineData(@"\\?\..")]
[InlineData(@"\\?\\")]
[InlineData(@"\\?\C:\\")]
[InlineData(@"\\?\C:\|")]
[InlineData(@"\\?\C:\.")]
[InlineData(@"\\?\C:\..")]
[InlineData(@"\\?\C:\Foo\.")]
[InlineData(@"\\?\C:\Foo\..")]
public static void GetFullPath_Windows_ArgumentExceptionPaths(string path)
{
Assert.Throws<ArgumentException>(() => Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"bad::$DATA")]
[InlineData(@"C :")]
[InlineData(@"C :\somedir")]
public static void GetFullPath_Windows_NotSupportedExceptionPaths(string path)
{
// Many of these used to throw ArgumentException despite being documented as NotSupportedException
Assert.Throws<NotSupportedException>(() => Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:...")]
[InlineData(@"C:...\somedir")]
[InlineData(@"\.. .\")]
[InlineData(@"\. .\")]
[InlineData(@"\ .\")]
public static void GetFullPath_Windows_LegacyArgumentExceptionPaths(string path)
{
// These paths are legitimate Windows paths that can be created without extended syntax.
// We now allow them through.
Path.GetFullPath(path);
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_MaxPathNotTooLong()
{
// Shouldn't throw anymore
Path.GetFullPath(@"C:\" + new string('a', 255) + @"\");
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_PathTooLong()
{
Assert.Throws<PathTooLongException>(() => Path.GetFullPath(@"C:\" + new string('a', short.MaxValue) + @"\"));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"C:\", @"C:\")]
[InlineData(@"C:\.", @"C:\")]
[InlineData(@"C:\..", @"C:\")]
[InlineData(@"C:\..\..", @"C:\")]
[InlineData(@"C:\A\..", @"C:\")]
[InlineData(@"C:\..\..\A\..", @"C:\")]
public static void GetFullPath_Windows_RelativeRoot(string path, string expected)
{
Assert.Equal(Path.GetFullPath(path), expected);
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_StrangeButLegalPaths()
{
// These are legal and creatable without using extended syntax if you use a trailing slash
// (such as "md ...\"). We used to filter these out, but now allow them to prevent apps from
// being blocked when they hit these paths.
string curDir = Directory.GetCurrentDirectory();
Assert.NotEqual(
Path.GetFullPath(curDir + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ". " + Path.DirectorySeparatorChar));
Assert.NotEqual(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + "..." + Path.DirectorySeparatorChar));
Assert.NotEqual(
Path.GetFullPath(Path.GetDirectoryName(curDir) + Path.DirectorySeparatorChar),
Path.GetFullPath(curDir + Path.DirectorySeparatorChar + ".. " + Path.DirectorySeparatorChar));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\?\C:\ ")]
[InlineData(@"\\?\C:\ \ ")]
[InlineData(@"\\?\C:\ .")]
[InlineData(@"\\?\C:\ ..")]
[InlineData(@"\\?\C:\...")]
public static void GetFullPath_Windows_ValidExtendedPaths(string path)
{
Assert.Equal(path, Path.GetFullPath(path));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\server\share", @"\\server\share")]
[InlineData(@"\\server\share", @" \\server\share")]
[InlineData(@"\\server\share\dir", @"\\server\share\dir")]
[InlineData(@"\\server\share", @"\\server\share\.")]
[InlineData(@"\\server\share", @"\\server\share\..")]
[InlineData(@"\\server\share\", @"\\server\share\ ")]
[InlineData(@"\\server\ share\", @"\\server\ share\")]
[InlineData(@"\\?\UNC\server\share", @"\\?\UNC\server\share")]
[InlineData(@"\\?\UNC\server\share\dir", @"\\?\UNC\server\share\dir")]
[InlineData(@"\\?\UNC\server\share\. ", @"\\?\UNC\server\share\. ")]
[InlineData(@"\\?\UNC\server\share\.. ", @"\\?\UNC\server\share\.. ")]
[InlineData(@"\\?\UNC\server\share\ ", @"\\?\UNC\server\share\ ")]
[InlineData(@"\\?\UNC\server\ share\", @"\\?\UNC\server\ share\")]
public static void GetFullPath_Windows_UNC_Valid(string expected, string input)
{
Assert.Equal(expected, Path.GetFullPath(input));
}
[PlatformSpecific(PlatformID.Windows)]
[Theory]
[InlineData(@"\\")]
[InlineData(@"\\server")]
[InlineData(@"\\server\")]
[InlineData(@"\\server\\")]
[InlineData(@"\\server\..")]
[InlineData(@"\\?\UNC\")]
[InlineData(@"\\?\UNC\server")]
[InlineData(@"\\?\UNC\server\")]
[InlineData(@"\\?\UNC\server\\")]
[InlineData(@"\\?\UNC\server\..")]
[InlineData(@"\\?\UNC\server\share\.")]
[InlineData(@"\\?\UNC\server\share\..")]
[InlineData(@"\\?\UNC\a\b\\")]
public static void GetFullPath_Windows_UNC_Invalid(string invalidPath)
{
Assert.Throws<ArgumentException>(() => Path.GetFullPath(invalidPath));
}
[PlatformSpecific(PlatformID.Windows)]
[Fact]
public static void GetFullPath_Windows_83Paths()
{
// Create a temporary file name with a name longer than 8.3 such that it'll need to be shortened.
string tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".txt");
File.Create(tempFilePath).Dispose();
try
{
// Get its short name
var sb = new StringBuilder(260);
if (GetShortPathName(tempFilePath, sb, sb.Capacity) > 0) // only proceed if we could successfully create the short name
{
// Make sure the shortened name expands back to the original one
Assert.Equal(tempFilePath, Path.GetFullPath(sb.ToString()));
// Validate case where short name doesn't expand to a real file
string invalidShortName = @"S:\DOESNT~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp";
Assert.Equal(invalidShortName, Path.GetFullPath(invalidShortName));
// Same thing, but with a long path that normalizes down to a short enough one
const int Iters = 1000;
var shortLongName = new StringBuilder(invalidShortName, invalidShortName.Length + (Iters * 2));
for (int i = 0; i < Iters; i++)
{
shortLongName.Append(Path.DirectorySeparatorChar).Append('.');
}
Assert.Equal(invalidShortName, Path.GetFullPath(shortLongName.ToString()));
}
}
finally
{
File.Delete(tempFilePath);
}
}
// Windows-only P/Invoke to create 8.3 short names from long names
[DllImport("kernel32.dll", CharSet = CharSet.Ansi)]
private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, int cchBuffer);
}
| |
namespace Voxel2Unity {
using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System;
using System.Text;
public static class VoxFile {
private static Color[] DefaultPallete {
get {
Color[] c = new Color[256];
int index = 0;
for (int r = 10; r >= 0; r -= 2) {
for (int g = 10; g >= 0; g -= 2) {
for (int b = 10; b >= 0; b -= 2) {
if (r + g + b != 0) {
c[index] = new Color((float)r / 10f, (float)g / 10f, (float)b / 10f);
index++;
}
}
}
}
for (int i = 14; i > 0; i--) {
if (i % 3 == 0) {
continue;
}
c[index] = new Color((float)i / 15f, 0f, 0f);
index++;
}
for (int i = 14; i > 0; i--) {
if (i % 3 == 0) {
continue;
}
c[index] = new Color(0f, (float)i / 15f, 0f);
index++;
}
for (int i = 14; i > 0; i--) {
if (i % 3 == 0) {
continue;
}
c[index] = new Color(0f, 0f, (float)i / 15f);
index++;
}
for (int i = 14; i > 0; i--) {
if (i % 3 == 0) {
continue;
}
c[index] = new Color((float)i / 15f, (float)i / 15f, (float)i / 15f);
index++;
}
c[255] = new Color(0f, 0f, 0f, 1f);
return c;
}
}
public static byte[] GetVoxByte (VoxData _data, Color[] _palatte) {
List<byte> _byte = new List<byte>();
///*
// --- SIZE ---
//size / children size
_byte.AddRange(Encoding.Default.GetBytes("SIZE"));
_byte.AddRange(BitConverter.GetBytes(12));
_byte.AddRange(BitConverter.GetBytes(0));
// content
_byte.AddRange(BitConverter.GetBytes(_data.SizeX));
_byte.AddRange(BitConverter.GetBytes(_data.SizeY));
_byte.AddRange(BitConverter.GetBytes(_data.SizeZ));
// --- XYZI ---
//size / children size
_byte.AddRange(Encoding.Default.GetBytes("XYZI"));
_byte.AddRange(BitConverter.GetBytes(_data.VoxelNum * 4 + 4));
_byte.AddRange(BitConverter.GetBytes(0));
_byte.AddRange(BitConverter.GetBytes(_data.VoxelNum));
for (int i = 0; i < _data.SizeX; i++) {
for (int j = 0; j < _data.SizeY; j++) {
for (int k = 0; k < _data.SizeZ; k++) {
if (_data.Voxels[i, j, k] != 0) {
_byte.Add((byte)i);
_byte.Add((byte)j);
_byte.Add((byte)k);
_byte.Add((byte)_data.Voxels[i, j, k]);
}
}
}
}
// --- RGBA ---
//size / children size
_byte.AddRange(Encoding.Default.GetBytes("RGBA"));
_byte.AddRange(BitConverter.GetBytes(1024));
_byte.AddRange(BitConverter.GetBytes(0));
for (int i = 0; i < 256; i++) {
Color _color = i < _palatte.Length ? _palatte[i] : new Color();
_byte.Add((byte)(_color.r * 255.0f));
_byte.Add((byte)(_color.g * 255.0f));
_byte.Add((byte)(_color.b * 255.0f));
_byte.Add((byte)(_color.a * 255.0f));
}
//*/
// --- Final ---
byte[] _ans = new byte[_byte.Count];
_byte.CopyTo(_ans);
return _ans;
}
public static byte[] GetMainByte (VoxData _voxData) {
List<byte> _byte = new List<byte>();
///*
// "VOX "
_byte.AddRange(Encoding.Default.GetBytes("VOX "));
// "VERSION "
_byte.AddRange(_voxData.Version);
// ID --> MAIN
_byte.AddRange(Encoding.Default.GetBytes("MAIN"));
// Main Chunk Size
_byte.AddRange(BitConverter.GetBytes(0));
// Main Chunk Children Size
byte[] _vox = GetVoxByte(_voxData, _voxData.Palatte);
_byte.AddRange(BitConverter.GetBytes(_vox.Length));
// Vox Chunk
_byte.AddRange(_vox);
//*/
byte[] _ans = new byte[_byte.Count];
_byte.CopyTo(_ans);
return _ans;
}
public static VoxData LoadVoxel(string path) {
return LoadVoxel(Util.FileToByte(path));
}
public static VoxData LoadVoxel (byte[] _data) {
if (_data[0] != 'V' || _data[1] != 'O' || _data[2] != 'X' || _data[3] != ' ') {
Debug.LogError("Error Magic Number");
return null;
}
using (MemoryStream _ms = new MemoryStream(_data)) {
using (BinaryReader _br = new BinaryReader(_ms)) {
VoxData _mainData = new VoxData();
///*
// VOX_
_br.ReadInt32();
// VERSION
_mainData.Version = _br.ReadBytes(4);
byte[] _chunkId = _br.ReadBytes(4);
if (_chunkId[0] != 'M' || _chunkId[1] != 'A' || _chunkId[2] != 'I' || _chunkId[3] != 'N') {
Debug.LogError("Error main ID");
return null;
}
int _chunkSize = _br.ReadInt32();
int _childrenSize = _br.ReadInt32();
_br.ReadBytes(_chunkSize);
int _readSize = 0;
while (_readSize < _childrenSize) {
_chunkId = _br.ReadBytes(4);
if (_chunkId[0] == 'S' && _chunkId[1] == 'I' && _chunkId[2] == 'Z' && _chunkId[3] == 'E') {
_readSize += ReadSizeChunk(_br, _mainData);
} else if (_chunkId[0] == 'X' && _chunkId[1] == 'Y' && _chunkId[2] == 'Z' && _chunkId[3] == 'I') {
_readSize += ReadVoxelChunk(_br, _mainData);
} else if (_chunkId[0] == 'R' && _chunkId[1] == 'G' && _chunkId[2] == 'B' && _chunkId[3] == 'A') {
_mainData.Palatte = new Color[256];
_readSize += ReadPalattee(_br, _mainData.Palatte);
} else {
int chunkSize = _br.ReadInt32();
int childrenSize = _br.ReadInt32();
_br.ReadBytes(chunkSize + childrenSize);
_readSize += chunkSize + childrenSize + 4 + 4 + 4;
}
}
if (_mainData.Palatte == null) {
_mainData.Palatte = DefaultPallete;
}
return _mainData;
}
}
}
static int ReadSizeChunk (BinaryReader _br, VoxData _mainData) {
int chunkSize = _br.ReadInt32();
int childrenSize = _br.ReadInt32();
_mainData.SizeX = _br.ReadInt32();
_mainData.SizeY = _br.ReadInt32();
_mainData.SizeZ = _br.ReadInt32();
///*
_mainData.Voxels = new int[_mainData.SizeX, _mainData.SizeY, _mainData.SizeZ];
//*/
if (childrenSize > 0) {
_br.ReadBytes(childrenSize);
}
return chunkSize + childrenSize + 4 * 3;
}
static int ReadVoxelChunk (BinaryReader _br, VoxData _mainData) {
int chunkSize = _br.ReadInt32();
int childrenSize = _br.ReadInt32();
int numVoxels = _br.ReadInt32();
for (int i = 0; i < numVoxels; ++i) {
int x = (int)_br.ReadByte();
int y = (int)_br.ReadByte();
int z = (int)_br.ReadByte();
_mainData.Voxels[x, y, z] = _br.ReadByte();
}
if (childrenSize > 0) {
_br.ReadBytes(childrenSize);
}
return chunkSize + childrenSize + 4 * 3;
}
static int ReadPalattee (BinaryReader _br, Color[] _colors) {
int chunkSize = _br.ReadInt32();
int childrenSize = _br.ReadInt32();
for (int i = 0; i < 256; ++i) {
_colors[i] = new Color((float)_br.ReadByte() / 255.0f, (float)_br.ReadByte() / 255.0f, (float)_br.ReadByte() / 255.0f, (float)_br.ReadByte() / 255.0f);
}
if (childrenSize > 0) {
_br.ReadBytes(childrenSize);
}
return chunkSize + childrenSize + 4 * 3;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.PolicyTroubleshooter.V1
{
/// <summary>Settings for <see cref="IamCheckerClient"/> instances.</summary>
public sealed partial class IamCheckerSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="IamCheckerSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="IamCheckerSettings"/>.</returns>
public static IamCheckerSettings GetDefault() => new IamCheckerSettings();
/// <summary>Constructs a new <see cref="IamCheckerSettings"/> object with default settings.</summary>
public IamCheckerSettings()
{
}
private IamCheckerSettings(IamCheckerSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
TroubleshootIamPolicySettings = existing.TroubleshootIamPolicySettings;
OnCopy(existing);
}
partial void OnCopy(IamCheckerSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IamCheckerClient.TroubleshootIamPolicy</c> and <c>IamCheckerClient.TroubleshootIamPolicyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings TroubleshootIamPolicySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="IamCheckerSettings"/> object.</returns>
public IamCheckerSettings Clone() => new IamCheckerSettings(this);
}
/// <summary>
/// Builder class for <see cref="IamCheckerClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class IamCheckerClientBuilder : gaxgrpc::ClientBuilderBase<IamCheckerClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public IamCheckerSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public IamCheckerClientBuilder()
{
UseJwtAccessWithScopes = IamCheckerClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref IamCheckerClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<IamCheckerClient> task);
/// <summary>Builds the resulting client.</summary>
public override IamCheckerClient Build()
{
IamCheckerClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<IamCheckerClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<IamCheckerClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private IamCheckerClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return IamCheckerClient.Create(callInvoker, Settings);
}
private async stt::Task<IamCheckerClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return IamCheckerClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => IamCheckerClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => IamCheckerClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => IamCheckerClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>IamChecker client wrapper, for convenient use.</summary>
/// <remarks>
/// IAM Policy Troubleshooter service.
///
/// This service helps you troubleshoot access issues for Google Cloud resources.
/// </remarks>
public abstract partial class IamCheckerClient
{
/// <summary>
/// The default endpoint for the IamChecker service, which is a host of "policytroubleshooter.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "policytroubleshooter.googleapis.com:443";
/// <summary>The default IamChecker scopes.</summary>
/// <remarks>
/// The default IamChecker scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="IamCheckerClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="IamCheckerClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="IamCheckerClient"/>.</returns>
public static stt::Task<IamCheckerClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new IamCheckerClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="IamCheckerClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="IamCheckerClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="IamCheckerClient"/>.</returns>
public static IamCheckerClient Create() => new IamCheckerClientBuilder().Build();
/// <summary>
/// Creates a <see cref="IamCheckerClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="IamCheckerSettings"/>.</param>
/// <returns>The created <see cref="IamCheckerClient"/>.</returns>
internal static IamCheckerClient Create(grpccore::CallInvoker callInvoker, IamCheckerSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
IamChecker.IamCheckerClient grpcClient = new IamChecker.IamCheckerClient(callInvoker);
return new IamCheckerClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC IamChecker client</summary>
public virtual IamChecker.IamCheckerClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Checks whether a member has a specific permission for a specific resource,
/// and explains why the member does or does not have that permission.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual TroubleshootIamPolicyResponse TroubleshootIamPolicy(TroubleshootIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Checks whether a member has a specific permission for a specific resource,
/// and explains why the member does or does not have that permission.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<TroubleshootIamPolicyResponse> TroubleshootIamPolicyAsync(TroubleshootIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Checks whether a member has a specific permission for a specific resource,
/// and explains why the member does or does not have that permission.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<TroubleshootIamPolicyResponse> TroubleshootIamPolicyAsync(TroubleshootIamPolicyRequest request, st::CancellationToken cancellationToken) =>
TroubleshootIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>IamChecker client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// IAM Policy Troubleshooter service.
///
/// This service helps you troubleshoot access issues for Google Cloud resources.
/// </remarks>
public sealed partial class IamCheckerClientImpl : IamCheckerClient
{
private readonly gaxgrpc::ApiCall<TroubleshootIamPolicyRequest, TroubleshootIamPolicyResponse> _callTroubleshootIamPolicy;
/// <summary>
/// Constructs a client wrapper for the IamChecker service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="IamCheckerSettings"/> used within this client.</param>
public IamCheckerClientImpl(IamChecker.IamCheckerClient grpcClient, IamCheckerSettings settings)
{
GrpcClient = grpcClient;
IamCheckerSettings effectiveSettings = settings ?? IamCheckerSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callTroubleshootIamPolicy = clientHelper.BuildApiCall<TroubleshootIamPolicyRequest, TroubleshootIamPolicyResponse>(grpcClient.TroubleshootIamPolicyAsync, grpcClient.TroubleshootIamPolicy, effectiveSettings.TroubleshootIamPolicySettings);
Modify_ApiCall(ref _callTroubleshootIamPolicy);
Modify_TroubleshootIamPolicyApiCall(ref _callTroubleshootIamPolicy);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_TroubleshootIamPolicyApiCall(ref gaxgrpc::ApiCall<TroubleshootIamPolicyRequest, TroubleshootIamPolicyResponse> call);
partial void OnConstruction(IamChecker.IamCheckerClient grpcClient, IamCheckerSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC IamChecker client</summary>
public override IamChecker.IamCheckerClient GrpcClient { get; }
partial void Modify_TroubleshootIamPolicyRequest(ref TroubleshootIamPolicyRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Checks whether a member has a specific permission for a specific resource,
/// and explains why the member does or does not have that permission.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override TroubleshootIamPolicyResponse TroubleshootIamPolicy(TroubleshootIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_TroubleshootIamPolicyRequest(ref request, ref callSettings);
return _callTroubleshootIamPolicy.Sync(request, callSettings);
}
/// <summary>
/// Checks whether a member has a specific permission for a specific resource,
/// and explains why the member does or does not have that permission.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<TroubleshootIamPolicyResponse> TroubleshootIamPolicyAsync(TroubleshootIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_TroubleshootIamPolicyRequest(ref request, ref callSettings);
return _callTroubleshootIamPolicy.Async(request, callSettings);
}
}
}
| |
/* ====================================================================
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.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
* Leon Wang
* ==============================================================*/
using System;
using System.Collections;
using System.IO;
using NUnit.Framework;
using NPOI.POIFS.FileSystem;
using NPOI.POIFS.Properties;
using NPOI.POIFS.Storage;
using System.Collections.Generic;
/**
* Class to Test DirectoryNode functionality
*
* @author Marc Johnson
*/
namespace TestCases.POIFS.FileSystem
{
/// <summary>
/// Summary description for TestDirectoryNode
/// </summary>
[TestFixture]
public class TestDirectoryNode
{
/**
* Constructor TestDirectoryNode
*
* @param name
*/
public TestDirectoryNode()
{
}
/**
* Test trivial constructor (a DirectoryNode with no children)
*
* @exception IOException
*/
[Test]
public void TestEmptyConstructor()
{
POIFSFileSystem fs = new POIFSFileSystem();
DirectoryProperty property1 = new DirectoryProperty("parent");
DirectoryProperty property2 = new DirectoryProperty("child");
DirectoryNode parent = new DirectoryNode(property1, fs, null);
DirectoryNode node = new DirectoryNode(property2, fs, parent);
Assert.AreEqual(0, parent.Path.Length);
Assert.AreEqual(1, node.Path.Length);
Assert.AreEqual("child", node.Path.GetComponent(0));
// Verify that GetEntries behaves correctly
int count = 0;
IEnumerator<Entry> iter = node.Entries;
while (iter.MoveNext())
{
count++;
}
Assert.AreEqual(0, count);
// Verify behavior of IsEmpty
Assert.IsTrue(node.IsEmpty);
// Verify behavior of EntryCount
Assert.AreEqual(0, node.EntryCount);
// Verify behavior of Entry
try
{
node.GetEntry("foo");
Assert.Fail("Should have caught FileNotFoundException");
}
catch (FileNotFoundException )
{
// as expected
}
// Verify behavior of isDirectoryEntry
Assert.IsTrue(node.IsDirectoryEntry);
// Verify behavior of GetName
Assert.AreEqual(property2.Name, node.Name);
// Verify behavior of isDocumentEntry
Assert.IsTrue(!node.IsDocumentEntry);
// Verify behavior of GetParent
Assert.AreEqual(parent, node.Parent);
}
/**
* Test non-trivial constructor (a DirectoryNode with children)
*
* @exception IOException
*/
[Test]
public void TestNonEmptyConstructor()
{
DirectoryProperty property1 = new DirectoryProperty("parent");
DirectoryProperty property2 = new DirectoryProperty("child1");
property1.AddChild(property2);
property1.AddChild(new DocumentProperty("child2", 2000));
property2.AddChild(new DocumentProperty("child3", 30000));
DirectoryNode node = new DirectoryNode(property1, new POIFSFileSystem(), null);
// Verify that GetEntries behaves correctly
int count = 0;
IEnumerator<Entry> iter = node.Entries;
while (iter.MoveNext())
{
count++;
//iter.Current;
}
Assert.AreEqual(2, count);
// Verify behavior of IsEmpty
Assert.IsTrue(!node.IsEmpty);
// Verify behavior of EntryCount
Assert.AreEqual(2, node.EntryCount);
// Verify behavior of Entry
DirectoryNode child1 = (DirectoryNode)node.GetEntry("child1");
child1.GetEntry("child3");
node.GetEntry("child2");
try
{
node.GetEntry("child3");
Assert.Fail("Should have caught FileNotFoundException");
}
catch (FileNotFoundException)
{
// as expected
}
// Verify behavior of isDirectoryEntry
Assert.IsTrue(node.IsDirectoryEntry);
// Verify behavior of GetName
Assert.AreEqual(property1.Name, node.Name);
// Verify behavior of isDocumentEntry
Assert.IsTrue(!node.IsDocumentEntry);
// Verify behavior of GetParent
Assert.IsNull(node.Parent);
}
/**
* Test deletion methods
*
* @exception IOException
*/
[Test]
public void TestDeletion()
{
POIFSFileSystem fs = new POIFSFileSystem();
DirectoryEntry root = fs.Root;
Assert.IsFalse(root.Delete());
Assert.IsTrue(root.IsEmpty);
DirectoryEntry dir = fs.CreateDirectory("myDir");
Assert.IsFalse(root.IsEmpty);
Assert.IsTrue(dir.IsEmpty);
Assert.IsFalse(root.Delete());
// Verify can Delete empty directory
Assert.IsTrue(dir.Delete());
dir = fs.CreateDirectory("NextDir");
DocumentEntry doc = dir.CreateDocument("foo", new MemoryStream(new byte[1]));
Assert.IsFalse(root.IsEmpty);
Assert.IsFalse(dir.IsEmpty);
Assert.IsFalse(dir.Delete());
// Verify cannot Delete empty directory
Assert.IsTrue(!dir.Delete());
Assert.IsTrue(doc.Delete());
Assert.IsTrue(dir.IsEmpty);
// Verify now we can Delete it
Assert.IsTrue(dir.Delete());
Assert.IsTrue(root.IsEmpty);
fs.Close();
}
/**
* Test Change name methods
*
* @exception IOException
*/
[Test]
public void TestRename()
{
POIFSFileSystem fs = new POIFSFileSystem();
DirectoryEntry root = fs.Root;
// Verify cannot Rename the root directory
Assert.IsTrue(!root.RenameTo("foo"));
DirectoryEntry dir = fs.CreateDirectory("myDir");
Assert.IsTrue(dir.RenameTo("foo"));
Assert.AreEqual("foo", dir.Name);
DirectoryEntry dir2 = fs.CreateDirectory("myDir");
Assert.IsTrue(!dir2.RenameTo("foo"));
Assert.AreEqual("myDir", dir2.Name);
Assert.IsTrue(dir.RenameTo("FirstDir"));
Assert.IsTrue(dir2.RenameTo("foo"));
Assert.AreEqual("foo", dir2.Name);
fs.Close();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
**
**
** Purpose: Exposes a separate Stream for Console IO and
** handles WinCE appropriately. Also keeps us from using the
** ThreadPool for all Console output.
**
**
===========================================================*/
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Diagnostics.Contracts;
namespace System.IO {
internal sealed class __ConsoleStream : Stream
{
// We know that if we are using console APIs rather than file APIs, then the encoding
// is Encoding.Unicode implying 2 bytes per character:
const int BytesPerWChar = 2;
[System.Security.SecurityCritical] // auto-generated
private SafeFileHandle _handle;
private bool _canRead;
private bool _canWrite;
private bool _useFileAPIs;
private bool _isPipe; // When reading from pipes, we need to properly handle EOF cases.
[System.Security.SecurityCritical] // auto-generated
internal __ConsoleStream(SafeFileHandle handle, FileAccess access, bool useFileAPIs)
{
Contract.Assert(handle != null && !handle.IsInvalid, "__ConsoleStream expects a valid handle!");
_handle = handle;
_canRead = ( (access & FileAccess.Read) == FileAccess.Read );
_canWrite = ( (access & FileAccess.Write) == FileAccess.Write);
_useFileAPIs = useFileAPIs;
_isPipe = Win32Native.GetFileType(handle) == Win32Native.FILE_TYPE_PIPE;
}
public override bool CanRead {
[Pure]
get { return _canRead; }
}
public override bool CanWrite {
[Pure]
get { return _canWrite; }
}
public override bool CanSeek {
[Pure]
get { return false; }
}
public override long Length {
get {
__Error.SeekNotSupported();
return 0; // compiler appeasement
}
}
public override long Position {
get {
__Error.SeekNotSupported();
return 0; // compiler appeasement
}
set {
__Error.SeekNotSupported();
}
}
[System.Security.SecuritySafeCritical] // auto-generated
protected override void Dispose(bool disposing)
{
// We're probably better off not closing the OS handle here. First,
// we allow a program to get multiple instances of __ConsoleStreams
// around the same OS handle, so closing one handle would invalidate
// them all. Additionally, we want a second AppDomain to be able to
// write to stdout if a second AppDomain quits.
if (_handle != null) {
_handle = null;
}
_canRead = false;
_canWrite = false;
base.Dispose(disposing);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void Flush()
{
if (_handle == null) __Error.FileNotOpen();
if (!CanWrite) __Error.WriteNotSupported();
}
public override void SetLength(long value)
{
__Error.SeekNotSupported();
}
[System.Security.SecuritySafeCritical] // auto-generated
public override int Read([In, Out] byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException((offset < 0 ? "offset" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_canRead) __Error.ReadNotSupported();
int bytesRead;
int errCode = ReadFileNative(_handle, buffer, offset, count, _useFileAPIs, _isPipe, out bytesRead);
if (Win32Native.ERROR_SUCCESS != errCode)
__Error.WinIOError(errCode, String.Empty);
return bytesRead;
}
public override long Seek(long offset, SeekOrigin origin) {
__Error.SeekNotSupported();
return 0; // compiler appeasement
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void Write(byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException((offset < 0 ? "offset" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_canWrite) __Error.WriteNotSupported();
int errCode = WriteFileNative(_handle, buffer, offset, count, _useFileAPIs);
if (Win32Native.ERROR_SUCCESS != errCode)
__Error.WinIOError(errCode, String.Empty);
return;
}
// P/Invoke wrappers for writing to and from a file, nearly identical
// to the ones on FileStream. These are duplicated to save startup/hello
// world working set.
[System.Security.SecurityCritical] // auto-generated
private unsafe static int ReadFileNative(SafeFileHandle hFile, byte[] bytes, int offset, int count, bool useFileAPIs, bool isPipe, out int bytesRead) {
Contract.Requires(offset >= 0, "offset >= 0");
Contract.Requires(count >= 0, "count >= 0");
Contract.Requires(bytes != null, "bytes != null");
// Don't corrupt memory when multiple threads are erroneously writing
// to this stream simultaneously.
if (bytes.Length - offset < count)
throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_IORaceCondition"));
Contract.EndContractBlock();
// You can't use the fixed statement on an array of length 0.
if (bytes.Length == 0) {
bytesRead = 0;
return Win32Native.ERROR_SUCCESS;
}
// First, wait bytes to become available. This is preferable to letting ReadFile block,
// since ReadFile is not abortable (via Thread.Abort), while WaitForAvailableConsoleInput is.
#if !FEATURE_CORESYSTEM // CoreSystem isn't signaling stdin when input is available so we can't block on it
WaitForAvailableConsoleInput(hFile, isPipe);
#endif
bool readSuccess;
if (useFileAPIs) {
fixed (byte* p = bytes) {
readSuccess = (0 != Win32Native.ReadFile(hFile, p + offset, count, out bytesRead, IntPtr.Zero));
}
} else {
fixed (byte* p = bytes) {
int charsRead;
readSuccess = Win32Native.ReadConsoleW(hFile, p + offset, count / BytesPerWChar, out charsRead, IntPtr.Zero);
bytesRead = charsRead * BytesPerWChar;
}
}
if (readSuccess)
return Win32Native.ERROR_SUCCESS;
int errorCode = Marshal.GetLastWin32Error();
// For pipes that are closing or broken, just stop.
// (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing;
// ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is mot an error, but EOF.)
if (errorCode == Win32Native.ERROR_NO_DATA || errorCode == Win32Native.ERROR_BROKEN_PIPE)
return Win32Native.ERROR_SUCCESS;
return errorCode;
}
[System.Security.SecurityCritical] // auto-generated
private static unsafe int WriteFileNative(SafeFileHandle hFile, byte[] bytes, int offset, int count, bool useFileAPIs) {
Contract.Requires(offset >= 0, "offset >= 0");
Contract.Requires(count >= 0, "count >= 0");
Contract.Requires(bytes != null, "bytes != null");
Contract.Requires(bytes.Length >= offset + count, "bytes.Length >= offset + count");
// You can't use the fixed statement on an array of length 0.
if (bytes.Length == 0)
return Win32Native.ERROR_SUCCESS;
bool writeSuccess;
if (useFileAPIs) {
fixed (byte* p = bytes) {
int numBytesWritten;
writeSuccess = (0 != Win32Native.WriteFile(hFile, p + offset, count, out numBytesWritten, IntPtr.Zero));
Contract.Assert(!writeSuccess || count == numBytesWritten);
}
} else {
// Note that WriteConsoleW has a max limit on num of chars to write (64K)
// [http://msdn.microsoft.com/en-us/library/ms687401.aspx]
// However, we do not need to worry about that becasue the StreamWriter in Console has
// a much shorter buffer size anyway.
fixed (byte* p = bytes) {
Int32 charsWritten;
writeSuccess = Win32Native.WriteConsoleW(hFile, p + offset, count / BytesPerWChar, out charsWritten, IntPtr.Zero);
Contract.Assert(!writeSuccess || count / BytesPerWChar == charsWritten);
}
}
if (writeSuccess)
return Win32Native.ERROR_SUCCESS;
int errorCode = Marshal.GetLastWin32Error();
// For pipes that are closing or broken, just stop.
// (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing;
// ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is mot an error, but EOF.)
if (errorCode == Win32Native.ERROR_NO_DATA || errorCode == Win32Native.ERROR_BROKEN_PIPE)
return Win32Native.ERROR_SUCCESS;
return errorCode;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void WaitForAvailableConsoleInput(SafeFileHandle file, bool isPipe);
}
}
| |
namespace Nancy.Tests.Unit.ModelBinding
{
using System;
using FakeItEasy;
using Nancy.ModelBinding;
using Xunit;
public class DynamicModelBinderAdapterFixture
{
[Fact]
public void Should_throw_if_locator_is_null()
{
// Given, When
var result = Record.Exception(() => new DynamicModelBinderAdapter(null, new NancyContext(), null, A.Dummy<BindingConfig>()));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_context_is_null()
{
// Given, When
var result = Record.Exception(() => new DynamicModelBinderAdapter(A.Fake<IModelBinderLocator>(), null, null, A.Dummy<BindingConfig>()));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_configuration_is_null()
{
// Given, When
var result = Record.Exception(() => new DynamicModelBinderAdapter(A.Fake<IModelBinderLocator>(), A.Dummy<NancyContext>(), null, null));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_pass_type_to_locator_when_cast_implicitly()
{
// Given
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, new NancyContext(), null, A.Dummy<BindingConfig>());
// When
Model result = adapter;
// Then
A.CallTo(() => fakeLocator.GetBinderForType(typeof(Model), A<NancyContext>.Ignored)).MustHaveHappenedOnceExactly();
}
[Fact]
public void Should_invoke_binder_with_context()
{
// Given
var context = new NancyContext();
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, context)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, null, A.Dummy<BindingConfig>());
// When
Model result = adapter;
// Then
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, context)).MustHaveHappenedOnceExactly();
}
[Fact]
public void Should_pass_type_to_locator_when_cast_explicitly()
{
// Given
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, new NancyContext(), null, A.Dummy<BindingConfig>());
// When
var result = (Model)adapter;
// Then
A.CallTo(() => fakeLocator.GetBinderForType(typeof(Model), A<NancyContext>.Ignored)).MustHaveHappenedOnceExactly();
}
[Fact]
public void Should_return_object_from_binder_if_binder_doesnt_return_null()
{
// Given
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, new NancyContext(), null, A.Dummy<BindingConfig>());
// When
Model result = adapter;
// Then
result.ShouldNotBeNull();
result.ShouldBeSameAs(returnModel);
}
[Fact]
public void Should_throw_if_locator_does_not_return_binder()
{
// Given
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(null);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, new NancyContext(), null, A.Dummy<BindingConfig>());
// When
var result = Record.Exception(() => (Model)adapter);
// Then
result.ShouldBeOfType(typeof(ModelBindingException));
}
[Fact]
public void Should_pass_context_to_binder()
{
// Given
var context = new NancyContext();
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context , null, A.Dummy<BindingConfig>());
// When
Model result = adapter;
// Then
A.CallTo(() => fakeModelBinder.Bind(context, A<Type>._, A<object>._, A<BindingConfig>._, A<string[]>._)).MustHaveHappened();
}
[Fact]
public void Should_pass_type_to_binder()
{
// Given
var context = new NancyContext();
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, null, A.Dummy<BindingConfig>());
// When
Model result = adapter;
// Then
A.CallTo(() => fakeModelBinder.Bind(A<NancyContext>._, typeof(Model), A<object>._, A<BindingConfig>._, A<string[]>._)).MustHaveHappened();
}
[Fact]
public void Should_pass_instance_to_binder()
{
// Given
var context = new NancyContext();
var instance = new Model();
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, instance, A.Dummy<BindingConfig>());
// When
Model result = adapter;
// Then
A.CallTo(() => fakeModelBinder.Bind(A<NancyContext>._, A<Type>._, instance, A<BindingConfig>._, A<string[]>._)).MustHaveHappened();
}
[Fact]
public void Should_pass_binding_configuration_to_binder()
{
// Given
var context = new NancyContext();
var instance = new Model();
var config = BindingConfig.Default;
var blacklist = new[] {"foo", "bar"};
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, instance, config, blacklist);
// When
Model result = adapter;
// Then
A.CallTo(() => fakeModelBinder.Bind(A<NancyContext>._, A<Type>._, A<object>._, A<BindingConfig>._, blacklist)).MustHaveHappened();
}
[Fact]
public void Should_pass_blacklist_to_binder()
{
// Given
var context = new NancyContext();
var instance = new Model();
var config = BindingConfig.Default;
var fakeModelBinder = A.Fake<IModelBinder>();
var returnModel = new Model();
A.CallTo(() => fakeModelBinder.Bind(null, null, null, null)).WithAnyArguments().Returns(returnModel);
var fakeLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeLocator.GetBinderForType(A<Type>.Ignored, A<NancyContext>.Ignored)).Returns(fakeModelBinder);
dynamic adapter = new DynamicModelBinderAdapter(fakeLocator, context, instance, config);
// When
Model result = adapter;
// Then
A.CallTo(() => fakeModelBinder.Bind(A<NancyContext>._, A<Type>._, A<object>._, config, A<string[]>._)).MustHaveHappened();
}
}
public class Model
{
}
}
| |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using Newtonsoft.Json.Linq;
namespace KatanaContrib.Security.Foursquare
{
internal class FoursquareAuthenticationHandler : AuthenticationHandler<FoursquareAuthenticationOptions>
{
private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
private const string TokenEndpoint = "https://foursquare.com/oauth2/access_token";
private const string ApiEndpoint = "https://api.foursquare.com/v2/users/self";
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
public FoursquareAuthenticationHandler(HttpClient httpClient, ILogger logger)
{
_httpClient = httpClient;
_logger = logger;
}
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
AuthenticationProperties properties = null;
try
{
string code = null;
string state = null;
IReadableStringCollection query = Request.Query;
IList<string> values = query.GetValues("code");
if (values != null && values.Count == 1)
{
code = values[0];
}
state = Request.Cookies["state_value"];
properties = Options.StateDataFormat.Unprotect(state);
if (properties == null)
{
return null;
}
// OAuth2 10.12 CSRF
if (!ValidateCorrelationId(properties, _logger))
{
return new AuthenticationTicket(null, properties);
}
string requestPrefix = Request.Scheme + "://" + Request.Host;
string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath;
string tokenRequest = "grant_type=authorization_code" +
"&code=" + Uri.EscapeDataString(code) +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
"&client_id=" + Uri.EscapeDataString(Options.ClientId) +
"&client_secret=" + Uri.EscapeDataString(Options.ClientSecret);
HttpResponseMessage tokenResponse = await _httpClient.GetAsync(TokenEndpoint + "?" + tokenRequest, Request.CallCancelled);
tokenResponse.EnsureSuccessStatusCode();
string text = await tokenResponse.Content.ReadAsStringAsync();
JObject form = JObject.Parse(text);
JToken accessToken = null;
foreach(var x in form)
{
if(x.Key == "access_token")
{
accessToken = x.Value;
}
}
string expires = "5183999";
HttpResponseMessage graphResponse = await _httpClient.GetAsync(
ApiEndpoint + "?oauth_token=" + Uri.EscapeDataString(accessToken.ToString()) + "&v=20131201", Request.CallCancelled);
graphResponse.EnsureSuccessStatusCode();
text = await graphResponse.Content.ReadAsStringAsync();
JObject result = JObject.Parse(text);
JToken response = result["response"];
JObject user = response["user"] as JObject;
var context = new FoursquareAuthenticatedContext(Context, user, accessToken.ToString(), expires);
context.Identity = new ClaimsIdentity(
Options.AuthenticationType,
ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
if (!string.IsNullOrEmpty(context.Id))
{
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.LastName) && !string.IsNullOrEmpty(context.FirstName))
{
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, string.Format("{0} {1}", context.FirstName,context.LastName), XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.Email))
{
context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.FirstName))
{
context.Identity.AddClaim(new Claim("urn:foursquare:name", context.FirstName, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.Url))
{
context.Identity.AddClaim(new Claim("urn:foursquare:url", context.Url, XmlSchemaString, Options.AuthenticationType));
}
context.Properties = properties;
await Options.Provider.Authenticated(context);
return new AuthenticationTicket(context.Identity, context.Properties);
}
catch (Exception ex)
{
_logger.WriteError(ex.Message);
}
return new AuthenticationTicket(null, properties);
}
protected override Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode != 401)
{
return Task.FromResult<object>(null);
}
AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge != null)
{
string baseUri =
Request.Scheme +
Uri.SchemeDelimiter +
Request.Host +
Request.PathBase;
string currentUri =
baseUri +
Request.Path +
Request.QueryString;
string redirectUri =
baseUri +
Options.CallbackPath;
AuthenticationProperties properties = challenge.Properties;
if (string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = currentUri;
}
// OAuth2 10.12 CSRF
GenerateCorrelationId(properties);
string state = Options.StateDataFormat.Protect(properties);
Response.Cookies.Append("state_value", state, new CookieOptions(){Expires = DateTime.Now.AddDays(14)});
string authorizationEndpoint = "https://foursquare.com/oauth2/authenticate" +
"?client_id=" + Uri.EscapeDataString(Options.ClientId) +
"&response_type=code" +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri);
Response.Redirect(authorizationEndpoint);
}
return Task.FromResult<object>(null);
}
public override async Task<bool> InvokeAsync()
{
return await InvokeReplyPathAsync();
}
private async Task<bool> InvokeReplyPathAsync()
{
if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path)
{
// TODO: error responses
AuthenticationTicket ticket = await AuthenticateAsync();
if (ticket == null)
{
_logger.WriteWarning("Invalid return state, unable to redirect.");
Response.StatusCode = 500;
return true;
}
var context = new FoursquareReturnEndpointContext(Context, ticket);
context.SignInAsAuthenticationType = Options.SignInAsAuthenticationType;
context.RedirectUri = ticket.Properties.RedirectUri;
await Options.Provider.ReturnEndpoint(context);
if (context.SignInAsAuthenticationType != null &&
context.Identity != null)
{
ClaimsIdentity grantIdentity = context.Identity;
if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal))
{
grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType);
}
Context.Authentication.SignIn(context.Properties, grantIdentity);
}
if (!context.IsRequestCompleted && context.RedirectUri != null)
{
string redirectUri = context.RedirectUri;
if (context.Identity == null)
{
// add a redirect hint that sign-in failed in some way
redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied");
}
Response.Redirect(redirectUri);
context.RequestCompleted();
}
return context.IsRequestCompleted;
}
return false;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Impl.Auth.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Org.Apache.Http.Impl.Auth
{
/// <summary>
/// <para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/BasicSchemeFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/BasicSchemeFactory", AccessFlags = 33)]
public partial class BasicSchemeFactory : global::Org.Apache.Http.Auth.IAuthSchemeFactory
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public BasicSchemeFactory() /* MethodBuilder.Create */
{
}
/// <java-name>
/// newInstance
/// </java-name>
[Dot42.DexImport("newInstance", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/auth/AuthScheme;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Auth.IAuthScheme NewInstance(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Auth.IAuthScheme);
}
}
/// <summary>
/// <para>Signals NTLM protocol failure.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/NTLMEngineException
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/NTLMEngineException", AccessFlags = 33)]
public partial class NTLMEngineException : global::Org.Apache.Http.Auth.AuthenticationException
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public NTLMEngineException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new NTLMEngineException with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public NTLMEngineException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new NTLMEngineException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public NTLMEngineException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para>Abstract authentication scheme class that serves as a basis for all authentication schemes supported by HttpClient. This class defines the generic way of parsing an authentication challenge. It does not make any assumptions regarding the format of the challenge nor does it impose any specific way of responding to that challenge.</para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/AuthSchemeBase
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/AuthSchemeBase", AccessFlags = 1057)]
public abstract partial class AuthSchemeBase : global::Org.Apache.Http.Auth.IAuthScheme
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public AuthSchemeBase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Processes the given challenge token. Some authentication schemes may involve multiple challenge-response exchanges. Such schemes must be able to maintain the state information when dealing with sequential challenges</para><para></para>
/// </summary>
/// <java-name>
/// processChallenge
/// </java-name>
[Dot42.DexImport("processChallenge", "(Lorg/apache/http/Header;)V", AccessFlags = 1)]
public virtual void ProcessChallenge(global::Org.Apache.Http.IHeader header) /* MethodBuilder.Create */
{
}
/// <java-name>
/// parseChallenge
/// </java-name>
[Dot42.DexImport("parseChallenge", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 1028)]
protected internal abstract void ParseChallenge(global::Org.Apache.Http.Util.CharArrayBuffer buffer, int pos, int len) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns <code>true</code> if authenticating against a proxy, <code>false</code> otherwise.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if authenticating against a proxy, <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// isProxy
/// </java-name>
[Dot42.DexImport("isProxy", "()Z", AccessFlags = 1)]
public virtual bool IsProxy() /* MethodBuilder.Create */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getSchemeName", "()Ljava/lang/String;", AccessFlags = 1025)]
public virtual string GetSchemeName() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(string);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getParameter", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)]
public virtual string GetParameter(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(string);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getRealm", "()Ljava/lang/String;", AccessFlags = 1025)]
public virtual string GetRealm() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(string);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "isConnectionBased", "()Z", AccessFlags = 1025)]
public virtual bool IsConnectionBased() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "isComplete", "()Z", AccessFlags = 1025)]
public virtual bool IsComplete() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "authenticate", "(Lorg/apache/http/auth/Credentials;Lorg/apache/http/HttpRequest;)Lorg/apache/http" +
"/Header;", AccessFlags = 1025)]
public virtual global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, global::Org.Apache.Http.IHttpRequest request) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
public string SchemeName
{
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getSchemeName", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetSchemeName(); }
}
public string Realm
{
[Dot42.DexImport("org/apache/http/auth/AuthScheme", "getRealm", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetRealm(); }
}
}
/// <summary>
/// <para>Authentication credentials required to respond to a authentication challenge are invalid</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/UnsupportedDigestAlgorithmException
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/UnsupportedDigestAlgorithmException", AccessFlags = 33)]
public partial class UnsupportedDigestAlgorithmException : global::System.SystemException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new UnsupportedAuthAlgoritmException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public UnsupportedDigestAlgorithmException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new UnsupportedAuthAlgoritmException with the specified message.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public UnsupportedDigestAlgorithmException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new UnsupportedAuthAlgoritmException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public UnsupportedDigestAlgorithmException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <java-name>
/// org/apache/http/impl/auth/NTLMScheme
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/NTLMScheme", AccessFlags = 33)]
public partial class NTLMScheme : global::Org.Apache.Http.Impl.Auth.AuthSchemeBase
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/impl/auth/NTLMEngine;)V", AccessFlags = 1)]
public NTLMScheme(global::Org.Apache.Http.Impl.Auth.INTLMEngine engine) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns textual designation of the given authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the given authentication scheme </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetSchemeName() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getParameter
/// </java-name>
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1)]
public override string GetParameter(string name) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns authentication realm. If the concept of an authentication realm is not applicable to the given authentication scheme, returns <code>null</code>.</para><para></para>
/// </summary>
/// <returns>
/// <para>the authentication realm </para>
/// </returns>
/// <java-name>
/// getRealm
/// </java-name>
[Dot42.DexImport("getRealm", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetRealm() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Tests if the authentication scheme is provides authorization on a per connection basis instead of usual per request basis</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the scheme is connection based, <code>false</code> if the scheme is request based. </para>
/// </returns>
/// <java-name>
/// isConnectionBased
/// </java-name>
[Dot42.DexImport("isConnectionBased", "()Z", AccessFlags = 1)]
public override bool IsConnectionBased() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// parseChallenge
/// </java-name>
[Dot42.DexImport("parseChallenge", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 4)]
protected internal override void ParseChallenge(global::Org.Apache.Http.Util.CharArrayBuffer buffer, int pos, int len) /* MethodBuilder.Create */
{
}
/// <java-name>
/// authenticate
/// </java-name>
[Dot42.DexImport("authenticate", "(Lorg/apache/http/auth/Credentials;Lorg/apache/http/HttpRequest;)Lorg/apache/http" +
"/Header;", AccessFlags = 1)]
public override global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, global::Org.Apache.Http.IHttpRequest request) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHeader);
}
/// <summary>
/// <para>Authentication process may involve a series of challenge-response exchanges. This method tests if the authorization process has been completed, either successfully or unsuccessfully, that is, all the required authorization challenges have been processed in their entirety.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the authentication process has been completed, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isComplete
/// </java-name>
[Dot42.DexImport("isComplete", "()Z", AccessFlags = 1)]
public override bool IsComplete() /* MethodBuilder.Create */
{
return default(bool);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal NTLMScheme() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <summary>
/// <para>Returns textual designation of the given authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para>the name of the given authentication scheme </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
public string SchemeName
{
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSchemeName(); }
}
/// <summary>
/// <para>Returns authentication realm. If the concept of an authentication realm is not applicable to the given authentication scheme, returns <code>null</code>.</para><para></para>
/// </summary>
/// <returns>
/// <para>the authentication realm </para>
/// </returns>
/// <java-name>
/// getRealm
/// </java-name>
public string Realm
{
[Dot42.DexImport("getRealm", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetRealm(); }
}
}
/// <summary>
/// <para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/DigestSchemeFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/DigestSchemeFactory", AccessFlags = 33)]
public partial class DigestSchemeFactory : global::Org.Apache.Http.Auth.IAuthSchemeFactory
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public DigestSchemeFactory() /* MethodBuilder.Create */
{
}
/// <java-name>
/// newInstance
/// </java-name>
[Dot42.DexImport("newInstance", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/auth/AuthScheme;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.Auth.IAuthScheme NewInstance(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Auth.IAuthScheme);
}
}
/// <summary>
/// <para>Abstract NTLM authentication engine. The engine can be used to generate Type1 messages and Type3 messages in response to a Type2 challenge. </para><para>For details see </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/NTLMEngine
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/NTLMEngine", AccessFlags = 1537)]
public partial interface INTLMEngine
/* scope: __dot42__ */
{
/// <summary>
/// <para>Generates a Type1 message given the domain and workstation.</para><para></para>
/// </summary>
/// <returns>
/// <para>Type1 message </para>
/// </returns>
/// <java-name>
/// generateType1Msg
/// </java-name>
[Dot42.DexImport("generateType1Msg", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)]
string GenerateType1Msg(string domain, string workstation) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Generates a Type3 message given the user credentials and the authentication challenge.</para><para></para>
/// </summary>
/// <returns>
/// <para>Type3 response. </para>
/// </returns>
/// <java-name>
/// generateType3Msg
/// </java-name>
[Dot42.DexImport("generateType3Msg", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/la" +
"ng/String;)Ljava/lang/String;", AccessFlags = 1025)]
string GenerateType3Msg(string username, string password, string domain, string workstation, string challenge) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Basic authentication scheme as defined in RFC 2617. </para><para><para> </para><simplesectsep></simplesectsep><para>Rodney Waldhoff </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para>Ortwin Glueck </para><simplesectsep></simplesectsep><para>Sean C. Sullivan </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/BasicScheme
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/BasicScheme", AccessFlags = 33)]
public partial class BasicScheme : global::Org.Apache.Http.Impl.Auth.RFC2617Scheme
/* scope: __dot42__ */
{
/// <summary>
/// <para>Default constructor for the basic authetication scheme. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public BasicScheme() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns textual designation of the basic authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>basic</code> </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetSchemeName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Processes the Basic challenge.</para><para></para>
/// </summary>
/// <java-name>
/// processChallenge
/// </java-name>
[Dot42.DexImport("processChallenge", "(Lorg/apache/http/Header;)V", AccessFlags = 1)]
public override void ProcessChallenge(global::Org.Apache.Http.IHeader header) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests if the Basic authentication process has been completed.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if Basic authorization has been processed, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isComplete
/// </java-name>
[Dot42.DexImport("isComplete", "()Z", AccessFlags = 1)]
public override bool IsComplete() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns <code>false</code>. Basic authentication scheme is request based.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>false</code>. </para>
/// </returns>
/// <java-name>
/// isConnectionBased
/// </java-name>
[Dot42.DexImport("isConnectionBased", "()Z", AccessFlags = 1)]
public override bool IsConnectionBased() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Produces basic authorization header for the given set of Credentials.</para><para></para>
/// </summary>
/// <returns>
/// <para>a basic authorization string </para>
/// </returns>
/// <java-name>
/// authenticate
/// </java-name>
[Dot42.DexImport("authenticate", "(Lorg/apache/http/auth/Credentials;Lorg/apache/http/HttpRequest;)Lorg/apache/http" +
"/Header;", AccessFlags = 1)]
public override global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, global::Org.Apache.Http.IHttpRequest request) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHeader);
}
/// <summary>
/// <para>Returns a basic <code>Authorization</code> header value for the given Credentials and charset.</para><para></para>
/// </summary>
/// <returns>
/// <para>a basic authorization header </para>
/// </returns>
/// <java-name>
/// authenticate
/// </java-name>
[Dot42.DexImport("authenticate", "(Lorg/apache/http/auth/Credentials;Ljava/lang/String;Z)Lorg/apache/http/Header;", AccessFlags = 9)]
public static global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, string charset, bool proxy) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHeader);
}
/// <summary>
/// <para>Returns textual designation of the basic authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>basic</code> </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
public string SchemeName
{
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSchemeName(); }
}
}
/// <summary>
/// <para>Digest authentication scheme as defined in RFC 2617. Both MD5 (default) and MD5-sess are supported. Currently only qop=auth or no qop is supported. qop=auth-int is unsupported. If auth and auth-int are provided, auth is used. </para><para>Credential charset is configured via the credential charset parameter. Since the digest username is included as clear text in the generated Authentication header, the charset of the username must be compatible with the http element charset. </para><para><para> </para><simplesectsep></simplesectsep><para>Rodney Waldhoff </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para>Ortwin Glueck </para><simplesectsep></simplesectsep><para>Sean C. Sullivan </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/DigestScheme
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/DigestScheme", AccessFlags = 33)]
public partial class DigestScheme : global::Org.Apache.Http.Impl.Auth.RFC2617Scheme
/* scope: __dot42__ */
{
/// <summary>
/// <para>Default constructor for the digest authetication scheme. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public DigestScheme() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Processes the Digest challenge.</para><para></para>
/// </summary>
/// <java-name>
/// processChallenge
/// </java-name>
[Dot42.DexImport("processChallenge", "(Lorg/apache/http/Header;)V", AccessFlags = 1)]
public override void ProcessChallenge(global::Org.Apache.Http.IHeader header) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests if the Digest authentication process has been completed.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if Digest authorization has been processed, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isComplete
/// </java-name>
[Dot42.DexImport("isComplete", "()Z", AccessFlags = 1)]
public override bool IsComplete() /* MethodBuilder.Create */
{
return default(bool);
}
/// <summary>
/// <para>Returns textual designation of the digest authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>digest</code> </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetSchemeName() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns <code>false</code>. Digest authentication scheme is request based.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>false</code>. </para>
/// </returns>
/// <java-name>
/// isConnectionBased
/// </java-name>
[Dot42.DexImport("isConnectionBased", "()Z", AccessFlags = 1)]
public override bool IsConnectionBased() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// overrideParamter
/// </java-name>
[Dot42.DexImport("overrideParamter", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)]
public virtual void OverrideParamter(string name, string value) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Produces a digest authorization string for the given set of Credentials, method name and URI.</para><para></para>
/// </summary>
/// <returns>
/// <para>a digest authorization string </para>
/// </returns>
/// <java-name>
/// authenticate
/// </java-name>
[Dot42.DexImport("authenticate", "(Lorg/apache/http/auth/Credentials;Lorg/apache/http/HttpRequest;)Lorg/apache/http" +
"/Header;", AccessFlags = 1)]
public override global::Org.Apache.Http.IHeader Authenticate(global::Org.Apache.Http.Auth.ICredentials credentials, global::Org.Apache.Http.IHttpRequest request) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHeader);
}
/// <summary>
/// <para>Creates a random cnonce value based on the current time.</para><para></para>
/// </summary>
/// <returns>
/// <para>The cnonce value as String. </para>
/// </returns>
/// <java-name>
/// createCnonce
/// </java-name>
[Dot42.DexImport("createCnonce", "()Ljava/lang/String;", AccessFlags = 9)]
public static string CreateCnonce() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns textual designation of the digest authentication scheme.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>digest</code> </para>
/// </returns>
/// <java-name>
/// getSchemeName
/// </java-name>
public string SchemeName
{
[Dot42.DexImport("getSchemeName", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetSchemeName(); }
}
}
/// <summary>
/// <para>Abstract authentication scheme class that lays foundation for all RFC 2617 compliant authetication schemes and provides capabilities common to all authentication schemes defined in RFC 2617.</para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/auth/RFC2617Scheme
/// </java-name>
[Dot42.DexImport("org/apache/http/impl/auth/RFC2617Scheme", AccessFlags = 1057)]
public abstract partial class RFC2617Scheme : global::Org.Apache.Http.Impl.Auth.AuthSchemeBase
/* scope: __dot42__ */
{
/// <summary>
/// <para>Default constructor for RFC2617 compliant authetication schemes. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public RFC2617Scheme() /* MethodBuilder.Create */
{
}
/// <java-name>
/// parseChallenge
/// </java-name>
[Dot42.DexImport("parseChallenge", "(Lorg/apache/http/util/CharArrayBuffer;II)V", AccessFlags = 4)]
protected internal override void ParseChallenge(global::Org.Apache.Http.Util.CharArrayBuffer buffer, int pos, int len) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns authentication parameters map. Keys in the map are lower-cased.</para><para></para>
/// </summary>
/// <returns>
/// <para>the map of authentication parameters </para>
/// </returns>
/// <java-name>
/// getParameters
/// </java-name>
[Dot42.DexImport("getParameters", "()Ljava/util/Map;", AccessFlags = 4, Signature = "()Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;")]
protected internal virtual global::Java.Util.IMap<string, string> GetParameters() /* MethodBuilder.Create */
{
return default(global::Java.Util.IMap<string, string>);
}
/// <summary>
/// <para>Returns authentication parameter with the given name, if available.</para><para></para>
/// </summary>
/// <returns>
/// <para>the parameter with the given name </para>
/// </returns>
/// <java-name>
/// getParameter
/// </java-name>
[Dot42.DexImport("getParameter", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1)]
public override string GetParameter(string name) /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns authentication realm. The realm may not be null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the authentication realm </para>
/// </returns>
/// <java-name>
/// getRealm
/// </java-name>
[Dot42.DexImport("getRealm", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetRealm() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns authentication parameters map. Keys in the map are lower-cased.</para><para></para>
/// </summary>
/// <returns>
/// <para>the map of authentication parameters </para>
/// </returns>
/// <java-name>
/// getParameters
/// </java-name>
protected internal global::Java.Util.IMap<string, string> Parameters
{
[Dot42.DexImport("getParameters", "()Ljava/util/Map;", AccessFlags = 4, Signature = "()Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;")]
get{ return GetParameters(); }
}
/// <summary>
/// <para>Returns authentication realm. The realm may not be null.</para><para></para>
/// </summary>
/// <returns>
/// <para>the authentication realm </para>
/// </returns>
/// <java-name>
/// getRealm
/// </java-name>
public string Realm
{
[Dot42.DexImport("getRealm", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetRealm(); }
}
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Threading;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem
{
internal class Transactional
{
/// Run 'stepWithEffect' followed by continuation 'k', but if the continuation later fails with
/// an exception, undo the original effect by running 'compensatingEffect'.
/// Note: if 'compensatingEffect' throws, it masks the original exception.
/// Note: This is a monadic bind where the first two arguments comprise M<A>.
public static B Try<A, B>(Func<A> stepWithEffect, Action<A> compensatingEffect, Func<A, B> k)
{
var stepCompleted = false;
var allOk = false;
A a = default(A);
try
{
a = stepWithEffect();
stepCompleted = true;
var r = k(a);
allOk = true;
return r;
}
finally
{
if (!allOk && stepCompleted)
{
compensatingEffect(a);
}
}
}
// if A == void, this is the overload
public static B Try<B>(Action stepWithEffect, Action compensatingEffect, Func<B> k)
{
return Try(
() => { stepWithEffect(); return 0; },
(int dummy) => { compensatingEffect(); },
(int dummy) => { return k(); });
}
// if A & B are both void, this is the overload
public static void Try(Action stepWithEffect, Action compensatingEffect, Action k)
{
Try(
() => { stepWithEffect(); return 0; },
(int dummy) => { compensatingEffect(); },
(int dummy) => { k(); return 0; });
}
}
[CLSCompliant(false)]
[ComVisible(true)]
public class FileNode : HierarchyNode
{
private static Dictionary<string, int> extensionIcons;
/// <summary>
/// overwrites of the generic hierarchyitem.
/// </summary>
[System.ComponentModel.BrowsableAttribute(false)]
public override string Caption
{
get
{
// Use LinkedIntoProjectAt property if available
string caption = this.ItemNode.GetMetadata(ProjectFileConstants.LinkedIntoProjectAt);
if (caption == null || caption.Length == 0)
{
// Otherwise use filename
caption = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
caption = Path.GetFileName(caption);
}
return caption;
}
}
public override int ImageIndex
{
get
{
// Check if the file is there.
if (!this.CanShowDefaultIcon())
{
return (int)ProjectNode.ImageName.MissingFile;
}
//Check for known extensions
int imageIndex;
string extension = System.IO.Path.GetExtension(this.FileName);
if ((string.IsNullOrEmpty(extension)) || (!extensionIcons.TryGetValue(extension, out imageIndex)))
{
// Missing or unknown extension; let the base class handle this case.
return base.ImageIndex;
}
// The file type is known and there is an image for it in the image list.
return imageIndex;
}
}
public override Guid ItemTypeGuid
{
get { return VSConstants.GUID_ItemType_PhysicalFile; }
}
public override int MenuCommandId
{
get { return VsMenus.IDM_VS_CTXT_ITEMNODE; }
}
public override string Url
{
get
{
string path = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
if (String.IsNullOrEmpty(path))
{
return String.Empty;
}
Url url;
if (Path.IsPathRooted(path))
{
// Use absolute path
url = new Microsoft.VisualStudio.Shell.Url(path);
}
else
{
// Path is relative, so make it relative to project path
url = new Url(this.ProjectMgr.BaseURI, path);
}
return url.AbsoluteUrl;
}
}
static FileNode()
{
// Build the dictionary with the mapping between some well known extensions
// and the index of the icons inside the standard image list.
extensionIcons = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
extensionIcons.Add(".aspx", (int)ProjectNode.ImageName.WebForm);
extensionIcons.Add(".asax", (int)ProjectNode.ImageName.GlobalApplicationClass);
extensionIcons.Add(".asmx", (int)ProjectNode.ImageName.WebService);
extensionIcons.Add(".ascx", (int)ProjectNode.ImageName.WebUserControl);
extensionIcons.Add(".asp", (int)ProjectNode.ImageName.ASPPage);
extensionIcons.Add(".config", (int)ProjectNode.ImageName.WebConfig);
extensionIcons.Add(".htm", (int)ProjectNode.ImageName.HTMLPage);
extensionIcons.Add(".html", (int)ProjectNode.ImageName.HTMLPage);
extensionIcons.Add(".css", (int)ProjectNode.ImageName.StyleSheet);
extensionIcons.Add(".xsl", (int)ProjectNode.ImageName.StyleSheet);
extensionIcons.Add(".vbs", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".js", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".wsf", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".txt", (int)ProjectNode.ImageName.TextFile);
extensionIcons.Add(".resx", (int)ProjectNode.ImageName.Resources);
extensionIcons.Add(".rc", (int)ProjectNode.ImageName.Resources);
extensionIcons.Add(".bmp", (int)ProjectNode.ImageName.Bitmap);
extensionIcons.Add(".ico", (int)ProjectNode.ImageName.Icon);
extensionIcons.Add(".gif", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".jpg", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".png", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".map", (int)ProjectNode.ImageName.ImageMap);
extensionIcons.Add(".wav", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".mid", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".midi", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".avi", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mov", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mpg", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mpeg", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".cab", (int)ProjectNode.ImageName.CAB);
extensionIcons.Add(".jar", (int)ProjectNode.ImageName.JAR);
extensionIcons.Add(".xslt", (int)ProjectNode.ImageName.XSLTFile);
extensionIcons.Add(".xsd", (int)ProjectNode.ImageName.XMLSchema);
extensionIcons.Add(".xml", (int)ProjectNode.ImageName.XMLFile);
extensionIcons.Add(".pfx", (int)ProjectNode.ImageName.PFX);
extensionIcons.Add(".snk", (int)ProjectNode.ImageName.SNK);
}
/// <summary>
/// Constructor for the FileNode
/// </summary>
/// <param name="root">Root of the hierarchy</param>
/// <param name="element">Associated project element</param>
internal FileNode(ProjectNode root, ProjectElement element, uint? hierarchyId = null)
: base(root, element, hierarchyId)
{
if (this.ProjectMgr.NodeHasDesigner(this.ItemNode.GetMetadata(ProjectFileConstants.Include)))
{
this.HasDesigner = true;
}
}
public virtual string RelativeFilePath
{
get
{
return PackageUtilities.MakeRelativeIfRooted(this.Url, this.ProjectMgr.BaseURI);
}
}
public override NodeProperties CreatePropertiesObject()
{
return new FileNodeProperties(this);
}
public override object GetIconHandle(bool open)
{
int index = this.ImageIndex;
if (NoImage == index)
{
// There is no image for this file; let the base class handle this case.
return base.GetIconHandle(open);
}
// Return the handle for the image.
return this.ProjectMgr.ImageHandler.GetIconHandle(index);
}
/// <summary>
/// Get an instance of the automation object for a FileNode
/// </summary>
/// <returns>An instance of the Automation.OAFileNode if succeeded</returns>
public override object GetAutomationObject()
{
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return null;
}
return new Automation.OAFileItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
/// <summary>
/// Renames a file node.
/// </summary>
/// <param name="label">The new name.</param>
/// <returns>An errorcode for failure or S_OK.</returns>
/// <exception cref="InvalidOperationException">if the file cannot be validated</exception>
/// <devremark>
/// We are going to throw instaed of showing messageboxes, since this method is called from various places where a dialog box does not make sense.
/// For example the FileNodeProperties are also calling this method. That should not show directly a messagebox.
/// Also the automation methods are also calling SetEditLabel
/// </devremark>
public override int SetEditLabel(string label)
{
// IMPORTANT NOTE: This code will be called when a parent folder is renamed. As such, it is
// expected that we can be called with a label which is the same as the current
// label and this should not be considered a NO-OP.
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return VSConstants.E_FAIL;
}
// Validate the filename.
if (String.IsNullOrEmpty(label))
{
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, CultureInfo.CurrentUICulture));
}
else if (label.Length > NativeMethods.MAX_PATH)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.PathTooLong, CultureInfo.CurrentUICulture), label));
}
else if (Utilities.IsFileNameInvalid(label))
{
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, CultureInfo.CurrentUICulture));
}
for (HierarchyNode n = this.Parent.FirstChild; n != null; n = n.NextSibling)
{
if (n != this && String.Compare(n.Caption, label, StringComparison.OrdinalIgnoreCase) == 0)
{
//A file or folder with the name '{0}' already exists on disk at this location. Please choose another name.
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileOrFolderAlreadyExists, CultureInfo.CurrentUICulture), label));
}
}
string fileName = Path.GetFileNameWithoutExtension(label);
// If there is no filename or it starts with a leading dot issue an error message and quit.
if (String.IsNullOrEmpty(fileName) || fileName[0] == '.')
{
throw new InvalidOperationException(SR.GetString(SR.FileNameCannotContainALeadingPeriod, CultureInfo.CurrentUICulture));
}
// Verify that the file extension is unchanged
string strRelPath = Path.GetFileName(this.ItemNode.GetMetadata(ProjectFileConstants.Include));
if (String.Compare(Path.GetExtension(strRelPath), Path.GetExtension(label), StringComparison.OrdinalIgnoreCase) != 0)
{
// Don't prompt if we are in automation function.
if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
{
// Prompt to confirm that they really want to change the extension of the file
string message = SR.GetString(SR.ConfirmExtensionChange, CultureInfo.CurrentUICulture, new string[] { label });
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Debug.Assert(shell != null, "Could not get the ui shell from the project");
if (shell == null)
{
return VSConstants.E_FAIL;
}
if (!PromptYesNoWithYesSelected(message, null, OLEMSGICON.OLEMSGICON_INFO, shell))
{
// The user cancelled the confirmation for changing the extension.
// Return S_OK in order not to show any extra dialog box
return VSConstants.S_OK;
}
}
}
// Build the relative path by looking at folder names above us as one scenarios
// where we get called is when a folder above us gets renamed (in which case our path is invalid)
HierarchyNode parent = this.Parent;
while (parent != null && (parent is FolderNode))
{
strRelPath = Path.Combine(parent.Caption, strRelPath);
parent = parent.Parent;
}
var result = SetEditLabel(label, strRelPath);
return result;
}
// Implementation of functionality from Microsoft.VisualStudio.Shell.VsShellUtilities.PromptYesNo
// Difference: Yes button is default
private static bool PromptYesNoWithYesSelected(string message, string title, OLEMSGICON icon, IVsUIShell uiShell)
{
Guid emptyGuid = Guid.Empty;
int result = 0;
#pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs
ThreadHelper.Generic.Invoke(() =>
#pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs
{
ErrorHandler.ThrowOnFailure(uiShell.ShowMessageBox(0u, ref emptyGuid, title, message, null, 0u, OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, icon, 0, out result));
});
return result == (int)NativeMethods.IDYES;
}
public override string GetMkDocument()
{
Debug.Assert(this.Url != null, "No url specified for this node");
return this.Url;
}
/// <summary>
/// Delete the item corresponding to the specified path from storage.
/// </summary>
/// <param name="path"></param>
public override void DeleteFromStorage(string path)
{
if (File.Exists(path))
{
File.SetAttributes(path, FileAttributes.Normal); // make sure it's not readonly.
File.Delete(path);
}
}
/// <summary>
/// Rename the underlying document based on the change the user just made to the edit label.
/// </summary>
public int SetEditLabel(string label, string relativePath)
{
int returnValue = VSConstants.S_OK;
uint oldId = this.ID;
string strSavePath = Path.GetDirectoryName(relativePath);
string newRelPath = Path.Combine(strSavePath, label);
if (!Path.IsPathRooted(relativePath))
{
strSavePath = Path.Combine(Path.GetDirectoryName(this.ProjectMgr.BaseURI.Uri.LocalPath), strSavePath);
}
string newName = Path.Combine(strSavePath, label);
if (NativeMethods.IsSamePath(newName, this.Url))
{
// If this is really a no-op, then nothing to do
if (String.Compare(newName, this.Url, StringComparison.Ordinal) == 0)
return VSConstants.S_FALSE;
}
else
{
// If the renamed file already exists then quit (unless it is the result of the parent having done the move).
if (IsFileOnDisk(newName)
&& (IsFileOnDisk(this.Url)
|| String.Compare(Path.GetFileName(newName), Path.GetFileName(this.Url), StringComparison.Ordinal) != 0))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileCannotBeRenamedToAnExistingFile, CultureInfo.CurrentUICulture), label));
}
else if (newName.Length > NativeMethods.MAX_PATH)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.PathTooLong, CultureInfo.CurrentUICulture), label));
}
}
string oldName = this.Url;
// must update the caption prior to calling RenameDocument, since it may
// cause queries of that property (such as from open editors).
string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
RenameDocument(oldName, newName);
// Return S_FALSE if the hierarchy item id has changed. This forces VS to flush the stale
// hierarchy item id.
if (returnValue == (int)VSConstants.S_OK || returnValue == (int)VSConstants.S_FALSE || returnValue == VSConstants.OLE_E_PROMPTSAVECANCELLED)
{
return (oldId == this.ID) ? VSConstants.S_OK : (int)VSConstants.S_FALSE;
}
return returnValue;
}
/// <summary>
/// Returns a specific Document manager to handle files
/// </summary>
/// <returns>Document manager object</returns>
internal override DocumentManager GetDocumentManager()
{
return new FileDocumentManager(this);
}
/// <summary>
/// Called by the drag&drop implementation to ask the node
/// which is being dragged/droped over which nodes should
/// process the operation.
/// This allows for dragging to a node that cannot contain
/// items to let its parent accept the drop, while a reference
/// node delegate to the project and a folder/project node to itself.
/// </summary>
/// <returns></returns>
public override HierarchyNode GetDragTargetHandlerNode()
{
Debug.Assert(this.ProjectMgr != null, " The project manager is null for the filenode");
HierarchyNode handlerNode = this;
while (handlerNode != null && !(handlerNode is ProjectNode || handlerNode is FolderNode))
handlerNode = handlerNode.Parent;
if (handlerNode == null)
handlerNode = this.ProjectMgr;
return handlerNode;
}
public override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if (this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
// Exec on special filenode commands
if (cmdGroup == VsMenus.guidStandardCommandSet97)
{
IVsWindowFrame windowFrame = null;
switch ((VsCommands)cmd)
{
case VsCommands.ViewCode:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Code, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.ViewForm:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Designer, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.Open:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, WindowFrameShowAction.Show);
case VsCommands.OpenWith:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, true, VSConstants.LOGVIEWID_UserChooseView, out windowFrame, WindowFrameShowAction.Show);
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result)
{
if (cmdGroup == VsMenus.guidStandardCommandSet97)
{
switch ((VsCommands)cmd)
{
case VsCommands.Copy:
case VsCommands.Paste:
case VsCommands.Cut:
case VsCommands.Rename:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
case VsCommands.ViewCode:
case VsCommands.Open:
case VsCommands.OpenWith:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else if (cmdGroup == VsMenus.guidStandardCommandSet2K)
{
if ((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT)
{
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else
{
return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP;
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
public override void DoDefaultAction()
{
CCITracing.TraceCall();
FileDocumentManager manager = this.GetDocumentManager() as FileDocumentManager;
Debug.Assert(manager != null, "Could not get the FileDocumentManager");
manager.Open(false, false, WindowFrameShowAction.Show);
}
/// <summary>
/// Performs a SaveAs operation of an open document. Called from SaveItem after the running document table has been updated with the new doc data.
/// </summary>
/// <param name="docData">A pointer to the document in the rdt</param>
/// <param name="newFilePath">The new file path to the document</param>
/// <returns></returns>
public override int AfterSaveItemAs(IntPtr docData, string newFilePath)
{
if (String.IsNullOrEmpty(newFilePath))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "newFilePath");
}
int returnCode = VSConstants.S_OK;
newFilePath = newFilePath.Trim();
//Identify if Path or FileName are the same for old and new file
string newDirectoryName = Path.GetDirectoryName(newFilePath);
Uri newDirectoryUri = new Uri(newDirectoryName);
string newCanonicalDirectoryName = newDirectoryUri.LocalPath;
newCanonicalDirectoryName = newCanonicalDirectoryName.TrimEnd(Path.DirectorySeparatorChar);
string oldCanonicalDirectoryName = new Uri(Path.GetDirectoryName(this.GetMkDocument())).LocalPath;
oldCanonicalDirectoryName = oldCanonicalDirectoryName.TrimEnd(Path.DirectorySeparatorChar);
string errorMessage = String.Empty;
bool isSamePath = NativeMethods.IsSamePath(newCanonicalDirectoryName, oldCanonicalDirectoryName);
bool isSameFile = NativeMethods.IsSamePath(newFilePath, this.Url);
// Currently we do not support if the new directory is located outside the project cone
string projectCannonicalDirecoryName = new Uri(this.ProjectMgr.ProjectFolder).LocalPath;
projectCannonicalDirecoryName = projectCannonicalDirecoryName.TrimEnd(Path.DirectorySeparatorChar);
if (!isSamePath && newCanonicalDirectoryName.IndexOf(projectCannonicalDirecoryName, StringComparison.OrdinalIgnoreCase) == -1)
{
errorMessage = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.LinkedItemsAreNotSupported, CultureInfo.CurrentUICulture), Path.GetFileNameWithoutExtension(newFilePath));
throw new InvalidOperationException(errorMessage);
}
//Get target container
HierarchyNode targetContainer = null;
if (isSamePath)
{
targetContainer = this.Parent;
}
else if (NativeMethods.IsSamePath(newCanonicalDirectoryName, projectCannonicalDirecoryName))
{
//the projectnode is the target container
targetContainer = this.ProjectMgr;
}
else
{
//search for the target container among existing child nodes
targetContainer = this.ProjectMgr.FindChild(newDirectoryName);
if (targetContainer != null && (targetContainer is FileNode))
{
// We already have a file node with this name in the hierarchy.
errorMessage = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileAlreadyExistsAndCannotBeRenamed, CultureInfo.CurrentUICulture), Path.GetFileNameWithoutExtension(newFilePath));
throw new InvalidOperationException(errorMessage);
}
}
if (targetContainer == null)
{
// Add a chain of subdirectories to the project.
string relativeUri = PackageUtilities.GetPathDistance(this.ProjectMgr.BaseURI.Uri, newDirectoryUri);
Debug.Assert(!String.IsNullOrEmpty(relativeUri) && relativeUri != newDirectoryUri.LocalPath, "Could not make pat distance of " + this.ProjectMgr.BaseURI.Uri.LocalPath + " and " + newDirectoryUri);
targetContainer = this.ProjectMgr.CreateFolderNodes(relativeUri);
}
Debug.Assert(targetContainer != null, "We should have found a target node by now");
//Suspend file changes while we rename the document
string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
string oldName = Path.Combine(this.ProjectMgr.ProjectFolder, oldrelPath);
SuspendFileChanges sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
try
{
// Rename the node.
DocumentManager.UpdateCaption(this.ProjectMgr.Site, Path.GetFileName(newFilePath), docData);
// Check if the file name was actually changed.
// In same cases (e.g. if the item is a file and the user has changed its encoding) this function
// is called even if there is no real rename.
var oldParent = this.Parent;
if (!isSameFile || (oldParent.ID != targetContainer.ID))
{
// The path of the file is changed or its parent is changed; in both cases we have
// to rename the item.
this.RenameFileNode(oldName, newFilePath, targetContainer.ID);
OnInvalidateItems(oldParent);
// This is what othe project systems do; for the purposes of source control, the old file is removed, and a new file is added
// (althought the old file stays on disk!)
this.ProjectMgr.Tracker.OnItemRemoved(oldName, VSREMOVEFILEFLAGS.VSREMOVEFILEFLAGS_NoFlags);
this.ProjectMgr.Tracker.OnItemAdded(newFilePath, VSADDFILEFLAGS.VSADDFILEFLAGS_NoFlags);
}
}
catch (Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
this.RecoverFromRenameFailure(newFilePath, oldrelPath);
throw;
}
finally
{
sfc.Resume();
}
return returnCode;
}
/// <summary>
/// Determines if this is node a valid node for painting the default file icon.
/// </summary>
/// <returns></returns>
public override bool CanShowDefaultIcon()
{
string moniker = this.GetMkDocument();
if (String.IsNullOrEmpty(moniker) || !File.Exists(moniker))
{
return false;
}
return true;
}
public virtual string FileName
{
get
{
return this.Caption;
}
set
{
this.SetEditLabel(value);
}
}
/// <summary>
/// Determine if this item is represented physical on disk and shows a messagebox in case that the file is not present and a UI is to be presented.
/// </summary>
/// <param name="showMessage">true if user should be presented for UI in case the file is not present</param>
/// <returns>true if file is on disk</returns>
public virtual bool IsFileOnDisk(bool showMessage)
{
bool fileExist = IsFileOnDisk(this.Url);
if (!fileExist && showMessage && !Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
{
string message = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.ItemDoesNotExistInProjectDirectory, CultureInfo.CurrentUICulture), this.Caption);
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton);
}
return fileExist;
}
/// <summary>
/// Determine if the file represented by "path" exist in storage.
/// Override this method if your files are not persisted on disk.
/// </summary>
/// <param name="path">Url representing the file</param>
/// <returns>True if the file exist</returns>
public virtual bool IsFileOnDisk(string path)
{
return File.Exists(path);
}
/// <summary>
/// Renames the file in the hierarchy by removing old node and adding a new node in the hierarchy.
/// </summary>
/// <param name="oldFileName">The old file name.</param>
/// <param name="newFileName">The new file name</param>
/// <param name="newParentId">The new parent id of the item.</param>
/// <returns>The newly added FileNode.</returns>
/// <remarks>While a new node will be used to represent the item, the underlying MSBuild item will be the same and as a result file properties saved in the project file will not be lost.</remarks>
public virtual FileNode RenameFileNode(string oldFileName, string newFileName, uint newParentId)
{
if (string.Compare(oldFileName, newFileName, StringComparison.Ordinal) == 0)
{
// We do not want to rename the same file
return null;
}
string[] file = new string[1];
file[0] = newFileName;
VSADDRESULT[] result = new VSADDRESULT[1];
Guid emptyGuid = Guid.Empty;
FileNode childAdded = null;
string originalInclude = this.ItemNode.Item.UnevaluatedInclude;
return Transactional.Try(
// Action
() =>
{
// It's unfortunate that MPF implements rename in terms of AddItemWithSpecific. Since this
// is the case, we have to pass false to prevent AddITemWithSpecific to fire Add events on
// the IVsTrackProjectDocuments2 tracker. Otherwise, clients listening to this event
// (SCCI, for example) will be really confused.
using (this.ProjectMgr.ExtensibilityEventsHelper.SuspendEvents())
{
var currentId = this.ID;
// actual deletion is delayed until all checks are passed
Func<uint> getIdOfExistingItem =
() =>
{
this.OnItemDeleted();
this.Parent.RemoveChild(this);
return currentId;
};
// raises OnItemAdded inside
ErrorHandler.ThrowOnFailure(this.ProjectMgr.AddItemWithSpecific(newParentId, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, null, 0, file, IntPtr.Zero, 0, ref emptyGuid, null, ref emptyGuid, result, false, getIdOfExistingItem));
childAdded = this.ProjectMgr.FindChild(newFileName) as FileNode;
Debug.Assert(childAdded != null, "Could not find the renamed item in the hierarchy");
}
},
// Compensation
() =>
{
// it failed, but 'this' is dead and 'childAdded' is here to stay, so fix the latter back
using (this.ProjectMgr.ExtensibilityEventsHelper.SuspendEvents())
{
childAdded.ItemNode.Rename(originalInclude);
childAdded.ItemNode.RefreshProperties();
}
},
// Continuation
() =>
{
// Since this node has been removed all of its state is zombied at this point
// Do not call virtual methods after this point since the object is in a deleted state.
// Remove the item created by the add item. We need to do this otherwise we will have two items.
// Please be aware that we have not removed the ItemNode associated to the removed file node from the hierrachy.
// What we want to achieve here is to reuse the existing build item.
// We want to link to the newly created node to the existing item node and addd the new include.
//temporarily keep properties from new itemnode since we are going to overwrite it
string newInclude = childAdded.ItemNode.Item.UnevaluatedInclude;
string dependentOf = childAdded.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);
childAdded.ItemNode.RemoveFromProjectFile();
// Assign existing msbuild item to the new childnode
childAdded.ItemNode = this.ItemNode;
childAdded.ItemNode.Item.ItemType = this.ItemNode.ItemName;
childAdded.ItemNode.Item.Xml.Include = newInclude;
if (!string.IsNullOrEmpty(dependentOf))
childAdded.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, dependentOf);
childAdded.ItemNode.RefreshProperties();
// Extensibilty events has rename
this.ProjectMgr.ExtensibilityEventsHelper.FireItemRenamed(childAdded, Path.GetFileName(originalInclude));
//Update the new document in the RDT.
try
{
DocumentManager.RenameDocument(this.ProjectMgr.Site, oldFileName, newFileName, childAdded.ID);
// The current automation node is renamed, but the hierarchy ID is now pointing to the old item, which
// is invalid. Update it.
this.ID = childAdded.ID;
//Update FirstChild
childAdded.FirstChild = this.FirstChild;
//Update ChildNodes
SetNewParentOnChildNodes(childAdded);
RenameChildNodes(childAdded);
return childAdded;
}
finally
{
//Select the new node in the hierarchy
IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer);
uiWindow.ExpandItem(this.ProjectMgr.InteropSafeIVsUIHierarchy, childAdded.ID, EXPANDFLAGS.EXPF_SelectItem);
}
});
}
/// <summary>
/// Rename all childnodes
/// </summary>
/// <param name="parentNode">The newly added Parent node.</param>
public virtual void RenameChildNodes(FileNode parentNode)
{
foreach (HierarchyNode child in GetChildNodes())
{
FileNode childNode = child as FileNode;
if (null == childNode)
{
continue;
}
string newfilename;
if (childNode.HasParentNodeNameRelation)
{
string relationalName = childNode.Parent.GetRelationalName();
string extension = childNode.GetRelationNameExtension();
newfilename = relationalName + extension;
newfilename = Path.Combine(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), newfilename);
}
else
{
newfilename = Path.Combine(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), childNode.Caption);
}
childNode.RenameDocument(childNode.GetMkDocument(), newfilename);
//We must update the DependsUpon property since the rename operation will not do it if the childNode is not renamed
//which happens if the is no name relation between the parent and the child
string dependentOf = childNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);
if (!string.IsNullOrEmpty(dependentOf))
{
childNode.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, childNode.Parent.ItemNode.GetMetadata(ProjectFileConstants.Include));
}
}
}
/// <summary>
/// Tries recovering from a rename failure.
/// </summary>
/// <param name="fileThatFailed"> The file that failed to be renamed.</param>
/// <param name="originalFileName">The original filenamee</param>
public virtual void RecoverFromRenameFailure(string fileThatFailed, string originalFileName)
{
// TODO does this do anything useful? did it ever change in the first place?
if (this.ItemNode != null && !String.IsNullOrEmpty(originalFileName))
{
this.ItemNode.Rename(originalFileName);
this.ItemNode.RefreshProperties();
}
}
public override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation)
{
if (deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage)
{
return this.ProjectMgr.CanProjectDeleteItems;
}
return false;
}
/// <summary>
/// This should be overriden for node that are not saved on disk
/// </summary>
/// <param name="oldName">Previous name in storage</param>
/// <param name="newName">New name in storage</param>
public virtual void RenameInStorage(string oldName, string newName)
{
File.Move(oldName, newName);
}
/// <summary>
/// This method should be overridden to provide the list of special files and associated flags for source control.
/// </summary>
/// <param name="sccFile">One of the file associated to the node.</param>
/// <param name="files">The list of files to be placed under source control.</param>
/// <param name="flags">The flags that are associated to the files.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "scc")]
public override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags)
{
if (this.ExcludeNodeFromScc)
{
return;
}
if (files == null)
{
throw new ArgumentNullException("files");
}
if (flags == null)
{
throw new ArgumentNullException("flags");
}
foreach (HierarchyNode node in this.GetChildNodes())
{
files.Add(node.GetMkDocument());
}
}
/// <summary>
/// Get's called to rename the eventually running document this hierarchyitem points to
/// </summary>
/// returns FALSE if the doc can not be renamed
public bool RenameDocument(string oldName, string newName)
{
IVsRunningDocumentTable pRDT = this.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (pRDT == null) return false;
IntPtr docData = IntPtr.Zero;
IVsHierarchy pIVsHierarchy;
uint itemId;
uint uiVsDocCookie;
SuspendFileChanges sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
try
{
VSRENAMEFILEFLAGS renameflag = VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags;
ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie));
if (pIVsHierarchy != null && !Utilities.IsSameComObject(pIVsHierarchy, this.ProjectMgr))
{
// Don't rename it if it wasn't opened by us.
return false;
}
// ask other potentially running packages
if (!this.ProjectMgr.Tracker.CanRenameItem(oldName, newName, renameflag))
{
return false;
}
// Allow the user to "fix" the project by renaming the item in the hierarchy
// to the real name of the file on disk.
bool shouldRenameInStorage = IsFileOnDisk(oldName) || !IsFileOnDisk(newName);
Transactional.Try(
// Action
() => { if (shouldRenameInStorage) RenameInStorage(oldName, newName); },
// Compensation
() => { if (shouldRenameInStorage) RenameInStorage(newName, oldName); },
// Continuation
() =>
{
string newFileName = Path.GetFileName(newName);
string oldCaption = this.Caption;
Transactional.Try(
// Action
() => DocumentManager.UpdateCaption(this.ProjectMgr.Site, newFileName, docData),
// Compensation
() => DocumentManager.UpdateCaption(this.ProjectMgr.Site, oldCaption, docData),
// Continuation
() =>
{
bool caseOnlyChange = NativeMethods.IsSamePath(oldName, newName);
if (!caseOnlyChange)
{
// Check out the project file if necessary.
if (!this.ProjectMgr.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
this.RenameFileNode(oldName, newName);
}
else
{
this.RenameCaseOnlyChange(newFileName);
}
bool extensionWasChanged = (0 != String.Compare(Path.GetExtension(oldName), Path.GetExtension(newName), StringComparison.OrdinalIgnoreCase));
if (extensionWasChanged)
{
// Update the BuildAction
this.ItemNode.ItemName = this.ProjectMgr.DefaultBuildAction(newName);
}
this.ProjectMgr.Tracker.OnItemRenamed(oldName, newName, renameflag);
});
});
}
finally
{
if (docData != IntPtr.Zero)
{
Marshal.Release(docData);
}
sfc.Resume(); // can throw, e.g. when RenameFileNode failed, but file was renamed on disk and now editor cannot find file
}
return true;
}
private FileNode RenameFileNode(string oldFileName, string newFileName)
{
return this.RenameFileNode(oldFileName, newFileName, this.Parent.ID);
}
/// <summary>
/// Renames the file node for a case only change.
/// </summary>
/// <param name="newFileName">The new file name.</param>
private void RenameCaseOnlyChange(string newFileName)
{
//Update the include for this item.
string include = this.ItemNode.Item.UnevaluatedInclude;
if (String.Compare(include, newFileName, StringComparison.OrdinalIgnoreCase) == 0)
{
this.ItemNode.Item.Xml.Include = newFileName;
}
else
{
string includeDir = Path.GetDirectoryName(include);
this.ItemNode.Item.Xml.Include = Path.Combine(includeDir, newFileName);
}
this.ItemNode.RefreshProperties();
this.ReDraw(UIHierarchyElement.Caption);
this.RenameChildNodes(this);
// Refresh the property browser.
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Debug.Assert(shell != null, "Could not get the ui shell from the project");
if (shell == null)
{
throw new InvalidOperationException();
}
shell.RefreshPropertyBrowser(0);
//Select the new node in the hierarchy
IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer);
uiWindow.ExpandItem(this.ProjectMgr.InteropSafeIVsUIHierarchy, this.ID, EXPANDFLAGS.EXPF_SelectItem);
}
/// <summary>
/// Update the ChildNodes after the parent node has been renamed
/// </summary>
/// <param name="newFileNode">The new FileNode created as part of the rename of this node</param>
private void SetNewParentOnChildNodes(FileNode newFileNode)
{
foreach (HierarchyNode childNode in GetChildNodes())
{
childNode.Parent = newFileNode;
}
}
private List<HierarchyNode> GetChildNodes()
{
List<HierarchyNode> childNodes = new List<HierarchyNode>();
HierarchyNode childNode = this.FirstChild;
while (childNode != null)
{
childNodes.Add(childNode);
childNode = childNode.NextSibling;
}
return childNodes;
}
public override __VSPROVISIONALVIEWINGSTATUS ProvisionalViewingStatus =>
IsFileOnDisk(false)
? __VSPROVISIONALVIEWINGSTATUS.PVS_Enabled
: __VSPROVISIONALVIEWINGSTATUS.PVS_Disabled;
}
}
| |
// 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.Arm\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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void AbsUInt16()
{
var test = new SimpleUnaryOpTest__AbsUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.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 (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 SimpleUnaryOpTest__AbsUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.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<Int16> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)-TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__AbsUInt16 testClass)
{
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__AbsUInt16 testClass)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Int16*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Vector128<Int16> _clsVar1;
private Vector128<Int16> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__AbsUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)-TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public SimpleUnaryOpTest__AbsUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)-TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)-TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Abs(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Abs(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Int16*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__AbsUInt16();
var result = AdvSimd.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__AbsUInt16();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Int16*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Int16*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Int16*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _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<Int16> op1, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Int16[] firstOp, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (ushort)Math.Abs(firstOp[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (ushort)Math.Abs(firstOp[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Abs)}<UInt16>(Vector128<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Mail;
using System.Text;
using Xunit;
namespace System.Net.Http.Tests
{
public class HttpRequestHeadersTest
{
private HttpRequestHeaders headers;
public HttpRequestHeadersTest()
{
headers = new HttpRequestHeaders();
}
#region Request headers
[Fact]
public void Accept_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison()
{
// Use uppercase header name to make sure the parser gets retrieved using case-insensitive comparison.
Assert.Throws<FormatException>(() => { headers.Add("AcCePt", "this is invalid"); });
}
[Fact]
public void Accept_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
MediaTypeWithQualityHeaderValue value1 = new MediaTypeWithQualityHeaderValue("text/plain");
value1.CharSet = "utf-8";
value1.Quality = 0.5;
value1.Parameters.Add(new NameValueHeaderValue("custom", "value"));
MediaTypeWithQualityHeaderValue value2 = new MediaTypeWithQualityHeaderValue("text/plain");
value2.CharSet = "iso-8859-1";
value2.Quality = 0.3868;
Assert.Equal(0, headers.Accept.Count);
headers.Accept.Add(value1);
headers.Accept.Add(value2);
Assert.Equal(2, headers.Accept.Count);
Assert.Equal(value1, headers.Accept.ElementAt(0));
Assert.Equal(value2, headers.Accept.ElementAt(1));
headers.Accept.Clear();
Assert.Equal(0, headers.Accept.Count);
}
[Fact]
public void Accept_ReadEmptyProperty_EmptyCollection()
{
HttpRequestMessage request = new HttpRequestMessage();
Assert.Equal(0, request.Headers.Accept.Count);
// Copy to another list
List<MediaTypeWithQualityHeaderValue> accepts = request.Headers.Accept.ToList();
Assert.Equal(0, accepts.Count);
accepts = new List<MediaTypeWithQualityHeaderValue>(request.Headers.Accept);
Assert.Equal(0, accepts.Count);
}
[Fact]
public void Accept_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Accept",
",, , ,,text/plain; charset=iso-8859-1; q=1.0,\r\n */xml; charset=utf-8; q=0.5,,,");
MediaTypeWithQualityHeaderValue value1 = new MediaTypeWithQualityHeaderValue("text/plain");
value1.CharSet = "iso-8859-1";
value1.Quality = 1.0;
MediaTypeWithQualityHeaderValue value2 = new MediaTypeWithQualityHeaderValue("*/xml");
value2.CharSet = "utf-8";
value2.Quality = 0.5;
Assert.Equal(value1, headers.Accept.ElementAt(0));
Assert.Equal(value2, headers.Accept.ElementAt(1));
}
[Fact]
public void Accept_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
// Add a valid media-type with an invalid quality value
headers.TryAddWithoutValidation("Accept", "text/plain; q=a"); // invalid quality
Assert.NotNull(headers.Accept.First());
Assert.Null(headers.Accept.First().Quality);
Assert.Equal("text/plain; q=a", headers.Accept.First().ToString());
headers.Clear();
headers.TryAddWithoutValidation("Accept", "text/plain application/xml"); // no separator
Assert.Equal(0, headers.Accept.Count);
Assert.Equal(1, headers.GetValues("Accept").Count());
Assert.Equal("text/plain application/xml", headers.GetValues("Accept").First());
}
[Fact]
public void AcceptCharset_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.AcceptCharset.Count);
headers.AcceptCharset.Add(new StringWithQualityHeaderValue("iso-8859-5"));
headers.AcceptCharset.Add(new StringWithQualityHeaderValue("unicode-1-1", 0.8));
Assert.Equal(2, headers.AcceptCharset.Count);
Assert.Equal(new StringWithQualityHeaderValue("iso-8859-5"), headers.AcceptCharset.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("unicode-1-1", 0.8), headers.AcceptCharset.ElementAt(1));
headers.AcceptCharset.Clear();
Assert.Equal(0, headers.AcceptCharset.Count);
}
[Fact]
public void AcceptCharset_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Accept-Charset", ", ,,iso-8859-5 , \r\n utf-8 ; q=0.300 ,,,");
Assert.Equal(new StringWithQualityHeaderValue("iso-8859-5"),
headers.AcceptCharset.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("utf-8", 0.3),
headers.AcceptCharset.ElementAt(1));
}
[Fact]
public void AcceptCharset_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Accept-Charset", "iso-8859-5 utf-8"); // no separator
Assert.Equal(0, headers.AcceptCharset.Count);
Assert.Equal(1, headers.GetValues("Accept-Charset").Count());
Assert.Equal("iso-8859-5 utf-8", headers.GetValues("Accept-Charset").First());
headers.Clear();
headers.TryAddWithoutValidation("Accept-Charset", "utf-8; q=1; q=0.3");
Assert.Equal(0, headers.AcceptCharset.Count);
Assert.Equal(1, headers.GetValues("Accept-Charset").Count());
Assert.Equal("utf-8; q=1; q=0.3", headers.GetValues("Accept-Charset").First());
}
[Fact]
public void AcceptCharset_AddMultipleValuesAndGetValueString_AllValuesAddedUsingTheCorrectDelimiter()
{
headers.TryAddWithoutValidation("Accept-Charset", "invalid value");
headers.Add("Accept-Charset", "utf-8");
headers.AcceptCharset.Add(new StringWithQualityHeaderValue("iso-8859-5", 0.5));
foreach (var header in headers.GetHeaderStrings())
{
Assert.Equal("Accept-Charset", header.Key);
Assert.Equal("utf-8, iso-8859-5; q=0.5, invalid value", header.Value);
}
}
[Fact]
public void AcceptEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.AcceptEncoding.Count);
headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("compress", 0.9));
headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
Assert.Equal(2, headers.AcceptEncoding.Count);
Assert.Equal(new StringWithQualityHeaderValue("compress", 0.9), headers.AcceptEncoding.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("gzip"), headers.AcceptEncoding.ElementAt(1));
headers.AcceptEncoding.Clear();
Assert.Equal(0, headers.AcceptEncoding.Count);
}
[Fact]
public void AcceptEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Accept-Encoding", ", gzip; q=1.0, identity; q=0.5, *;q=0, ");
Assert.Equal(new StringWithQualityHeaderValue("gzip", 1),
headers.AcceptEncoding.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("identity", 0.5),
headers.AcceptEncoding.ElementAt(1));
Assert.Equal(new StringWithQualityHeaderValue("*", 0),
headers.AcceptEncoding.ElementAt(2));
headers.AcceptEncoding.Clear();
headers.TryAddWithoutValidation("Accept-Encoding", "");
Assert.Equal(0, headers.AcceptEncoding.Count);
Assert.False(headers.Contains("Accept-Encoding"));
}
[Fact]
public void AcceptEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Accept-Encoding", "gzip deflate"); // no separator
Assert.Equal(0, headers.AcceptEncoding.Count);
Assert.Equal(1, headers.GetValues("Accept-Encoding").Count());
Assert.Equal("gzip deflate", headers.GetValues("Accept-Encoding").First());
headers.Clear();
headers.TryAddWithoutValidation("Accept-Encoding", "compress; q=1; gzip");
Assert.Equal(0, headers.AcceptEncoding.Count);
Assert.Equal(1, headers.GetValues("Accept-Encoding").Count());
Assert.Equal("compress; q=1; gzip", headers.GetValues("Accept-Encoding").First());
}
[Fact]
public void AcceptLanguage_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.AcceptLanguage.Count);
headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("da"));
headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-GB", 0.8));
headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en", 0.7));
Assert.Equal(3, headers.AcceptLanguage.Count);
Assert.Equal(new StringWithQualityHeaderValue("da"), headers.AcceptLanguage.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("en-GB", 0.8), headers.AcceptLanguage.ElementAt(1));
Assert.Equal(new StringWithQualityHeaderValue("en", 0.7), headers.AcceptLanguage.ElementAt(2));
headers.AcceptLanguage.Clear();
Assert.Equal(0, headers.AcceptLanguage.Count);
}
[Fact]
public void AcceptLanguage_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Accept-Language", " , de-DE;q=0.9,de-AT;q=0.5,*;q=0.010 , ");
Assert.Equal(new StringWithQualityHeaderValue("de-DE", 0.9),
headers.AcceptLanguage.ElementAt(0));
Assert.Equal(new StringWithQualityHeaderValue("de-AT", 0.5),
headers.AcceptLanguage.ElementAt(1));
Assert.Equal(new StringWithQualityHeaderValue("*", 0.01),
headers.AcceptLanguage.ElementAt(2));
headers.AcceptLanguage.Clear();
headers.TryAddWithoutValidation("Accept-Language", "");
Assert.Equal(0, headers.AcceptLanguage.Count);
Assert.False(headers.Contains("Accept-Language"));
}
[Fact]
public void AcceptLanguage_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Accept-Language", "de -DE"); // no separator
Assert.Equal(0, headers.AcceptLanguage.Count);
Assert.Equal(1, headers.GetValues("Accept-Language").Count());
Assert.Equal("de -DE", headers.GetValues("Accept-Language").First());
headers.Clear();
headers.TryAddWithoutValidation("Accept-Language", "en; q=0.4,[");
Assert.Equal(0, headers.AcceptLanguage.Count);
Assert.Equal(1, headers.GetValues("Accept-Language").Count());
Assert.Equal("en; q=0.4,[", headers.GetValues("Accept-Language").First());
}
[Fact]
public void Expect_Add100Continue_Success()
{
// use non-default casing to make sure we do case-insensitive comparison.
headers.Expect.Add(new NameValueWithParametersHeaderValue("100-CONTINUE"));
Assert.True(headers.ExpectContinue == true);
Assert.Equal(1, headers.Expect.Count);
}
[Fact]
public void Expect_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Expect.Count);
Assert.Null(headers.ExpectContinue);
headers.Expect.Add(new NameValueWithParametersHeaderValue("custom1"));
headers.Expect.Add(new NameValueWithParametersHeaderValue("custom2"));
headers.ExpectContinue = true;
// Connection collection has 2 values plus '100-Continue'
Assert.Equal(3, headers.Expect.Count);
Assert.Equal(3, headers.GetValues("Expect").Count());
Assert.True(headers.ExpectContinue == true, "ExpectContinue == true");
Assert.Equal(new NameValueWithParametersHeaderValue("custom1"), headers.Expect.ElementAt(0));
Assert.Equal(new NameValueWithParametersHeaderValue("custom2"), headers.Expect.ElementAt(1));
// Remove '100-continue' value from store. But leave other 'Expect' values.
headers.ExpectContinue = false;
Assert.True(headers.ExpectContinue == false, "ExpectContinue == false");
Assert.Equal(2, headers.Expect.Count);
Assert.Equal(new NameValueWithParametersHeaderValue("custom1"), headers.Expect.ElementAt(0));
Assert.Equal(new NameValueWithParametersHeaderValue("custom2"), headers.Expect.ElementAt(1));
headers.ExpectContinue = true;
headers.Expect.Clear();
Assert.True(headers.ExpectContinue == false, "ExpectContinue should be modified by Expect.Clear().");
Assert.Equal(0, headers.Expect.Count);
IEnumerable<string> dummyArray;
Assert.False(headers.TryGetValues("Expect", out dummyArray), "Expect header count after Expect.Clear().");
// Remove '100-continue' value from store. Since there are no other 'Expect' values, remove whole header.
headers.ExpectContinue = false;
Assert.True(headers.ExpectContinue == false, "ExpectContinue == false");
Assert.Equal(0, headers.Expect.Count);
Assert.False(headers.Contains("Expect"));
headers.ExpectContinue = null;
Assert.Null(headers.ExpectContinue);
}
[Fact]
public void Expect_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Expect",
", , 100-continue, name1 = value1, name2; param2=paramValue2, name3=value3; param3 ,");
// Connection collection has 3 values plus '100-continue'
Assert.Equal(4, headers.Expect.Count);
Assert.Equal(4, headers.GetValues("Expect").Count());
Assert.True(headers.ExpectContinue == true, "ExpectContinue expected to be true.");
Assert.Equal(new NameValueWithParametersHeaderValue("100-continue"),
headers.Expect.ElementAt(0));
Assert.Equal(new NameValueWithParametersHeaderValue("name1", "value1"),
headers.Expect.ElementAt(1));
NameValueWithParametersHeaderValue expected2 = new NameValueWithParametersHeaderValue("name2");
expected2.Parameters.Add(new NameValueHeaderValue("param2", "paramValue2"));
Assert.Equal(expected2, headers.Expect.ElementAt(2));
NameValueWithParametersHeaderValue expected3 = new NameValueWithParametersHeaderValue("name3", "value3");
expected3.Parameters.Add(new NameValueHeaderValue("param3"));
Assert.Equal(expected3, headers.Expect.ElementAt(3));
headers.Expect.Clear();
Assert.Null(headers.ExpectContinue);
Assert.Equal(0, headers.Expect.Count);
IEnumerable<string> dummyArray;
Assert.False(headers.TryGetValues("Expect", out dummyArray), "Expect header count after Expect.Clear().");
}
[Fact]
public void Expect_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Expect", "100-continue other"); // no separator
Assert.Equal(0, headers.Expect.Count);
Assert.Equal(1, headers.GetValues("Expect").Count());
Assert.Equal("100-continue other", headers.GetValues("Expect").First());
}
[Fact]
public void Host_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Host);
headers.Host = "host";
Assert.Equal("host", headers.Host);
headers.Host = null;
Assert.Null(headers.Host);
Assert.False(headers.Contains("Host"),
"Header store should not contain a header 'Host' after setting it to null.");
Assert.Throws<FormatException>(() => { headers.Host = "invalid host"; });
}
[Fact]
public void Host_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Host", "host:80");
Assert.Equal("host:80", headers.Host);
}
[Fact]
public void IfMatch_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.IfMatch.Count);
headers.IfMatch.Add(new EntityTagHeaderValue("\"custom1\""));
headers.IfMatch.Add(new EntityTagHeaderValue("\"custom2\"", true));
Assert.Equal(2, headers.IfMatch.Count);
Assert.Equal(2, headers.GetValues("If-Match").Count());
Assert.Equal(new EntityTagHeaderValue("\"custom1\""), headers.IfMatch.ElementAt(0));
Assert.Equal(new EntityTagHeaderValue("\"custom2\"", true), headers.IfMatch.ElementAt(1));
headers.IfMatch.Clear();
Assert.Equal(0, headers.IfMatch.Count);
Assert.False(headers.Contains("If-Match"), "Header store should not contain 'If-Match'");
}
[Fact]
public void IfMatch_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-Match", ", , W/\"tag1\", \"tag2\", W/\"tag3\" ,");
Assert.Equal(3, headers.IfMatch.Count);
Assert.Equal(3, headers.GetValues("If-Match").Count());
Assert.Equal(new EntityTagHeaderValue("\"tag1\"", true), headers.IfMatch.ElementAt(0));
Assert.Equal(new EntityTagHeaderValue("\"tag2\"", false), headers.IfMatch.ElementAt(1));
Assert.Equal(new EntityTagHeaderValue("\"tag3\"", true), headers.IfMatch.ElementAt(2));
headers.IfMatch.Clear();
headers.Add("If-Match", "*");
Assert.Equal(1, headers.IfMatch.Count);
Assert.Same(EntityTagHeaderValue.Any, headers.IfMatch.ElementAt(0));
}
[Fact]
public void IfMatch_UseAddMethodWithInvalidInput_PropertyNotUpdated()
{
headers.TryAddWithoutValidation("If-Match", "W/\"tag1\" \"tag2\""); // no separator
Assert.Equal(0, headers.IfMatch.Count);
Assert.Equal(1, headers.GetValues("If-Match").Count());
}
[Fact]
public void IfNoneMatch_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.IfNoneMatch.Count);
headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"custom1\""));
headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"custom2\"", true));
Assert.Equal(2, headers.IfNoneMatch.Count);
Assert.Equal(2, headers.GetValues("If-None-Match").Count());
Assert.Equal(new EntityTagHeaderValue("\"custom1\""), headers.IfNoneMatch.ElementAt(0));
Assert.Equal(new EntityTagHeaderValue("\"custom2\"", true), headers.IfNoneMatch.ElementAt(1));
headers.IfNoneMatch.Clear();
Assert.Equal(0, headers.IfNoneMatch.Count);
Assert.False(headers.Contains("If-None-Match"), "Header store should not contain 'If-None-Match'");
}
[Fact]
public void IfNoneMatch_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-None-Match", "W/\"tag1\", \"tag2\", W/\"tag3\"");
Assert.Equal(3, headers.IfNoneMatch.Count);
Assert.Equal(3, headers.GetValues("If-None-Match").Count());
Assert.Equal(new EntityTagHeaderValue("\"tag1\"", true), headers.IfNoneMatch.ElementAt(0));
Assert.Equal(new EntityTagHeaderValue("\"tag2\"", false), headers.IfNoneMatch.ElementAt(1));
Assert.Equal(new EntityTagHeaderValue("\"tag3\"", true), headers.IfNoneMatch.ElementAt(2));
headers.IfNoneMatch.Clear();
headers.Add("If-None-Match", "*");
Assert.Equal(1, headers.IfNoneMatch.Count);
Assert.Same(EntityTagHeaderValue.Any, headers.IfNoneMatch.ElementAt(0));
}
[Fact]
public void TE_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
TransferCodingWithQualityHeaderValue value1 = new TransferCodingWithQualityHeaderValue("custom");
value1.Quality = 0.5;
value1.Parameters.Add(new NameValueHeaderValue("name", "value"));
TransferCodingWithQualityHeaderValue value2 = new TransferCodingWithQualityHeaderValue("custom");
value2.Quality = 0.3868;
Assert.Equal(0, headers.TE.Count);
headers.TE.Add(value1);
headers.TE.Add(value2);
Assert.Equal(2, headers.TE.Count);
Assert.Equal(value1, headers.TE.ElementAt(0));
Assert.Equal(value2, headers.TE.ElementAt(1));
headers.TE.Clear();
Assert.Equal(0, headers.TE.Count);
}
[Fact]
public void TE_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("TE",
",custom1; param1=value1; q=1.0,,\r\n custom2; param2=value2; q=0.5 ,");
TransferCodingWithQualityHeaderValue value1 = new TransferCodingWithQualityHeaderValue("custom1");
value1.Parameters.Add(new NameValueHeaderValue("param1", "value1"));
value1.Quality = 1.0;
TransferCodingWithQualityHeaderValue value2 = new TransferCodingWithQualityHeaderValue("custom2");
value2.Parameters.Add(new NameValueHeaderValue("param2", "value2"));
value2.Quality = 0.5;
Assert.Equal(value1, headers.TE.ElementAt(0));
Assert.Equal(value2, headers.TE.ElementAt(1));
headers.Clear();
headers.TryAddWithoutValidation("TE", "");
Assert.False(headers.Contains("TE"), "'TE' header should not be added if it just has empty values.");
}
[Fact]
public void Range_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Range);
RangeHeaderValue value = new RangeHeaderValue(1, 2);
headers.Range = value;
Assert.Equal(value, headers.Range);
headers.Range = null;
Assert.Null(headers.Range);
}
[Fact]
public void Range_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Range", "custom= , ,1-2, -4 , ");
RangeHeaderValue value = new RangeHeaderValue();
value.Unit = "custom";
value.Ranges.Add(new RangeItemHeaderValue(1, 2));
value.Ranges.Add(new RangeItemHeaderValue(null, 4));
Assert.Equal(value, headers.Range);
}
[Fact]
public void Authorization_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Authorization);
headers.Authorization = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
Assert.Equal(new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="), headers.Authorization);
headers.Authorization = null;
Assert.Null(headers.Authorization);
Assert.False(headers.Contains("Authorization"),
"Header store should not contain a header 'Authorization' after setting it to null.");
}
[Fact]
public void Authorization_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Authorization", "NTLM blob");
Assert.Equal(new AuthenticationHeaderValue("NTLM", "blob"), headers.Authorization);
}
[Fact]
public void ProxyAuthorization_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.ProxyAuthorization);
headers.ProxyAuthorization = new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
Assert.Equal(new AuthenticationHeaderValue("Basic", "QWxhZGRpbjpvcGVuIHNlc2FtZQ=="),
headers.ProxyAuthorization);
headers.ProxyAuthorization = null;
Assert.Null(headers.ProxyAuthorization);
Assert.False(headers.Contains("ProxyAuthorization"),
"Header store should not contain a header 'ProxyAuthorization' after setting it to null.");
}
[Fact]
public void ProxyAuthorization_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Proxy-Authorization", "NTLM blob");
Assert.Equal(new AuthenticationHeaderValue("NTLM", "blob"), headers.ProxyAuthorization);
}
[Fact]
public void UserAgent_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.UserAgent.Count);
headers.UserAgent.Add(new ProductInfoHeaderValue("(custom1)"));
headers.UserAgent.Add(new ProductInfoHeaderValue("custom2", "1.1"));
Assert.Equal(2, headers.UserAgent.Count);
Assert.Equal(2, headers.GetValues("User-Agent").Count());
Assert.Equal(new ProductInfoHeaderValue("(custom1)"), headers.UserAgent.ElementAt(0));
Assert.Equal(new ProductInfoHeaderValue("custom2", "1.1"), headers.UserAgent.ElementAt(1));
headers.UserAgent.Clear();
Assert.Equal(0, headers.UserAgent.Count);
Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after calling Clear().");
headers.UserAgent.Add(new ProductInfoHeaderValue("(comment)"));
headers.UserAgent.Remove(new ProductInfoHeaderValue("(comment)"));
Assert.Equal(0, headers.UserAgent.Count);
Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after removing last value.");
}
[Fact]
public void UserAgent_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("User-Agent", "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.6.30 Version/10.63");
Assert.Equal(4, headers.UserAgent.Count);
Assert.Equal(4, headers.GetValues("User-Agent").Count());
Assert.Equal(new ProductInfoHeaderValue("Opera", "9.80"), headers.UserAgent.ElementAt(0));
Assert.Equal(new ProductInfoHeaderValue("(Windows NT 6.1; U; en)"), headers.UserAgent.ElementAt(1));
Assert.Equal(new ProductInfoHeaderValue("Presto", "2.6.30"), headers.UserAgent.ElementAt(2));
Assert.Equal(new ProductInfoHeaderValue("Version", "10.63"), headers.UserAgent.ElementAt(3));
headers.UserAgent.Clear();
Assert.Equal(0, headers.UserAgent.Count);
Assert.False(headers.Contains("User-Agent"), "User-Agent header should be removed after calling Clear().");
}
[Fact]
public void UserAgent_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("User-Agent", "custom\u4F1A");
Assert.Null(headers.GetParsedValues("User-Agent"));
Assert.Equal(1, headers.GetValues("User-Agent").Count());
Assert.Equal("custom\u4F1A", headers.GetValues("User-Agent").First());
headers.Clear();
// Note that "User-Agent" uses whitespaces as separators, so the following is an invalid value
headers.TryAddWithoutValidation("User-Agent", "custom1, custom2");
Assert.Null(headers.GetParsedValues("User-Agent"));
Assert.Equal(1, headers.GetValues("User-Agent").Count());
Assert.Equal("custom1, custom2", headers.GetValues("User-Agent").First());
headers.Clear();
headers.TryAddWithoutValidation("User-Agent", "custom1, ");
Assert.Null(headers.GetParsedValues("User-Agent"));
Assert.Equal(1, headers.GetValues("User-Agent").Count());
Assert.Equal("custom1, ", headers.GetValues("User-Agent").First());
headers.Clear();
headers.TryAddWithoutValidation("User-Agent", ",custom1");
Assert.Null(headers.GetParsedValues("User-Agent"));
Assert.Equal(1, headers.GetValues("User-Agent").Count());
Assert.Equal(",custom1", headers.GetValues("User-Agent").First());
}
[Fact]
public void UserAgent_AddMultipleValuesAndGetValueString_AllValuesAddedUsingTheCorrectDelimiter()
{
headers.TryAddWithoutValidation("User-Agent", "custom\u4F1A");
headers.Add("User-Agent", "custom2/1.1");
headers.UserAgent.Add(new ProductInfoHeaderValue("(comment)"));
foreach (var header in headers.GetHeaderStrings())
{
Assert.Equal("User-Agent", header.Key);
Assert.Equal("custom2/1.1 (comment) custom\u4F1A", header.Value);
}
}
[Fact]
public void IfRange_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.IfRange);
headers.IfRange = new RangeConditionHeaderValue("\"x\"");
Assert.Equal(1, headers.GetValues("If-Range").Count());
Assert.Equal(new RangeConditionHeaderValue("\"x\""), headers.IfRange);
headers.IfRange = null;
Assert.Null(headers.IfRange);
Assert.False(headers.Contains("If-Range"), "If-Range header should be removed after calling Clear().");
}
[Fact]
public void IfRange_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-Range", " W/\"tag\" ");
Assert.Equal(new RangeConditionHeaderValue(new EntityTagHeaderValue("\"tag\"", true)),
headers.IfRange);
Assert.Equal(1, headers.GetValues("If-Range").Count());
headers.IfRange = null;
Assert.Null(headers.IfRange);
Assert.False(headers.Contains("If-Range"), "If-Range header should be removed after calling Clear().");
}
[Fact]
public void IfRange_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("If-Range", "\"tag\"\u4F1A");
Assert.Null(headers.GetParsedValues("If-Range"));
Assert.Equal(1, headers.GetValues("If-Range").Count());
Assert.Equal("\"tag\"\u4F1A", headers.GetValues("If-Range").First());
headers.Clear();
headers.TryAddWithoutValidation("If-Range", " \"tag\", ");
Assert.Null(headers.GetParsedValues("If-Range"));
Assert.Equal(1, headers.GetValues("If-Range").Count());
Assert.Equal(" \"tag\", ", headers.GetValues("If-Range").First());
}
[Fact]
public void From_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.From);
headers.From = "[email protected]";
Assert.Equal("[email protected]", headers.From);
headers.From = null;
Assert.Null(headers.From);
Assert.False(headers.Contains("From"),
"Header store should not contain a header 'From' after setting it to null.");
Assert.Throws<FormatException>(() => { headers.From = " "; });
Assert.Throws<FormatException>(() => { headers.From = "invalid email address"; });
}
[Fact]
public void From_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("From", " \"My Name\" [email protected] ");
Assert.Equal("\"My Name\" [email protected] ", headers.From);
// The following encoded string represents the character sequence "\u4F1A\u5458\u670D\u52A1".
headers.Clear();
headers.TryAddWithoutValidation("From", "=?utf-8?Q?=E4=BC=9A=E5=91=98=E6=9C=8D=E5=8A=A1?= <[email protected]>");
Assert.Equal("=?utf-8?Q?=E4=BC=9A=E5=91=98=E6=9C=8D=E5=8A=A1?= <[email protected]>", headers.From);
}
[Fact]
public void From_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("From", " [email protected] ,");
Assert.Null(headers.GetParsedValues("From"));
Assert.Equal(1, headers.GetValues("From").Count());
Assert.Equal(" [email protected] ,", headers.GetValues("From").First());
headers.Clear();
headers.TryAddWithoutValidation("From", "info@");
Assert.Null(headers.GetParsedValues("From"));
Assert.Equal(1, headers.GetValues("From").Count());
Assert.Equal("info@", headers.GetValues("From").First());
}
[Fact]
public void IfModifiedSince_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.IfModifiedSince);
DateTimeOffset expected = DateTimeOffset.Now;
headers.IfModifiedSince = expected;
Assert.Equal(expected, headers.IfModifiedSince);
headers.IfModifiedSince = null;
Assert.Null(headers.IfModifiedSince);
Assert.False(headers.Contains("If-Modified-Since"),
"Header store should not contain a header 'IfModifiedSince' after setting it to null.");
}
[Fact]
public void IfModifiedSince_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfModifiedSince);
headers.Clear();
headers.TryAddWithoutValidation("If-Modified-Since", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfModifiedSince);
}
[Fact]
public void IfModifiedSince_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(headers.GetParsedValues("If-Modified-Since"));
Assert.Equal(1, headers.GetValues("If-Modified-Since").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("If-Modified-Since").First());
headers.Clear();
headers.TryAddWithoutValidation("If-Modified-Since", " Sun, 06 Nov ");
Assert.Null(headers.GetParsedValues("If-Modified-Since"));
Assert.Equal(1, headers.GetValues("If-Modified-Since").Count());
Assert.Equal(" Sun, 06 Nov ", headers.GetValues("If-Modified-Since").First());
}
[Fact]
public void IfUnmodifiedSince_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.IfUnmodifiedSince);
DateTimeOffset expected = DateTimeOffset.Now;
headers.IfUnmodifiedSince = expected;
Assert.Equal(expected, headers.IfUnmodifiedSince);
headers.IfUnmodifiedSince = null;
Assert.Null(headers.IfUnmodifiedSince);
Assert.False(headers.Contains("If-Unmodified-Since"),
"Header store should not contain a header 'IfUnmodifiedSince' after setting it to null.");
}
[Fact]
public void IfUnmodifiedSince_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfUnmodifiedSince);
headers.Clear();
headers.TryAddWithoutValidation("If-Unmodified-Since", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.IfUnmodifiedSince);
}
[Fact]
public void IfUnmodifiedSince_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(headers.GetParsedValues("If-Unmodified-Since"));
Assert.Equal(1, headers.GetValues("If-Unmodified-Since").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("If-Unmodified-Since").First());
headers.Clear();
headers.TryAddWithoutValidation("If-Unmodified-Since", " Sun, 06 Nov ");
Assert.Null(headers.GetParsedValues("If-Unmodified-Since"));
Assert.Equal(1, headers.GetValues("If-Unmodified-Since").Count());
Assert.Equal(" Sun, 06 Nov ", headers.GetValues("If-Unmodified-Since").First());
}
[Fact]
public void Referrer_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Referrer);
Uri expected = new Uri("http://example.com/path/");
headers.Referrer = expected;
Assert.Equal(expected, headers.Referrer);
headers.Referrer = null;
Assert.Null(headers.Referrer);
Assert.False(headers.Contains("Referer"),
"Header store should not contain a header 'Referrer' after setting it to null.");
}
[Fact]
public void Referrer_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Referer", " http://www.example.com/path/?q=v ");
Assert.Equal(new Uri("http://www.example.com/path/?q=v"), headers.Referrer);
headers.Clear();
headers.TryAddWithoutValidation("Referer", "/relative/uri/");
Assert.Equal(new Uri("/relative/uri/", UriKind.Relative), headers.Referrer);
}
[Fact]
public void Referrer_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Referer", " http://example.com http://other");
Assert.Null(headers.GetParsedValues("Referer"));
Assert.Equal(1, headers.GetValues("Referer").Count());
Assert.Equal(" http://example.com http://other", headers.GetValues("Referer").First());
headers.Clear();
headers.TryAddWithoutValidation("Referer", "http://host /other");
Assert.Null(headers.GetParsedValues("Referer"));
Assert.Equal(1, headers.GetValues("Referer").Count());
Assert.Equal("http://host /other", headers.GetValues("Referer").First());
}
[Fact]
public void MaxForwards_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.MaxForwards);
headers.MaxForwards = 15;
Assert.Equal(15, headers.MaxForwards);
headers.MaxForwards = null;
Assert.Null(headers.MaxForwards);
Assert.False(headers.Contains("Max-Forwards"),
"Header store should not contain a header 'MaxForwards' after setting it to null.");
// Make sure the header gets serialized correctly
headers.MaxForwards = 12345;
Assert.Equal("12345", headers.GetValues("Max-Forwards").First());
}
[Fact]
public void MaxForwards_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Max-Forwards", " 00123 ");
Assert.Equal(123, headers.MaxForwards);
headers.Clear();
headers.TryAddWithoutValidation("Max-Forwards", "0");
Assert.Equal(0, headers.MaxForwards);
}
[Fact]
public void MaxForwards_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Max-Forwards", "15,");
Assert.Null(headers.GetParsedValues("Max-Forwards"));
Assert.Equal(1, headers.GetValues("Max-Forwards").Count());
Assert.Equal("15,", headers.GetValues("Max-Forwards").First());
headers.Clear();
headers.TryAddWithoutValidation("Max-Forwards", "1.0");
Assert.Null(headers.GetParsedValues("Max-Forwards"));
Assert.Equal(1, headers.GetValues("Max-Forwards").Count());
Assert.Equal("1.0", headers.GetValues("Max-Forwards").First());
}
[Fact]
public void AddHeaders_SpecialHeaderValuesOnSourceNotOnDestination_Copied()
{
// Positive
HttpRequestHeaders source = new HttpRequestHeaders();
source.ExpectContinue = true;
source.TransferEncodingChunked = true;
source.ConnectionClose = true;
HttpRequestHeaders destination = new HttpRequestHeaders();
Assert.Null(destination.ExpectContinue);
Assert.Null(destination.TransferEncodingChunked);
Assert.Null(destination.ConnectionClose);
destination.AddHeaders(source);
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.True(destination.ExpectContinue.Value);
Assert.True(destination.TransferEncodingChunked.Value);
Assert.True(destination.ConnectionClose.Value);
// Negitive
source = new HttpRequestHeaders();
source.ExpectContinue = false;
source.TransferEncodingChunked = false;
source.ConnectionClose = false;
destination = new HttpRequestHeaders();
Assert.Null(destination.ExpectContinue);
Assert.Null(destination.TransferEncodingChunked);
Assert.Null(destination.ConnectionClose);
destination.AddHeaders(source);
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.False(destination.ExpectContinue.Value);
Assert.False(destination.TransferEncodingChunked.Value);
Assert.False(destination.ConnectionClose.Value);
}
[Fact]
public void AddHeaders_SpecialHeaderValuesOnDestinationNotOnSource_NotCopied()
{
// Positive
HttpRequestHeaders destination = new HttpRequestHeaders();
destination.ExpectContinue = true;
destination.TransferEncodingChunked = true;
destination.ConnectionClose = true;
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.True(destination.ExpectContinue.Value);
Assert.True(destination.TransferEncodingChunked.Value);
Assert.True(destination.ConnectionClose.Value);
HttpRequestHeaders source = new HttpRequestHeaders();
Assert.Null(source.ExpectContinue);
Assert.Null(source.TransferEncodingChunked);
Assert.Null(source.ConnectionClose);
destination.AddHeaders(source);
Assert.Null(source.ExpectContinue);
Assert.Null(source.TransferEncodingChunked);
Assert.Null(source.ConnectionClose);
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.True(destination.ExpectContinue.Value);
Assert.True(destination.TransferEncodingChunked.Value);
Assert.True(destination.ConnectionClose.Value);
// Negitive
destination = new HttpRequestHeaders();
destination.ExpectContinue = false;
destination.TransferEncodingChunked = false;
destination.ConnectionClose = false;
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.False(destination.ExpectContinue.Value);
Assert.False(destination.TransferEncodingChunked.Value);
Assert.False(destination.ConnectionClose.Value);
source = new HttpRequestHeaders();
Assert.Null(source.ExpectContinue);
Assert.Null(source.TransferEncodingChunked);
Assert.Null(source.ConnectionClose);
destination.AddHeaders(source);
Assert.Null(source.ExpectContinue);
Assert.Null(source.TransferEncodingChunked);
Assert.Null(source.ConnectionClose);
Assert.NotNull(destination.ExpectContinue);
Assert.NotNull(destination.TransferEncodingChunked);
Assert.NotNull(destination.ConnectionClose);
Assert.False(destination.ExpectContinue.Value);
Assert.False(destination.TransferEncodingChunked.Value);
Assert.False(destination.ConnectionClose.Value);
}
#endregion
#region General headers
[Fact]
public void Connection_AddClose_Success()
{
headers.Connection.Add("CLOSE"); // use non-default casing to make sure we do case-insensitive comparison.
Assert.True(headers.ConnectionClose == true);
Assert.Equal(1, headers.Connection.Count);
}
[Fact]
public void Connection_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Connection.Count);
Assert.Null(headers.ConnectionClose);
headers.Connection.Add("custom1");
headers.Connection.Add("custom2");
headers.ConnectionClose = true;
// Connection collection has 2 values plus 'close'
Assert.Equal(3, headers.Connection.Count);
Assert.Equal(3, headers.GetValues("Connection").Count());
Assert.True(headers.ConnectionClose == true, "ConnectionClose");
Assert.Equal("custom1", headers.Connection.ElementAt(0));
Assert.Equal("custom2", headers.Connection.ElementAt(1));
// Remove 'close' value from store. But leave other 'Connection' values.
headers.ConnectionClose = false;
Assert.True(headers.ConnectionClose == false, "ConnectionClose == false");
Assert.Equal(2, headers.Connection.Count);
Assert.Equal("custom1", headers.Connection.ElementAt(0));
Assert.Equal("custom2", headers.Connection.ElementAt(1));
headers.ConnectionClose = true;
headers.Connection.Clear();
Assert.True(headers.ConnectionClose == false,
"ConnectionClose should be modified by Connection.Clear().");
Assert.Equal(0, headers.Connection.Count);
IEnumerable<string> dummyArray;
Assert.False(headers.TryGetValues("Connection", out dummyArray),
"Connection header count after Connection.Clear().");
// Remove 'close' value from store. Since there are no other 'Connection' values, remove whole header.
headers.ConnectionClose = false;
Assert.True(headers.ConnectionClose == false, "ConnectionClose == false");
Assert.Equal(0, headers.Connection.Count);
Assert.False(headers.Contains("Connection"));
headers.ConnectionClose = null;
Assert.Null(headers.ConnectionClose);
}
[Fact]
public void Connection_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Connection", "custom1, close, custom2, custom3");
// Connection collection has 3 values plus 'close'
Assert.Equal(4, headers.Connection.Count);
Assert.Equal(4, headers.GetValues("Connection").Count());
Assert.True(headers.ConnectionClose == true);
Assert.Equal("custom1", headers.Connection.ElementAt(0));
Assert.Equal("close", headers.Connection.ElementAt(1));
Assert.Equal("custom2", headers.Connection.ElementAt(2));
Assert.Equal("custom3", headers.Connection.ElementAt(3));
headers.Connection.Clear();
Assert.Null(headers.ConnectionClose);
Assert.Equal(0, headers.Connection.Count);
IEnumerable<string> dummyArray;
Assert.False(headers.TryGetValues("Connection", out dummyArray),
"Connection header count after Connection.Clear().");
}
[Fact]
public void Connection_AddInvalidValue_Throw()
{
Assert.Throws<FormatException>(() => { headers.Connection.Add("this is invalid"); });
}
[Fact]
public void TransferEncoding_AddChunked_Success()
{
// use non-default casing to make sure we do case-insensitive comparison.
headers.TransferEncoding.Add(new TransferCodingHeaderValue("CHUNKED"));
Assert.True(headers.TransferEncodingChunked == true);
Assert.Equal(1, headers.TransferEncoding.Count);
}
[Fact]
public void TransferEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.Null(headers.TransferEncodingChunked);
headers.TransferEncoding.Add(new TransferCodingHeaderValue("custom1"));
headers.TransferEncoding.Add(new TransferCodingHeaderValue("custom2"));
headers.TransferEncodingChunked = true;
// Connection collection has 2 values plus 'chunked'
Assert.Equal(3, headers.TransferEncoding.Count);
Assert.Equal(3, headers.GetValues("Transfer-Encoding").Count());
Assert.Equal(true, headers.TransferEncodingChunked);
Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0));
Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1));
// Remove 'chunked' value from store. But leave other 'Transfer-Encoding' values. Note that according to
// the RFC this is not valid, since 'chunked' must always be present. However this check is done
// in the transport handler since the user can add invalid header values anyways.
headers.TransferEncodingChunked = false;
Assert.True(headers.TransferEncodingChunked == false, "TransferEncodingChunked == false");
Assert.Equal(2, headers.TransferEncoding.Count);
Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0));
Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1));
headers.TransferEncodingChunked = true;
headers.TransferEncoding.Clear();
Assert.True(headers.TransferEncodingChunked == false,
"TransferEncodingChunked should be modified by TransferEncoding.Clear().");
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.Contains("Transfer-Encoding"));
// Remove 'chunked' value from store. Since there are no other 'Transfer-Encoding' values, remove whole
// header.
headers.TransferEncodingChunked = false;
Assert.True(headers.TransferEncodingChunked == false, "TransferEncodingChunked == false");
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.Contains("Transfer-Encoding"));
headers.TransferEncodingChunked = null;
Assert.Null(headers.TransferEncodingChunked);
}
[Fact]
public void TransferEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Transfer-Encoding", " , custom1, , custom2, custom3, chunked ,");
// Connection collection has 3 values plus 'chunked'
Assert.Equal(4, headers.TransferEncoding.Count);
Assert.Equal(4, headers.GetValues("Transfer-Encoding").Count());
Assert.True(headers.TransferEncodingChunked == true, "TransferEncodingChunked expected to be true.");
Assert.Equal(new TransferCodingHeaderValue("custom1"), headers.TransferEncoding.ElementAt(0));
Assert.Equal(new TransferCodingHeaderValue("custom2"), headers.TransferEncoding.ElementAt(1));
Assert.Equal(new TransferCodingHeaderValue("custom3"), headers.TransferEncoding.ElementAt(2));
headers.TransferEncoding.Clear();
Assert.Null(headers.TransferEncodingChunked);
Assert.Equal(0, headers.TransferEncoding.Count);
Assert.False(headers.Contains("Transfer-Encoding"),
"Transfer-Encoding header after TransferEncoding.Clear().");
}
[Fact]
public void TransferEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Transfer-Encoding", "custom\u4F1A");
Assert.Null(headers.GetParsedValues("Transfer-Encoding"));
Assert.Equal(1, headers.GetValues("Transfer-Encoding").Count());
Assert.Equal("custom\u4F1A", headers.GetValues("Transfer-Encoding").First());
headers.Clear();
headers.TryAddWithoutValidation("Transfer-Encoding", "custom1 custom2");
Assert.Null(headers.GetParsedValues("Transfer-Encoding"));
Assert.Equal(1, headers.GetValues("Transfer-Encoding").Count());
Assert.Equal("custom1 custom2", headers.GetValues("Transfer-Encoding").First());
headers.Clear();
headers.TryAddWithoutValidation("Transfer-Encoding", "");
Assert.False(headers.Contains("Transfer-Encoding"), "'Transfer-Encoding' header should not be added if it just has empty values.");
}
[Fact]
public void Upgrade_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Upgrade.Count);
headers.Upgrade.Add(new ProductHeaderValue("custom1"));
headers.Upgrade.Add(new ProductHeaderValue("custom2", "1.1"));
Assert.Equal(2, headers.Upgrade.Count);
Assert.Equal(2, headers.GetValues("Upgrade").Count());
Assert.Equal(new ProductHeaderValue("custom1"), headers.Upgrade.ElementAt(0));
Assert.Equal(new ProductHeaderValue("custom2", "1.1"), headers.Upgrade.ElementAt(1));
headers.Upgrade.Clear();
Assert.Equal(0, headers.Upgrade.Count);
Assert.False(headers.Contains("Upgrade"), "Upgrade header should be removed after calling Clear().");
}
[Fact]
public void Upgrade_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Upgrade", " , custom1 / 1.0, , custom2, custom3/2.0,");
Assert.Equal(3, headers.Upgrade.Count);
Assert.Equal(3, headers.GetValues("Upgrade").Count());
Assert.Equal(new ProductHeaderValue("custom1", "1.0"), headers.Upgrade.ElementAt(0));
Assert.Equal(new ProductHeaderValue("custom2"), headers.Upgrade.ElementAt(1));
Assert.Equal(new ProductHeaderValue("custom3", "2.0"), headers.Upgrade.ElementAt(2));
headers.Upgrade.Clear();
Assert.Equal(0, headers.Upgrade.Count);
Assert.False(headers.Contains("Upgrade"), "Upgrade header should be removed after calling Clear().");
}
[Fact]
public void Upgrade_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Upgrade", "custom\u4F1A");
Assert.Null(headers.GetParsedValues("Upgrade"));
Assert.Equal(1, headers.GetValues("Upgrade").Count());
Assert.Equal("custom\u4F1A", headers.GetValues("Upgrade").First());
headers.Clear();
headers.TryAddWithoutValidation("Upgrade", "custom1 custom2");
Assert.Null(headers.GetParsedValues("Upgrade"));
Assert.Equal(1, headers.GetValues("Upgrade").Count());
Assert.Equal("custom1 custom2", headers.GetValues("Upgrade").First());
}
[Fact]
public void Date_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.Date);
DateTimeOffset expected = DateTimeOffset.Now;
headers.Date = expected;
Assert.Equal(expected, headers.Date);
headers.Date = null;
Assert.Null(headers.Date);
Assert.False(headers.Contains("Date"),
"Header store should not contain a header 'Date' after setting it to null.");
// Make sure the header gets serialized correctly
headers.Date = (new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero));
Assert.Equal("Sun, 06 Nov 1994 08:49:37 GMT", headers.GetValues("Date").First());
}
[Fact]
public void Date_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Date", " Sun, 06 Nov 1994 08:49:37 GMT ");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.Date);
headers.Clear();
headers.TryAddWithoutValidation("Date", "Sun, 06 Nov 1994 08:49:37 GMT");
Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), headers.Date);
}
[Fact]
public void Date_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Date", " Sun, 06 Nov 1994 08:49:37 GMT ,");
Assert.Null(headers.GetParsedValues("Date"));
Assert.Equal(1, headers.GetValues("Date").Count());
Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", headers.GetValues("Date").First());
headers.Clear();
headers.TryAddWithoutValidation("Date", " Sun, 06 Nov ");
Assert.Null(headers.GetParsedValues("Date"));
Assert.Equal(1, headers.GetValues("Date").Count());
Assert.Equal(" Sun, 06 Nov ", headers.GetValues("Date").First());
}
[Fact]
public void Via_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Via.Count);
headers.Via.Add(new ViaHeaderValue("x11", "host"));
headers.Via.Add(new ViaHeaderValue("1.1", "example.com:8080", "HTTP", "(comment)"));
Assert.Equal(2, headers.Via.Count);
Assert.Equal(new ViaHeaderValue("x11", "host"), headers.Via.ElementAt(0));
Assert.Equal(new ViaHeaderValue("1.1", "example.com:8080", "HTTP", "(comment)"),
headers.Via.ElementAt(1));
headers.Via.Clear();
Assert.Equal(0, headers.Via.Count);
}
[Fact]
public void Via_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Via", ", 1.1 host, WS/1.0 [::1],X/11 192.168.0.1 (c(comment)) ");
Assert.Equal(new ViaHeaderValue("1.1", "host"), headers.Via.ElementAt(0));
Assert.Equal(new ViaHeaderValue("1.0", "[::1]", "WS"), headers.Via.ElementAt(1));
Assert.Equal(new ViaHeaderValue("11", "192.168.0.1", "X", "(c(comment))"), headers.Via.ElementAt(2));
headers.Via.Clear();
headers.TryAddWithoutValidation("Via", "");
Assert.Equal(0, headers.Via.Count);
Assert.False(headers.Contains("Via"));
}
[Fact]
public void Via_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Via", "1.1 host1 1.1 host2"); // no separator
Assert.Equal(0, headers.Via.Count);
Assert.Equal(1, headers.GetValues("Via").Count());
Assert.Equal("1.1 host1 1.1 host2", headers.GetValues("Via").First());
headers.Clear();
headers.TryAddWithoutValidation("Via", "X/11 host/1");
Assert.Equal(0, headers.Via.Count);
Assert.Equal(1, headers.GetValues("Via").Count());
Assert.Equal("X/11 host/1", headers.GetValues("Via").First());
}
[Fact]
public void Warning_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Warning.Count);
headers.Warning.Add(new WarningHeaderValue(199, "microsoft.com", "\"Miscellaneous warning\""));
headers.Warning.Add(new WarningHeaderValue(113, "example.com", "\"Heuristic expiration\""));
Assert.Equal(2, headers.Warning.Count);
Assert.Equal(new WarningHeaderValue(199, "microsoft.com", "\"Miscellaneous warning\""),
headers.Warning.ElementAt(0));
Assert.Equal(new WarningHeaderValue(113, "example.com", "\"Heuristic expiration\""),
headers.Warning.ElementAt(1));
headers.Warning.Clear();
Assert.Equal(0, headers.Warning.Count);
}
[Fact]
public void Warning_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Warning",
"112 example.com \"Disconnected operation\", 111 example.org \"Revalidation failed\"");
Assert.Equal(new WarningHeaderValue(112, "example.com", "\"Disconnected operation\""),
headers.Warning.ElementAt(0));
Assert.Equal(new WarningHeaderValue(111, "example.org", "\"Revalidation failed\""),
headers.Warning.ElementAt(1));
headers.Warning.Clear();
headers.TryAddWithoutValidation("Warning", "");
Assert.Equal(0, headers.Warning.Count);
Assert.False(headers.Contains("Warning"));
}
[Fact]
public void Warning_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Warning", "123 host1 \"\" 456 host2 \"\""); // no separator
Assert.Equal(0, headers.Warning.Count);
Assert.Equal(1, headers.GetValues("Warning").Count());
Assert.Equal("123 host1 \"\" 456 host2 \"\"", headers.GetValues("Warning").First());
headers.Clear();
headers.TryAddWithoutValidation("Warning", "123 host1\"text\"");
Assert.Equal(0, headers.Warning.Count);
Assert.Equal(1, headers.GetValues("Warning").Count());
Assert.Equal("123 host1\"text\"", headers.GetValues("Warning").First());
}
[Fact]
public void CacheControl_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Null(headers.CacheControl);
CacheControlHeaderValue value = new CacheControlHeaderValue();
value.NoCache = true;
value.NoCacheHeaders.Add("token1");
value.NoCacheHeaders.Add("token2");
value.MustRevalidate = true;
value.SharedMaxAge = new TimeSpan(1, 2, 3);
headers.CacheControl = value;
Assert.Equal(value, headers.CacheControl);
headers.CacheControl = null;
Assert.Null(headers.CacheControl);
Assert.False(headers.Contains("Cache-Control"),
"Header store should not contain a header 'Cache-Control' after setting it to null.");
}
[Fact]
public void CacheControl_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Cache-Control", "no-cache=\"token1, token2\", must-revalidate, max-age=3");
headers.Add("Cache-Control", "");
headers.Add("Cache-Control", "public, s-maxage=15");
headers.TryAddWithoutValidation("Cache-Control", "");
CacheControlHeaderValue value = new CacheControlHeaderValue();
value.NoCache = true;
value.NoCacheHeaders.Add("token1");
value.NoCacheHeaders.Add("token2");
value.MustRevalidate = true;
value.MaxAge = new TimeSpan(0, 0, 3);
value.Public = true;
value.SharedMaxAge = new TimeSpan(0, 0, 15);
Assert.Equal(value, headers.CacheControl);
}
[Fact]
public void Trailer_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Trailer.Count);
headers.Trailer.Add("custom1");
headers.Trailer.Add("custom2");
Assert.Equal(2, headers.Trailer.Count);
Assert.Equal(2, headers.GetValues("Trailer").Count());
Assert.Equal("custom1", headers.Trailer.ElementAt(0));
Assert.Equal("custom2", headers.Trailer.ElementAt(1));
headers.Trailer.Clear();
Assert.Equal(0, headers.Trailer.Count);
Assert.False(headers.Contains("Trailer"),
"There should be no Trailer header after calling Clear().");
}
[Fact]
public void Trailer_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Trailer", ",custom1, custom2, custom3,");
Assert.Equal(3, headers.Trailer.Count);
Assert.Equal(3, headers.GetValues("Trailer").Count());
Assert.Equal("custom1", headers.Trailer.ElementAt(0));
Assert.Equal("custom2", headers.Trailer.ElementAt(1));
Assert.Equal("custom3", headers.Trailer.ElementAt(2));
headers.Trailer.Clear();
Assert.Equal(0, headers.Trailer.Count);
Assert.False(headers.Contains("Trailer"),
"There should be no Trailer header after calling Clear().");
}
[Fact]
public void Trailer_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Trailer", "custom1 custom2"); // no separator
Assert.Equal(0, headers.Trailer.Count);
Assert.Equal(1, headers.GetValues("Trailer").Count());
Assert.Equal("custom1 custom2", headers.GetValues("Trailer").First());
}
[Fact]
public void Pragma_ReadAndWriteProperty_ValueMatchesPriorSetValue()
{
Assert.Equal(0, headers.Pragma.Count);
headers.Pragma.Add(new NameValueHeaderValue("custom1", "value1"));
headers.Pragma.Add(new NameValueHeaderValue("custom2"));
Assert.Equal(2, headers.Pragma.Count);
Assert.Equal(2, headers.GetValues("Pragma").Count());
Assert.Equal(new NameValueHeaderValue("custom1", "value1"), headers.Pragma.ElementAt(0));
Assert.Equal(new NameValueHeaderValue("custom2"), headers.Pragma.ElementAt(1));
headers.Pragma.Clear();
Assert.Equal(0, headers.Pragma.Count);
Assert.False(headers.Contains("Pragma"),
"There should be no Pragma header after calling Clear().");
}
[Fact]
public void Pragma_UseAddMethod_AddedValueCanBeRetrievedUsingProperty()
{
headers.TryAddWithoutValidation("Pragma", ",custom1=value1, custom2, custom3=value3,");
Assert.Equal(3, headers.Pragma.Count);
Assert.Equal(3, headers.GetValues("Pragma").Count());
Assert.Equal(new NameValueHeaderValue("custom1", "value1"), headers.Pragma.ElementAt(0));
Assert.Equal(new NameValueHeaderValue("custom2"), headers.Pragma.ElementAt(1));
Assert.Equal(new NameValueHeaderValue("custom3", "value3"), headers.Pragma.ElementAt(2));
headers.Pragma.Clear();
Assert.Equal(0, headers.Pragma.Count);
Assert.False(headers.Contains("Pragma"),
"There should be no Pragma header after calling Clear().");
}
[Fact]
public void Pragma_UseAddMethodWithInvalidValue_InvalidValueRecognized()
{
headers.TryAddWithoutValidation("Pragma", "custom1, custom2=");
Assert.Equal(0, headers.Pragma.Count());
Assert.Equal(1, headers.GetValues("Pragma").Count());
Assert.Equal("custom1, custom2=", headers.GetValues("Pragma").First());
}
#endregion
[Fact]
public void ToString_SeveralRequestHeaders_Success()
{
HttpRequestMessage request = new HttpRequestMessage();
string expected = string.Empty;
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/xml"));
expected += HttpKnownHeaderNames.Accept + ": application/xml, */xml\r\n";
request.Headers.Authorization = new AuthenticationHeaderValue("Basic");
expected += HttpKnownHeaderNames.Authorization + ": Basic\r\n";
request.Headers.ExpectContinue = true;
expected += HttpKnownHeaderNames.Expect + ": 100-continue\r\n";
request.Headers.TransferEncodingChunked = true;
expected += HttpKnownHeaderNames.TransferEncoding + ": chunked\r\n";
Assert.Equal(expected, request.Headers.ToString());
}
[Fact]
public void CustomHeaders_ResponseHeadersAsCustomHeaders_Success()
{
// Header names reserved for response headers are permitted as custom request headers.
headers.Add("Accept-Ranges", "v");
headers.TryAddWithoutValidation("age", "v");
headers.Add("ETag", "v");
headers.Add("Location", "v");
headers.Add("Proxy-Authenticate", "v");
headers.Add("Retry-After", "v");
headers.Add("Server", "v");
headers.Add("Vary", "v");
headers.Add("WWW-Authenticate", "v");
}
[Fact]
public void InvalidHeaders_AddContentHeaders_Throw()
{
// Try adding content headers. Use different casing to make sure case-insensitive comparison
// is used.
Assert.Throws<InvalidOperationException>(() => { headers.Add("Allow", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Encoding", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Language", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("content-length", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Location", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-MD5", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Content-Range", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("CONTENT-TYPE", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Expires", "v"); });
Assert.Throws<InvalidOperationException>(() => { headers.Add("Last-Modified", "v"); });
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Text;
using System.Xml;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using log4net;
using log4net.Config;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using Nini.Config;
namespace OpenSim.Server.Base
{
public class ServicesServerBase : ServerBase
{
// Logger
//
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Command line args
//
protected string[] m_Arguments;
public string ConfigDirectory
{
get;
private set;
}
// Run flag
//
private bool m_Running = true;
// Handle all the automagical stuff
//
public ServicesServerBase(string prompt, string[] args) : base()
{
// Save raw arguments
m_Arguments = args;
// Read command line
ArgvConfigSource argvConfig = new ArgvConfigSource(args);
argvConfig.AddSwitch("Startup", "console", "c");
argvConfig.AddSwitch("Startup", "logfile", "l");
argvConfig.AddSwitch("Startup", "inifile", "i");
argvConfig.AddSwitch("Startup", "prompt", "p");
argvConfig.AddSwitch("Startup", "logconfig", "g");
// Automagically create the ini file name
string fileName = Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().Location);
string iniFile = fileName + ".ini";
string logConfig = null;
IConfig startupConfig = argvConfig.Configs["Startup"];
if (startupConfig != null)
{
// Check if a file name was given on the command line
iniFile = startupConfig.GetString("inifile", iniFile);
// Check if a prompt was given on the command line
prompt = startupConfig.GetString("prompt", prompt);
// Check for a Log4Net config file on the command line
logConfig =startupConfig.GetString("logconfig", logConfig);
}
// Find out of the file name is a URI and remote load it if possible.
// Load it as a local file otherwise.
Uri configUri;
try
{
if (Uri.TryCreate(iniFile, UriKind.Absolute, out configUri) &&
configUri.Scheme == Uri.UriSchemeHttp)
{
XmlReader r = XmlReader.Create(iniFile);
Config = new XmlConfigSource(r);
}
else
{
Config = new IniConfigSource(iniFile);
}
}
catch (Exception e)
{
System.Console.WriteLine("Error reading from config source. {0}", e.Message);
Environment.Exit(1);
}
// Merge OpSys env vars
m_log.Info("[CONFIG]: Loading environment variables for Config");
Util.MergeEnvironmentToConfig(Config);
// Merge the configuration from the command line into the loaded file
Config.Merge(argvConfig);
// Refresh the startupConfig post merge
if (Config.Configs["Startup"] != null)
{
startupConfig = Config.Configs["Startup"];
}
ConfigDirectory = startupConfig.GetString("ConfigDirectory", ".");
prompt = startupConfig.GetString("Prompt", prompt);
// Allow derived classes to load config before the console is opened.
ReadConfig();
// Create main console
string consoleType = "local";
if (startupConfig != null)
consoleType = startupConfig.GetString("console", consoleType);
if (consoleType == "basic")
{
MainConsole.Instance = new CommandConsole(prompt);
}
else if (consoleType == "rest")
{
MainConsole.Instance = new RemoteConsole(prompt);
((RemoteConsole)MainConsole.Instance).ReadConfig(Config);
}
else
{
MainConsole.Instance = new LocalConsole(prompt);
}
m_console = MainConsole.Instance;
if (logConfig != null)
{
FileInfo cfg = new FileInfo(logConfig);
XmlConfigurator.Configure(cfg);
}
else
{
XmlConfigurator.Configure();
}
LogEnvironmentInformation();
RegisterCommonAppenders(startupConfig);
if (startupConfig.GetString("PIDFile", String.Empty) != String.Empty)
{
CreatePIDFile(startupConfig.GetString("PIDFile"));
}
RegisterCommonCommands();
RegisterCommonComponents(Config);
// Allow derived classes to perform initialization that
// needs to be done after the console has opened
Initialise();
}
public bool Running
{
get { return m_Running; }
}
public virtual int Run()
{
Watchdog.Enabled = true;
MemoryWatchdog.Enabled = true;
while (m_Running)
{
try
{
MainConsole.Instance.Prompt();
}
catch (Exception e)
{
m_log.ErrorFormat("Command error: {0}", e);
}
}
RemovePIDFile();
return 0;
}
protected override void ShutdownSpecific()
{
m_Running = false;
m_log.Info("[CONSOLE] Quitting");
base.ShutdownSpecific();
}
protected virtual void ReadConfig()
{
}
protected virtual void Initialise()
{
}
}
}
| |
using System;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Input.Raw;
using Avalonia.Interactivity;
using Avalonia.Platform;
using Avalonia.VisualTree;
namespace Avalonia.Input
{
/// <summary>
/// Represents a mouse device.
/// </summary>
public class MouseDevice : IMouseDevice, IDisposable
{
private int _clickCount;
private Rect _lastClickRect;
private ulong _lastClickTime;
private readonly Pointer _pointer;
private bool _disposed;
private PixelPoint? _position;
public MouseDevice(Pointer? pointer = null)
{
_pointer = pointer ?? new Pointer(Pointer.GetNextFreeId(), PointerType.Mouse, true);
}
/// <summary>
/// Gets the control that is currently capturing by the mouse, if any.
/// </summary>
/// <remarks>
/// When an element captures the mouse, it receives mouse input whether the cursor is
/// within the control's bounds or not. To set the mouse capture, call the
/// <see cref="Capture"/> method.
/// </remarks>
[Obsolete("Use IPointer instead")]
public IInputElement? Captured => _pointer.Captured;
/// <summary>
/// Gets the mouse position, in screen coordinates.
/// </summary>
[Obsolete("Use events instead")]
public PixelPoint Position
{
get => _position ?? new PixelPoint(-1, -1);
protected set => _position = value;
}
/// <summary>
/// Captures mouse input to the specified control.
/// </summary>
/// <param name="control">The control.</param>
/// <remarks>
/// When an element captures the mouse, it receives mouse input whether the cursor is
/// within the control's bounds or not. The current mouse capture control is exposed
/// by the <see cref="Captured"/> property.
/// </remarks>
public void Capture(IInputElement? control)
{
_pointer.Capture(control);
}
/// <summary>
/// Gets the mouse position relative to a control.
/// </summary>
/// <param name="relativeTo">The control.</param>
/// <returns>The mouse position in the control's coordinates.</returns>
public Point GetPosition(IVisual relativeTo)
{
relativeTo = relativeTo ?? throw new ArgumentNullException(nameof(relativeTo));
if (relativeTo.VisualRoot == null)
{
throw new InvalidOperationException("Control is not attached to visual tree.");
}
#pragma warning disable CS0618 // Type or member is obsolete
var rootPoint = relativeTo.VisualRoot.PointToClient(Position);
#pragma warning restore CS0618 // Type or member is obsolete
var transform = relativeTo.VisualRoot.TransformToVisual(relativeTo);
return rootPoint * transform!.Value;
}
public void ProcessRawEvent(RawInputEventArgs e)
{
if (!e.Handled && e is RawPointerEventArgs margs)
ProcessRawEvent(margs);
}
public void TopLevelClosed(IInputRoot root)
{
ClearPointerOver(this, 0, root, PointerPointProperties.None, KeyModifiers.None);
}
public void SceneInvalidated(IInputRoot root, Rect rect)
{
// Pointer is outside of the target area
if (_position == null )
{
if (root.PointerOverElement != null)
ClearPointerOver(this, 0, root, PointerPointProperties.None, KeyModifiers.None);
return;
}
var clientPoint = root.PointToClient(_position.Value);
if (rect.Contains(clientPoint))
{
if (_pointer.Captured == null)
{
SetPointerOver(this, 0 /* TODO: proper timestamp */, root, clientPoint,
PointerPointProperties.None, KeyModifiers.None);
}
else
{
SetPointerOver(this, 0 /* TODO: proper timestamp */, root, _pointer.Captured,
PointerPointProperties.None, KeyModifiers.None);
}
}
}
int ButtonCount(PointerPointProperties props)
{
var rv = 0;
if (props.IsLeftButtonPressed)
rv++;
if (props.IsMiddleButtonPressed)
rv++;
if (props.IsRightButtonPressed)
rv++;
if (props.IsXButton1Pressed)
rv++;
if (props.IsXButton2Pressed)
rv++;
return rv;
}
private void ProcessRawEvent(RawPointerEventArgs e)
{
e = e ?? throw new ArgumentNullException(nameof(e));
var mouse = (MouseDevice)e.Device;
if(mouse._disposed)
return;
_position = e.Root.PointToScreen(e.Position);
var props = CreateProperties(e);
var keyModifiers = KeyModifiersUtils.ConvertToKey(e.InputModifiers);
switch (e.Type)
{
case RawPointerEventType.LeaveWindow:
LeaveWindow(mouse, e.Timestamp, e.Root, props, keyModifiers);
break;
case RawPointerEventType.LeftButtonDown:
case RawPointerEventType.RightButtonDown:
case RawPointerEventType.MiddleButtonDown:
case RawPointerEventType.XButton1Down:
case RawPointerEventType.XButton2Down:
if (ButtonCount(props) > 1)
e.Handled = MouseMove(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers);
else
e.Handled = MouseDown(mouse, e.Timestamp, e.Root, e.Position,
props, keyModifiers);
break;
case RawPointerEventType.LeftButtonUp:
case RawPointerEventType.RightButtonUp:
case RawPointerEventType.MiddleButtonUp:
case RawPointerEventType.XButton1Up:
case RawPointerEventType.XButton2Up:
if (ButtonCount(props) != 0)
e.Handled = MouseMove(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers);
else
e.Handled = MouseUp(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers);
break;
case RawPointerEventType.Move:
e.Handled = MouseMove(mouse, e.Timestamp, e.Root, e.Position, props, keyModifiers);
break;
case RawPointerEventType.Wheel:
e.Handled = MouseWheel(mouse, e.Timestamp, e.Root, e.Position, props, ((RawMouseWheelEventArgs)e).Delta, keyModifiers);
break;
}
}
private void LeaveWindow(IMouseDevice device, ulong timestamp, IInputRoot root, PointerPointProperties properties,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
_position = null;
ClearPointerOver(this, timestamp, root, properties, inputModifiers);
}
PointerPointProperties CreateProperties(RawPointerEventArgs args)
{
var kind = PointerUpdateKind.Other;
if (args.Type == RawPointerEventType.LeftButtonDown)
kind = PointerUpdateKind.LeftButtonPressed;
if (args.Type == RawPointerEventType.MiddleButtonDown)
kind = PointerUpdateKind.MiddleButtonPressed;
if (args.Type == RawPointerEventType.RightButtonDown)
kind = PointerUpdateKind.RightButtonPressed;
if (args.Type == RawPointerEventType.XButton1Down)
kind = PointerUpdateKind.XButton1Pressed;
if (args.Type == RawPointerEventType.XButton2Down)
kind = PointerUpdateKind.XButton2Pressed;
if (args.Type == RawPointerEventType.LeftButtonUp)
kind = PointerUpdateKind.LeftButtonReleased;
if (args.Type == RawPointerEventType.MiddleButtonUp)
kind = PointerUpdateKind.MiddleButtonReleased;
if (args.Type == RawPointerEventType.RightButtonUp)
kind = PointerUpdateKind.RightButtonReleased;
if (args.Type == RawPointerEventType.XButton1Up)
kind = PointerUpdateKind.XButton1Released;
if (args.Type == RawPointerEventType.XButton2Up)
kind = PointerUpdateKind.XButton2Released;
return new PointerPointProperties(args.InputModifiers, kind);
}
private MouseButton _lastMouseDownButton;
private bool MouseDown(IMouseDevice device, ulong timestamp, IInputElement root, Point p,
PointerPointProperties properties,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
var hit = HitTest(root, p);
if (hit != null)
{
_pointer.Capture(hit);
var source = GetSource(hit);
if (source != null)
{
var settings = AvaloniaLocator.Current.GetService<IPlatformSettings>();
var doubleClickTime = settings.DoubleClickTime.TotalMilliseconds;
if (!_lastClickRect.Contains(p) || timestamp - _lastClickTime > doubleClickTime)
{
_clickCount = 0;
}
++_clickCount;
_lastClickTime = timestamp;
_lastClickRect = new Rect(p, new Size())
.Inflate(new Thickness(settings.DoubleClickSize.Width / 2, settings.DoubleClickSize.Height / 2));
_lastMouseDownButton = properties.PointerUpdateKind.GetMouseButton();
var e = new PointerPressedEventArgs(source, _pointer, root, p, timestamp, properties, inputModifiers, _clickCount);
source.RaiseEvent(e);
return e.Handled;
}
}
return false;
}
private bool MouseMove(IMouseDevice device, ulong timestamp, IInputRoot root, Point p, PointerPointProperties properties,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
IInputElement? source;
if (_pointer.Captured == null)
{
source = SetPointerOver(this, timestamp, root, p, properties, inputModifiers);
}
else
{
SetPointerOver(this, timestamp, root, _pointer.Captured, properties, inputModifiers);
source = _pointer.Captured;
}
if (source is object)
{
var e = new PointerEventArgs(InputElement.PointerMovedEvent, source, _pointer, root,
p, timestamp, properties, inputModifiers);
source.RaiseEvent(e);
return e.Handled;
}
return false;
}
private bool MouseUp(IMouseDevice device, ulong timestamp, IInputRoot root, Point p, PointerPointProperties props,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
var hit = HitTest(root, p);
if (hit != null)
{
var source = GetSource(hit);
var e = new PointerReleasedEventArgs(source, _pointer, root, p, timestamp, props, inputModifiers,
_lastMouseDownButton);
source?.RaiseEvent(e);
_pointer.Capture(null);
return e.Handled;
}
return false;
}
private bool MouseWheel(IMouseDevice device, ulong timestamp, IInputRoot root, Point p,
PointerPointProperties props,
Vector delta, KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
var hit = HitTest(root, p);
if (hit != null)
{
var source = GetSource(hit);
var e = new PointerWheelEventArgs(source, _pointer, root, p, timestamp, props, inputModifiers, delta);
source?.RaiseEvent(e);
return e.Handled;
}
return false;
}
private IInteractive GetSource(IVisual hit)
{
hit = hit ?? throw new ArgumentNullException(nameof(hit));
return _pointer.Captured ??
(hit as IInteractive) ??
hit.GetSelfAndVisualAncestors().OfType<IInteractive>().FirstOrDefault();
}
private IInputElement? HitTest(IInputElement root, Point p)
{
root = root ?? throw new ArgumentNullException(nameof(root));
return _pointer.Captured ?? root.InputHitTest(p);
}
PointerEventArgs CreateSimpleEvent(RoutedEvent ev, ulong timestamp, IInteractive? source,
PointerPointProperties properties,
KeyModifiers inputModifiers)
{
return new PointerEventArgs(ev, source, _pointer, null, default,
timestamp, properties, inputModifiers);
}
private void ClearPointerOver(IPointerDevice device, ulong timestamp, IInputRoot root,
PointerPointProperties properties,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
var element = root.PointerOverElement;
var e = CreateSimpleEvent(InputElement.PointerLeaveEvent, timestamp, element, properties, inputModifiers);
if (element!=null && !element.IsAttachedToVisualTree)
{
// element has been removed from visual tree so do top down cleanup
if (root.IsPointerOver)
ClearChildrenPointerOver(e, root,true);
}
while (element != null)
{
e.Source = element;
e.Handled = false;
element.RaiseEvent(e);
element = (IInputElement?)element.VisualParent;
}
root.PointerOverElement = null;
}
private void ClearChildrenPointerOver(PointerEventArgs e, IInputElement element,bool clearRoot)
{
foreach (IInputElement el in element.VisualChildren)
{
if (el.IsPointerOver)
{
ClearChildrenPointerOver(e, el, true);
break;
}
}
if(clearRoot)
{
e.Source = element;
e.Handled = false;
element.RaiseEvent(e);
}
}
private IInputElement? SetPointerOver(IPointerDevice device, ulong timestamp, IInputRoot root, Point p,
PointerPointProperties properties,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
var element = root.InputHitTest(p);
if (element != root.PointerOverElement)
{
if (element != null)
{
SetPointerOver(device, timestamp, root, element, properties, inputModifiers);
}
else
{
ClearPointerOver(device, timestamp, root, properties, inputModifiers);
}
}
return element;
}
private void SetPointerOver(IPointerDevice device, ulong timestamp, IInputRoot root, IInputElement element,
PointerPointProperties properties,
KeyModifiers inputModifiers)
{
device = device ?? throw new ArgumentNullException(nameof(device));
root = root ?? throw new ArgumentNullException(nameof(root));
element = element ?? throw new ArgumentNullException(nameof(element));
IInputElement? branch = null;
IInputElement? el = element;
while (el != null)
{
if (el.IsPointerOver)
{
branch = el;
break;
}
el = (IInputElement?)el.VisualParent;
}
el = root.PointerOverElement;
var e = CreateSimpleEvent(InputElement.PointerLeaveEvent, timestamp, el, properties, inputModifiers);
if (el!=null && branch!=null && !el.IsAttachedToVisualTree)
{
ClearChildrenPointerOver(e,branch,false);
}
while (el != null && el != branch)
{
e.Source = el;
e.Handled = false;
el.RaiseEvent(e);
el = (IInputElement?)el.VisualParent;
}
el = root.PointerOverElement = element;
e.RoutedEvent = InputElement.PointerEnterEvent;
while (el != null && el != branch)
{
e.Source = el;
e.Handled = false;
el.RaiseEvent(e);
el = (IInputElement?)el.VisualParent;
}
}
public void Dispose()
{
_disposed = true;
_pointer?.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 gcsv = Google.Cloud.ServiceDirectory.V1Beta1;
using sys = System;
namespace Google.Cloud.ServiceDirectory.V1Beta1
{
/// <summary>Resource name for the <c>Service</c> resource.</summary>
public sealed partial class ServiceName : gax::IResourceName, sys::IEquatable<ServiceName>
{
/// <summary>The possible contents of <see cref="ServiceName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>.
/// </summary>
ProjectLocationNamespaceService = 1,
}
private static gax::PathTemplate s_projectLocationNamespaceService = new gax::PathTemplate("projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}");
/// <summary>Creates a <see cref="ServiceName"/> 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="ServiceName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static ServiceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ServiceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ServiceName"/> with the pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ServiceName"/> constructed from the provided ids.</returns>
public static ServiceName FromProjectLocationNamespaceService(string projectId, string locationId, string namespaceId, string serviceId) =>
new ServiceName(ResourceNameType.ProjectLocationNamespaceService, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), namespaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ServiceName"/> with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string namespaceId, string serviceId) =>
FormatProjectLocationNamespaceService(projectId, locationId, namespaceId, serviceId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ServiceName"/> with pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>.
/// </returns>
public static string FormatProjectLocationNamespaceService(string projectId, string locationId, string namespaceId, string serviceId) =>
s_projectLocationNamespaceService.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)));
/// <summary>Parses the given resource name string into a new <see cref="ServiceName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ServiceName"/> if successful.</returns>
public static ServiceName Parse(string serviceName) => Parse(serviceName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ServiceName"/> 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>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="serviceName">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="ServiceName"/> if successful.</returns>
public static ServiceName Parse(string serviceName, bool allowUnparsed) =>
TryParse(serviceName, allowUnparsed, out ServiceName 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="ServiceName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ServiceName"/>, 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 serviceName, out ServiceName result) => TryParse(serviceName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ServiceName"/> 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>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="serviceName">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="ServiceName"/>, 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 serviceName, bool allowUnparsed, out ServiceName result)
{
gax::GaxPreconditions.CheckNotNull(serviceName, nameof(serviceName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationNamespaceService.TryParseName(serviceName, out resourceName))
{
result = FromProjectLocationNamespaceService(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(serviceName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ServiceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string namespaceId = null, string projectId = null, string serviceId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
NamespaceId = namespaceId;
ProjectId = projectId;
ServiceId = serviceId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ServiceName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="namespaceId">The <c>Namespace</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param>
public ServiceName(string projectId, string locationId, string namespaceId, string serviceId) : this(ResourceNameType.ProjectLocationNamespaceService, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), namespaceId: gax::GaxPreconditions.CheckNotNullOrEmpty(namespaceId, nameof(namespaceId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId)))
{
}
/// <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>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Namespace</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string NamespaceId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Service</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ServiceId { 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.ProjectLocationNamespaceService: return s_projectLocationNamespaceService.Expand(ProjectId, LocationId, NamespaceId, ServiceId);
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 ServiceName);
/// <inheritdoc/>
public bool Equals(ServiceName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ServiceName a, ServiceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ServiceName a, ServiceName b) => !(a == b);
}
public partial class Service
{
/// <summary>
/// <see cref="gcsv::ServiceName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::ServiceName ServiceName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::ServiceName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// 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.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.WebSockets.Client.Tests
{
/// <summary>
/// ClientWebSocket tests that do require a remote server.
/// </summary>
public class ClientWebSocketTest
{
public readonly static object[][] EchoServers = WebSocketTestServers.EchoServers;
public readonly static object[][] EchoHeadersServers = WebSocketTestServers.EchoHeadersServers;
private const int TimeOutMilliseconds = 10000;
private const int CloseDescriptionMaxLength = 123;
private readonly ITestOutputHelper _output;
public ClientWebSocketTest(ITestOutputHelper output)
{
_output = output;
}
public static IEnumerable<object[]> UnavailableWebSocketServers
{
get
{
Uri server;
// Unknown server.
{
server = new Uri(string.Format("ws://{0}", Guid.NewGuid().ToString()));
yield return new object[] { server };
}
// Known server but not a real websocket endpoint.
{
server = HttpTestServers.RemoteEchoServer;
var ub = new UriBuilder("ws", server.Host, server.Port, server.PathAndQuery);
yield return new object[] { ub.Uri };
}
}
}
private static bool WebSocketsSupported { get { return WebSocketHelper.WebSocketsSupported; } }
#region Connect
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(UnavailableWebSocketServers))]
public async Task ConnectAsync_NotWebSocketServer_ThrowsWebSocketExceptionWithMessage(Uri server)
{
using (var cws = new ClientWebSocket())
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() =>
cws.ConnectAsync(server, cts.Token));
Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode);
Assert.Equal(WebSocketState.Closed, cws.State);
Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task EchoBinaryMessage_Success(Uri server)
{
await WebSocketHelper.TestEcho(server, WebSocketMessageType.Binary, TimeOutMilliseconds, _output);
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task EchoTextMessage_Success(Uri server)
{
await WebSocketHelper.TestEcho(server, WebSocketMessageType.Text, TimeOutMilliseconds, _output);
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoHeadersServers))]
public async Task ConnectAsync_AddCustomHeaders_Success(Uri server)
{
using (var cws = new ClientWebSocket())
{
cws.Options.SetRequestHeader("X-CustomHeader1", "Value1");
cws.Options.SetRequestHeader("X-CustomHeader2", "Value2");
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
Task taskConnect = cws.ConnectAsync(server, cts.Token);
Assert.True(
(cws.State == WebSocketState.None) ||
(cws.State == WebSocketState.Connecting) ||
(cws.State == WebSocketState.Open),
"State immediately after ConnectAsync incorrect: " + cws.State);
await taskConnect;
}
Assert.Equal(WebSocketState.Open, cws.State);
byte[] buffer = new byte[65536];
var segment = new ArraySegment<byte>(buffer, 0, buffer.Length);
WebSocketReceiveResult recvResult;
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
recvResult = await cws.ReceiveAsync(segment, cts.Token);
}
Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType);
string headers = WebSocketData.GetTextFromBuffer(segment);
Assert.True(headers.Contains("X-CustomHeader1:Value1"));
Assert.True(headers.Contains("X-CustomHeader2:Value2"));
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task ConnectAsync_PassNoSubProtocol_ServerRequires_ThrowsWebSocketExceptionWithMessage(Uri server)
{
const string AcceptedProtocol = "CustomProtocol";
using (var cws = new ClientWebSocket())
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var ub = new UriBuilder(server);
ub.Query = "subprotocol=" + AcceptedProtocol;
WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() =>
cws.ConnectAsync(ub.Uri, cts.Token));
Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode);
Assert.Equal(WebSocketState.Closed, cws.State);
Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task ConnectAsync_PassMultipleSubProtocols_ServerRequires_ConnectionUsesAgreedSubProtocol(Uri server)
{
const string AcceptedProtocol = "AcceptedProtocol";
const string OtherProtocol = "OtherProtocol";
using (var cws = new ClientWebSocket())
{
cws.Options.AddSubProtocol(AcceptedProtocol);
cws.Options.AddSubProtocol(OtherProtocol);
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var ub = new UriBuilder(server);
ub.Query = "subprotocol=" + AcceptedProtocol;
await cws.ConnectAsync(ub.Uri, cts.Token);
Assert.Equal(WebSocketState.Open, cws.State);
Assert.Equal(AcceptedProtocol, cws.SubProtocol);
}
}
#endregion
#region SendReceive
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task SendReceive_PartialMessage_Success(Uri server)
{
var sendBuffer = new byte[1024];
var sendSegment = new ArraySegment<byte>(sendBuffer);
var receiveBuffer = new byte[1024];
var receiveSegment = new ArraySegment<byte>(receiveBuffer);
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
// The server will read buffers and aggregate it up to 64KB before echoing back a complete message.
// But since this test uses a receive buffer that is small, we will get back partial message fragments
// as we read them until we read the complete message payload.
for (int i = 0; i < 63; i++)
{
await cws.SendAsync(sendSegment, WebSocketMessageType.Binary, false, ctsDefault.Token);
}
await cws.SendAsync(sendSegment, WebSocketMessageType.Binary, true, ctsDefault.Token);
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(receiveSegment, ctsDefault.Token);
Assert.Equal(false, recvResult.EndOfMessage);
while (recvResult.EndOfMessage == false)
{
recvResult = await cws.ReceiveAsync(receiveSegment, ctsDefault.Token);
}
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "PartialMessageTest", ctsDefault.Token);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task SendAsync_SendCloseMessageType_ThrowsArgumentExceptionWithMessage(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
string expectedInnerMessage = ResourceHelper.GetExceptionMessage(
"net_WebSockets_Argument_InvalidMessageType",
"Close",
"SendAsync",
"Binary",
"Text",
"CloseOutputAsync");
var expectedException = new ArgumentException(expectedInnerMessage, "messageType");
string expectedMessage = expectedException.Message;
Assert.Throws<ArgumentException>(() => {
Task t = cws.SendAsync(new ArraySegment<byte>(), WebSocketMessageType.Close, true, cts.Token); } );
Assert.Equal(WebSocketState.Open, cws.State);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task SendAsync__MultipleOutstandingSendOperations_Throws(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
Task [] tasks = new Task[10];
try
{
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = cws.SendAsync(
WebSocketData.GetBufferFromText("hello"),
WebSocketMessageType.Text,
true,
cts.Token);
}
Task.WaitAll(tasks);
Assert.Equal(WebSocketState.Open, cws.State);
}
catch (AggregateException ag)
{
foreach (var ex in ag.InnerExceptions)
{
if (ex is InvalidOperationException)
{
Assert.Equal(
ResourceHelper.GetExceptionMessage(
"net_Websockets_AlreadyOneOutstandingOperation",
"SendAsync"),
ex.Message);
Assert.Equal(WebSocketState.Aborted, cws.State);
}
else if (ex is WebSocketException)
{
// Multiple cases.
Assert.Equal(WebSocketState.Aborted, cws.State);
WebSocketError errCode = (ex as WebSocketException).WebSocketErrorCode;
Assert.True(
(errCode == WebSocketError.InvalidState) || (errCode == WebSocketError.Success),
"WebSocketErrorCode");
}
else
{
Assert.True(false, "Unexpected exception: " + ex.Message);
}
}
}
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task ReceiveAsync_MultipleOutstandingReceiveOperations_Throws(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
Task[] tasks = new Task[2];
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
cts.Token);
var recvBuffer = new byte[100];
var recvSegment = new ArraySegment<byte>(recvBuffer);
try
{
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = cws.ReceiveAsync(recvSegment, cts.Token);
}
Task.WaitAll(tasks);
Assert.Equal(WebSocketState.Open, cws.State);
}
catch (AggregateException ag)
{
foreach (var ex in ag.InnerExceptions)
{
if (ex is InvalidOperationException)
{
Assert.Equal(
ResourceHelper.GetExceptionMessage(
"net_Websockets_AlreadyOneOutstandingOperation",
"ReceiveAsync"),
ex.Message);
Assert.Equal(WebSocketState.Aborted, cws.State);
}
else if (ex is WebSocketException)
{
// Multiple cases.
Assert.Equal(WebSocketState.Aborted, cws.State);
WebSocketError errCode = (ex as WebSocketException).WebSocketErrorCode;
Assert.True(
(errCode == WebSocketError.InvalidState) || (errCode == WebSocketError.Success),
"WebSocketErrorCode");
}
else
{
Assert.True(false, "Unexpected exception: " + ex.Message);
}
}
}
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task SendAsync_SendZeroLengthPayloadAsEndOfMessage_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
string message = "hello";
await cws.SendAsync(
WebSocketData.GetBufferFromText(message),
WebSocketMessageType.Text,
false,
cts.Token);
Assert.Equal(WebSocketState.Open, cws.State);
await cws.SendAsync(new ArraySegment<byte>(new byte[0]),
WebSocketMessageType.Text,
true,
cts.Token);
Assert.Equal(WebSocketState.Open, cws.State);
var recvBuffer = new byte[100];
var receiveSegment = new ArraySegment<byte>(recvBuffer);
WebSocketReceiveResult recvRet = await cws.ReceiveAsync(receiveSegment, cts.Token);
Assert.Equal(WebSocketState.Open, cws.State);
Assert.Equal(message.Length, recvRet.Count);
Assert.Equal(WebSocketMessageType.Text, recvRet.MessageType);
Assert.Equal(true, recvRet.EndOfMessage);
Assert.Equal(null, recvRet.CloseStatus);
Assert.Equal(null, recvRet.CloseStatusDescription);
var recvSegment = new ArraySegment<byte>(receiveSegment.Array, receiveSegment.Offset, recvRet.Count);
Assert.Equal(message, WebSocketData.GetTextFromBuffer(recvSegment));
}
}
#endregion
#region Close
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_ServerInitiatedClose_Success(Uri server)
{
const string closeWebSocketMetaCommand = ".close";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
_output.WriteLine("SendAsync starting.");
await cws.SendAsync(
WebSocketData.GetBufferFromText(closeWebSocketMetaCommand),
WebSocketMessageType.Text,
true,
cts.Token);
_output.WriteLine("SendAsync done.");
var recvBuffer = new byte[256];
_output.WriteLine("ReceiveAsync starting.");
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(new ArraySegment<byte>(recvBuffer), cts.Token);
_output.WriteLine("ReceiveAsync done.");
// Verify received server-initiated close message.
Assert.Equal(WebSocketCloseStatus.NormalClosure, recvResult.CloseStatus);
Assert.Equal(closeWebSocketMetaCommand, recvResult.CloseStatusDescription);
// Verify current websocket state as CloseReceived which indicates only partial close.
Assert.Equal(WebSocketState.CloseReceived, cws.State);
Assert.Equal(WebSocketCloseStatus.NormalClosure, cws.CloseStatus);
Assert.Equal(closeWebSocketMetaCommand, cws.CloseStatusDescription);
// Send back close message to acknowledge server-initiated close.
_output.WriteLine("CloseAsync starting.");
await cws.CloseAsync(WebSocketCloseStatus.InvalidMessageType, string.Empty, cts.Token);
_output.WriteLine("CloseAsync done.");
Assert.Equal(WebSocketState.Closed, cws.State);
// Verify that there is no follow-up echo close message back from the server by
// making sure the close code and message are the same as from the first server close message.
Assert.Equal(WebSocketCloseStatus.NormalClosure, cws.CloseStatus);
Assert.Equal(closeWebSocketMetaCommand, cws.CloseStatusDescription);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_ClientInitiatedClose_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
Assert.Equal(WebSocketState.Open, cws.State);
var closeStatus = WebSocketCloseStatus.InvalidMessageType;
string closeDescription = "CloseAsync_InvalidMessageType";
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(WebSocketState.Closed, cws.State);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(closeDescription, cws.CloseStatusDescription);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_CloseDescriptionIsMaxLength_Success(Uri server)
{
string closeDescription = new string('C', CloseDescriptionMaxLength);
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, closeDescription, cts.Token);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_CloseDescriptionIsMaxLengthPlusOne_ThrowsArgumentException(Uri server)
{
string closeDescription = new string('C', CloseDescriptionMaxLength + 1);
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
string expectedInnerMessage = ResourceHelper.GetExceptionMessage(
"net_WebSockets_InvalidCloseStatusDescription",
closeDescription,
CloseDescriptionMaxLength);
var expectedException = new ArgumentException(expectedInnerMessage, "statusDescription");
string expectedMessage = expectedException.Message;
Assert.Throws<ArgumentException>(() =>
{ Task t = cws.CloseAsync(WebSocketCloseStatus.NormalClosure, closeDescription, cts.Token); });
Assert.Equal(WebSocketState.Open, cws.State);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_CloseDescriptionHasUnicode_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.InvalidMessageType;
string closeDescription = "CloseAsync_Containing\u016Cnicode.";
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(closeDescription, cws.CloseStatusDescription);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_CloseDescriptionIsNull_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.NormalClosure;
string closeDescription = null;
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(true, String.IsNullOrEmpty(cws.CloseStatusDescription));
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_ClientInitiated_CanReceive_CanClose(Uri server)
{
string message = "Hello WebSockets!";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.InvalidPayloadData;
string closeDescription = "CloseOutputAsync_Client_InvalidPayloadData";
await cws.SendAsync(WebSocketData.GetBufferFromText(message), WebSocketMessageType.Text, true, cts.Token);
// Need a short delay as per WebSocket rfc6455 section 5.5.1 there isn't a requirement to receive any
// data fragments after a close has been sent. The delay allows the received data fragment to be
// available before calling close. The WinRT MessageWebSocket implementation doesn't allow receiving
// after a call to Close.
await Task.Delay(100);
await cws.CloseOutputAsync(closeStatus, closeDescription, cts.Token);
// Should be able to receive the message echoed by the server.
var recvBuffer = new byte[100];
var segmentRecv = new ArraySegment<byte>(recvBuffer);
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(segmentRecv, cts.Token);
Assert.Equal(message.Length, recvResult.Count);
segmentRecv = new ArraySegment<byte>(segmentRecv.Array, 0, recvResult.Count);
Assert.Equal(message, WebSocketData.GetTextFromBuffer(segmentRecv));
Assert.Equal(null, recvResult.CloseStatus);
Assert.Equal(null, recvResult.CloseStatusDescription);
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(closeDescription, cws.CloseStatusDescription);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_ServerInitiated_CanSend(Uri server)
{
string message = "Hello WebSockets!";
var expectedCloseStatus = WebSocketCloseStatus.NormalClosure;
var expectedCloseDescription = ".shutdown";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".shutdown"),
WebSocketMessageType.Text,
true,
cts.Token);
// Should be able to receive a shutdown message.
var recvBuffer = new byte[100];
var segmentRecv = new ArraySegment<byte>(recvBuffer);
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(segmentRecv, cts.Token);
Assert.Equal(0, recvResult.Count);
Assert.Equal(expectedCloseStatus, recvResult.CloseStatus);
Assert.Equal(expectedCloseDescription, recvResult.CloseStatusDescription);
// Verify WebSocket state
Assert.Equal(expectedCloseStatus, cws.CloseStatus);
Assert.Equal(expectedCloseDescription, cws.CloseStatusDescription);
Assert.Equal(WebSocketState.CloseReceived, cws.State);
// Should be able to send.
await cws.SendAsync(WebSocketData.GetBufferFromText(message), WebSocketMessageType.Text, true, cts.Token);
// Cannot change the close status/description with the final close.
var closeStatus = WebSocketCloseStatus.InvalidPayloadData;
var closeDescription = "CloseOutputAsync_Client_Description";
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(expectedCloseStatus, cws.CloseStatus);
Assert.Equal(expectedCloseDescription, cws.CloseStatusDescription);
Assert.Equal(WebSocketState.Closed, cws.State);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_CloseDescriptionIsNull_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.NormalClosure;
string closeDescription = null;
await cws.CloseOutputAsync(closeStatus, closeDescription, cts.Token);
}
}
#endregion
#region Abort
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public void Abort_ConnectAndAbort_ThrowsWebSocketExceptionWithmessage(Uri server)
{
using (var cws = new ClientWebSocket())
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var ub = new UriBuilder(server);
ub.Query = "delay10sec";
Task t = cws.ConnectAsync(ub.Uri, cts.Token);
cws.Abort();
WebSocketException ex = Assert.Throws<WebSocketException>(() => t.GetAwaiter().GetResult());
Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message);
Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode);
Assert.Equal(WebSocketState.Closed, cws.State);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task Abort_SendAndAbort_Success(Uri server)
{
await TestCancellation(async (cws) => {
var cts = new CancellationTokenSource(TimeOutMilliseconds);
Task t = cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
cts.Token);
cws.Abort();
await t;
}, server);
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task Abort_ReceiveAndAbort_Success(Uri server)
{
await TestCancellation(async (cws) => {
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
ctsDefault.Token);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
Task t = cws.ReceiveAsync(segment, ctsDefault.Token);
cws.Abort();
await t;
}, server);
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task Abort_CloseAndAbort_Success(Uri server)
{
await TestCancellation(async (cws) => {
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
ctsDefault.Token);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
Task t = cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "AbortClose", ctsDefault.Token);
cws.Abort();
await t;
}, server);
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task ClientWebSocket_Abort_CloseOutputAsync(Uri server)
{
await TestCancellation(async (cws) => {
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
ctsDefault.Token);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
Task t = cws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "AbortShutdown", ctsDefault.Token);
cws.Abort();
await t;
}, server);
}
#endregion
#region Cancellation
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task ConnectAsync_Cancel_ThrowsWebSocketExceptionWithMessage(Uri server)
{
using (var cws = new ClientWebSocket())
{
var cts = new CancellationTokenSource(500);
var ub = new UriBuilder(server);
ub.Query = "delay10sec";
WebSocketException ex =
await Assert.ThrowsAsync<WebSocketException>(() => cws.ConnectAsync(ub.Uri, cts.Token));
Assert.Equal(
ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"),
ex.Message);
Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode);
Assert.Equal(WebSocketState.Closed, cws.State);
}
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task SendAsync_Cancel_Success(Uri server)
{
await TestCancellation((cws) => {
var cts = new CancellationTokenSource(5);
return cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
cts.Token);
}, server);
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task ReceiveAsync_Cancel_Success(Uri server)
{
await TestCancellation(async (cws) => {
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
var cts = new CancellationTokenSource(5);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
ctsDefault.Token);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
await cws.ReceiveAsync(segment, cts.Token);
}, server);
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseAsync_Cancel_Success(Uri server)
{
await TestCancellation(async (cws) => {
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
var cts = new CancellationTokenSource(5);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
ctsDefault.Token);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "CancelClose", cts.Token);
}, server);
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_Cancel_Success(Uri server)
{
await TestCancellation(async (cws) => {
var cts = new CancellationTokenSource(5);
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
ctsDefault.Token);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
await cws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "CancelShutdown", cts.Token);
}, server);
}
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task ReceiveAsync_CancelAndReceive_ThrowsWebSocketExceptionWithMessage(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(500);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
try
{
await cws.ReceiveAsync(segment, cts.Token);
Assert.True(false, "Receive should not complete.");
}
catch (OperationCanceledException) { }
catch (ObjectDisposedException) { }
catch (WebSocketException) { }
WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() =>
cws.ReceiveAsync(segment, CancellationToken.None));
Assert.Equal(
ResourceHelper.GetExceptionMessage("net_WebSockets_InvalidState", "Aborted", "Open, CloseSent"),
ex.Message);
}
}
private async Task TestCancellation(Func<ClientWebSocket, Task> action, Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
try
{
await action(cws);
// Operation finished before CTS expired.
}
catch (OperationCanceledException)
{
// Expected exception
Assert.Equal(WebSocketState.Aborted, cws.State);
}
catch (ObjectDisposedException)
{
// Expected exception
Assert.Equal(WebSocketState.Aborted, cws.State);
}
catch (WebSocketException exception)
{
Assert.Equal(ResourceHelper.GetExceptionMessage(
"net_WebSockets_InvalidState_ClosedOrAborted",
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"),
exception.Message);
Assert.Equal(WebSocketError.InvalidState, exception.WebSocketErrorCode);
Assert.Equal(WebSocketState.Aborted, cws.State);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace BankingSite.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Utils;
using osu.Game.Extensions;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Screens.Edit.Compose.Components;
using osuTK;
namespace osu.Game.Rulesets.Osu.Edit
{
public class OsuSelectionHandler : EditorSelectionHandler
{
/// <summary>
/// During a transform, the initial origin is stored so it can be used throughout the operation.
/// </summary>
private Vector2? referenceOrigin;
/// <summary>
/// During a transform, the initial path types of a single selected slider are stored so they
/// can be maintained throughout the operation.
/// </summary>
private List<PathType?> referencePathTypes;
protected override void OnSelectionChanged()
{
base.OnSelectionChanged();
Quad quad = selectedMovableObjects.Length > 0 ? getSurroundingQuad(selectedMovableObjects) : new Quad();
SelectionBox.CanRotate = quad.Width > 0 || quad.Height > 0;
SelectionBox.CanFlipX = SelectionBox.CanScaleX = quad.Width > 0;
SelectionBox.CanFlipY = SelectionBox.CanScaleY = quad.Height > 0;
SelectionBox.CanReverse = EditorBeatmap.SelectedHitObjects.Count > 1 || EditorBeatmap.SelectedHitObjects.Any(s => s is Slider);
}
protected override void OnOperationEnded()
{
base.OnOperationEnded();
referenceOrigin = null;
referencePathTypes = null;
}
public override bool HandleMovement(MoveSelectionEvent<HitObject> moveEvent)
{
var hitObjects = selectedMovableObjects;
// this will potentially move the selection out of bounds...
foreach (var h in hitObjects)
h.Position += this.ScreenSpaceDeltaToParentSpace(moveEvent.ScreenSpaceDelta);
// but this will be corrected.
moveSelectionInBounds();
return true;
}
public override bool HandleReverse()
{
var hitObjects = EditorBeatmap.SelectedHitObjects;
double endTime = hitObjects.Max(h => h.GetEndTime());
double startTime = hitObjects.Min(h => h.StartTime);
bool moreThanOneObject = hitObjects.Count > 1;
foreach (var h in hitObjects)
{
if (moreThanOneObject)
h.StartTime = endTime - (h.GetEndTime() - startTime);
if (h is Slider slider)
{
slider.Path.Reverse(out Vector2 offset);
slider.Position += offset;
}
}
return true;
}
public override bool HandleFlip(Direction direction)
{
var hitObjects = selectedMovableObjects;
var selectedObjectsQuad = getSurroundingQuad(hitObjects);
foreach (var h in hitObjects)
{
h.Position = GetFlippedPosition(direction, selectedObjectsQuad, h.Position);
if (h is Slider slider)
{
foreach (var point in slider.Path.ControlPoints)
{
point.Position = new Vector2(
(direction == Direction.Horizontal ? -1 : 1) * point.Position.X,
(direction == Direction.Vertical ? -1 : 1) * point.Position.Y
);
}
}
}
return true;
}
public override bool HandleScale(Vector2 scale, Anchor reference)
{
adjustScaleFromAnchor(ref scale, reference);
var hitObjects = selectedMovableObjects;
// for the time being, allow resizing of slider paths only if the slider is
// the only hit object selected. with a group selection, it's likely the user
// is not looking to change the duration of the slider but expand the whole pattern.
if (hitObjects.Length == 1 && hitObjects.First() is Slider slider)
scaleSlider(slider, scale);
else
scaleHitObjects(hitObjects, reference, scale);
moveSelectionInBounds();
return true;
}
private static void adjustScaleFromAnchor(ref Vector2 scale, Anchor reference)
{
// cancel out scale in axes we don't care about (based on which drag handle was used).
if ((reference & Anchor.x1) > 0) scale.X = 0;
if ((reference & Anchor.y1) > 0) scale.Y = 0;
// reverse the scale direction if dragging from top or left.
if ((reference & Anchor.x0) > 0) scale.X = -scale.X;
if ((reference & Anchor.y0) > 0) scale.Y = -scale.Y;
}
public override bool HandleRotation(float delta)
{
var hitObjects = selectedMovableObjects;
Quad quad = getSurroundingQuad(hitObjects);
referenceOrigin ??= quad.Centre;
foreach (var h in hitObjects)
{
h.Position = RotatePointAroundOrigin(h.Position, referenceOrigin.Value, delta);
if (h is IHasPath path)
{
foreach (var point in path.Path.ControlPoints)
point.Position = RotatePointAroundOrigin(point.Position, Vector2.Zero, delta);
}
}
// this isn't always the case but let's be lenient for now.
return true;
}
private void scaleSlider(Slider slider, Vector2 scale)
{
referencePathTypes ??= slider.Path.ControlPoints.Select(p => p.Type).ToList();
Quad sliderQuad = GetSurroundingQuad(slider.Path.ControlPoints.Select(p => p.Position));
// Limit minimum distance between control points after scaling to almost 0. Less than 0 causes the slider to flip, exactly 0 causes a crash through division by 0.
scale = Vector2.ComponentMax(new Vector2(Precision.FLOAT_EPSILON), sliderQuad.Size + scale) - sliderQuad.Size;
Vector2 pathRelativeDeltaScale = new Vector2(
sliderQuad.Width == 0 ? 0 : 1 + scale.X / sliderQuad.Width,
sliderQuad.Height == 0 ? 0 : 1 + scale.Y / sliderQuad.Height);
Queue<Vector2> oldControlPoints = new Queue<Vector2>();
foreach (var point in slider.Path.ControlPoints)
{
oldControlPoints.Enqueue(point.Position);
point.Position *= pathRelativeDeltaScale;
}
// Maintain the path types in case they were defaulted to bezier at some point during scaling
for (int i = 0; i < slider.Path.ControlPoints.Count; ++i)
slider.Path.ControlPoints[i].Type = referencePathTypes[i];
//if sliderhead or sliderend end up outside playfield, revert scaling.
Quad scaledQuad = getSurroundingQuad(new OsuHitObject[] { slider });
(bool xInBounds, bool yInBounds) = isQuadInBounds(scaledQuad);
if (xInBounds && yInBounds && slider.Path.HasValidLength)
return;
foreach (var point in slider.Path.ControlPoints)
point.Position = oldControlPoints.Dequeue();
}
private void scaleHitObjects(OsuHitObject[] hitObjects, Anchor reference, Vector2 scale)
{
scale = getClampedScale(hitObjects, reference, scale);
Quad selectionQuad = getSurroundingQuad(hitObjects);
foreach (var h in hitObjects)
h.Position = GetScaledPosition(reference, scale, selectionQuad, h.Position);
}
private (bool X, bool Y) isQuadInBounds(Quad quad)
{
bool xInBounds = (quad.TopLeft.X >= 0) && (quad.BottomRight.X <= DrawWidth);
bool yInBounds = (quad.TopLeft.Y >= 0) && (quad.BottomRight.Y <= DrawHeight);
return (xInBounds, yInBounds);
}
private void moveSelectionInBounds()
{
var hitObjects = selectedMovableObjects;
Quad quad = getSurroundingQuad(hitObjects);
Vector2 delta = Vector2.Zero;
if (quad.TopLeft.X < 0)
delta.X -= quad.TopLeft.X;
if (quad.TopLeft.Y < 0)
delta.Y -= quad.TopLeft.Y;
if (quad.BottomRight.X > DrawWidth)
delta.X -= quad.BottomRight.X - DrawWidth;
if (quad.BottomRight.Y > DrawHeight)
delta.Y -= quad.BottomRight.Y - DrawHeight;
foreach (var h in hitObjects)
h.Position += delta;
}
/// <summary>
/// Clamp scale for multi-object-scaling where selection does not exceed playfield bounds or flip.
/// </summary>
/// <param name="hitObjects">The hitobjects to be scaled</param>
/// <param name="reference">The anchor from which the scale operation is performed</param>
/// <param name="scale">The scale to be clamped</param>
/// <returns>The clamped scale vector</returns>
private Vector2 getClampedScale(OsuHitObject[] hitObjects, Anchor reference, Vector2 scale)
{
float xOffset = ((reference & Anchor.x0) > 0) ? -scale.X : 0;
float yOffset = ((reference & Anchor.y0) > 0) ? -scale.Y : 0;
Quad selectionQuad = getSurroundingQuad(hitObjects);
//todo: this is not always correct for selections involving sliders. This approximation assumes each point is scaled independently, but sliderends move with the sliderhead.
Quad scaledQuad = new Quad(selectionQuad.TopLeft.X + xOffset, selectionQuad.TopLeft.Y + yOffset, selectionQuad.Width + scale.X, selectionQuad.Height + scale.Y);
//max Size -> playfield bounds
if (scaledQuad.TopLeft.X < 0)
scale.X += scaledQuad.TopLeft.X;
if (scaledQuad.TopLeft.Y < 0)
scale.Y += scaledQuad.TopLeft.Y;
if (scaledQuad.BottomRight.X > DrawWidth)
scale.X -= scaledQuad.BottomRight.X - DrawWidth;
if (scaledQuad.BottomRight.Y > DrawHeight)
scale.Y -= scaledQuad.BottomRight.Y - DrawHeight;
//min Size -> almost 0. Less than 0 causes the quad to flip, exactly 0 causes scaling to get stuck at minimum scale.
Vector2 scaledSize = selectionQuad.Size + scale;
Vector2 minSize = new Vector2(Precision.FLOAT_EPSILON);
scale = Vector2.ComponentMax(minSize, scaledSize) - selectionQuad.Size;
return scale;
}
/// <summary>
/// Returns a gamefield-space quad surrounding the provided hit objects.
/// </summary>
/// <param name="hitObjects">The hit objects to calculate a quad for.</param>
private Quad getSurroundingQuad(OsuHitObject[] hitObjects) =>
GetSurroundingQuad(hitObjects.SelectMany(h =>
{
if (h is IHasPath path)
{
return new[]
{
h.Position,
// can't use EndPosition for reverse slider cases.
h.Position + path.Path.PositionAt(1)
};
}
return new[] { h.Position };
}));
/// <summary>
/// All osu! hitobjects which can be moved/rotated/scaled.
/// </summary>
private OsuHitObject[] selectedMovableObjects => SelectedItems.OfType<OsuHitObject>()
.Where(h => !(h is Spinner))
.ToArray();
}
}
| |
#if !NETFX_CORE
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Text;
using System.Security.Cryptography;
// **************************************************************
// * Raw implementation of the MD5 hash algorithm
// * from RFC 1321.
// *
// * Written By: Reid Borsuk and Jenny Zheng
// * Copyright (c) Microsoft Corporation. All rights reserved.
// **************************************************************
namespace NetworkCommsDotNet.Tools
{
// Simple struct for the (a,b,c,d) which is used to compute the mesage digest.
struct ABCDStruct
{
public uint A;
public uint B;
public uint C;
public uint D;
}
/// <summary>
/// Part of the managed MD5 calculator
/// </summary>
sealed class MD5Core
{
//Prevent CSC from adding a default public constructor
private MD5Core() { }
/// <summary>
/// Return an MD5 hash for the provided parameters
/// </summary>
/// <param name="input"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static byte[] GetHash(string input, Encoding encoding)
{
if (null == input)
throw new System.ArgumentNullException("input", "Unable to calculate hash over null input data");
if (null == encoding)
throw new System.ArgumentNullException("encoding", "Unable to calculate hash over a string without a default encoding. Consider using the GetHash(string) overload to use UTF8 Encoding");
byte[] target = encoding.GetBytes(input);
return GetHash(target);
}
/// <summary>
/// Return an MD5 hash for the provided parameters
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static byte[] GetHash(string input)
{
return GetHash(input, new UTF8Encoding());
}
/// <summary>
/// Return an MD5 hash for the provided parameters
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string GetHashString(byte[] input)
{
if (null == input)
throw new System.ArgumentNullException("input", "Unable to calculate hash over null input data");
string retval = BitConverter.ToString(GetHash(input));
retval = retval.Replace("-", "");
return retval;
}
/// <summary>
/// Return an MD5 hash for the provided parameters
/// </summary>
/// <param name="input"></param>
/// <param name="encoding"></param>
/// <returns></returns>
public static string GetHashString(string input, Encoding encoding)
{
if (null == input)
throw new System.ArgumentNullException("input", "Unable to calculate hash over null input data");
if (null == encoding)
throw new System.ArgumentNullException("encoding", "Unable to calculate hash over a string without a default encoding. Consider using the GetHashString(string) overload to use UTF8 Encoding");
byte[] target = encoding.GetBytes(input);
return GetHashString(target);
}
/// <summary>
/// Return an MD5 hash for the provided parameters
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string GetHashString(string input)
{
return GetHashString(input, new UTF8Encoding());
}
/// <summary>
/// Return an MD5 hash for the provided parameters
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static byte[] GetHash(byte[] input)
{
if (null == input)
throw new System.ArgumentNullException("input", "Unable to calculate hash over null input data");
//Initial values defined in RFC 1321
ABCDStruct abcd = new ABCDStruct();
abcd.A = 0x67452301;
abcd.B = 0xefcdab89;
abcd.C = 0x98badcfe;
abcd.D = 0x10325476;
//We pass in the input array by block, the final block of data must be handled specially for padding & length embedding
int startIndex = 0;
while (startIndex <= input.Length - 64)
{
MD5Core.GetHashBlock(input, ref abcd, startIndex);
startIndex += 64;
}
// The final data block.
return MD5Core.GetHashFinalBlock(input, startIndex, input.Length - startIndex, abcd, (Int64)input.Length * 8);
}
internal static byte[] GetHashFinalBlock(byte[] input, int ibStart, int cbSize, ABCDStruct ABCD, Int64 len)
{
byte[] working = new byte[64];
byte[] length = BitConverter.GetBytes(len);
//Padding is a single bit 1, followed by the number of 0s required to make size congruent to 448 modulo 512. Step 1 of RFC 1321
//The CLR ensures that our buffer is 0-assigned, we don't need to explicitly set it. This is why it ends up being quicker to just
//use a temporary array rather then doing in-place assignment (5% for small inputs)
Array.Copy(input, ibStart, working, 0, cbSize);
working[cbSize] = 0x80;
//We have enough room to store the length in this chunk
if (cbSize < 56)
{
Array.Copy(length, 0, working, 56, 8);
GetHashBlock(working, ref ABCD, 0);
}
else //We need an additional chunk to store the length
{
GetHashBlock(working, ref ABCD, 0);
//Create an entirely new chunk due to the 0-assigned trick mentioned above, to avoid an extra function call clearing the array
working = new byte[64];
Array.Copy(length, 0, working, 56, 8);
GetHashBlock(working, ref ABCD, 0);
}
byte[] output = new byte[16];
Array.Copy(BitConverter.GetBytes(ABCD.A), 0, output, 0, 4);
Array.Copy(BitConverter.GetBytes(ABCD.B), 0, output, 4, 4);
Array.Copy(BitConverter.GetBytes(ABCD.C), 0, output, 8, 4);
Array.Copy(BitConverter.GetBytes(ABCD.D), 0, output, 12, 4);
return output;
}
// Performs a single block transform of MD5 for a given set of ABCD inputs
/* If implementing your own hashing framework, be sure to set the initial ABCD correctly according to RFC 1321:
// A = 0x67452301;
// B = 0xefcdab89;
// C = 0x98badcfe;
// D = 0x10325476;
*/
internal static void GetHashBlock(byte[] input, ref ABCDStruct ABCDValue, int ibStart)
{
uint[] temp = Converter(input, ibStart);
uint a = ABCDValue.A;
uint b = ABCDValue.B;
uint c = ABCDValue.C;
uint d = ABCDValue.D;
a = r1(a, b, c, d, temp[0], 7, 0xd76aa478);
d = r1(d, a, b, c, temp[1], 12, 0xe8c7b756);
c = r1(c, d, a, b, temp[2], 17, 0x242070db);
b = r1(b, c, d, a, temp[3], 22, 0xc1bdceee);
a = r1(a, b, c, d, temp[4], 7, 0xf57c0faf);
d = r1(d, a, b, c, temp[5], 12, 0x4787c62a);
c = r1(c, d, a, b, temp[6], 17, 0xa8304613);
b = r1(b, c, d, a, temp[7], 22, 0xfd469501);
a = r1(a, b, c, d, temp[8], 7, 0x698098d8);
d = r1(d, a, b, c, temp[9], 12, 0x8b44f7af);
c = r1(c, d, a, b, temp[10], 17, 0xffff5bb1);
b = r1(b, c, d, a, temp[11], 22, 0x895cd7be);
a = r1(a, b, c, d, temp[12], 7, 0x6b901122);
d = r1(d, a, b, c, temp[13], 12, 0xfd987193);
c = r1(c, d, a, b, temp[14], 17, 0xa679438e);
b = r1(b, c, d, a, temp[15], 22, 0x49b40821);
a = r2(a, b, c, d, temp[1], 5, 0xf61e2562);
d = r2(d, a, b, c, temp[6], 9, 0xc040b340);
c = r2(c, d, a, b, temp[11], 14, 0x265e5a51);
b = r2(b, c, d, a, temp[0], 20, 0xe9b6c7aa);
a = r2(a, b, c, d, temp[5], 5, 0xd62f105d);
d = r2(d, a, b, c, temp[10], 9, 0x02441453);
c = r2(c, d, a, b, temp[15], 14, 0xd8a1e681);
b = r2(b, c, d, a, temp[4], 20, 0xe7d3fbc8);
a = r2(a, b, c, d, temp[9], 5, 0x21e1cde6);
d = r2(d, a, b, c, temp[14], 9, 0xc33707d6);
c = r2(c, d, a, b, temp[3], 14, 0xf4d50d87);
b = r2(b, c, d, a, temp[8], 20, 0x455a14ed);
a = r2(a, b, c, d, temp[13], 5, 0xa9e3e905);
d = r2(d, a, b, c, temp[2], 9, 0xfcefa3f8);
c = r2(c, d, a, b, temp[7], 14, 0x676f02d9);
b = r2(b, c, d, a, temp[12], 20, 0x8d2a4c8a);
a = r3(a, b, c, d, temp[5], 4, 0xfffa3942);
d = r3(d, a, b, c, temp[8], 11, 0x8771f681);
c = r3(c, d, a, b, temp[11], 16, 0x6d9d6122);
b = r3(b, c, d, a, temp[14], 23, 0xfde5380c);
a = r3(a, b, c, d, temp[1], 4, 0xa4beea44);
d = r3(d, a, b, c, temp[4], 11, 0x4bdecfa9);
c = r3(c, d, a, b, temp[7], 16, 0xf6bb4b60);
b = r3(b, c, d, a, temp[10], 23, 0xbebfbc70);
a = r3(a, b, c, d, temp[13], 4, 0x289b7ec6);
d = r3(d, a, b, c, temp[0], 11, 0xeaa127fa);
c = r3(c, d, a, b, temp[3], 16, 0xd4ef3085);
b = r3(b, c, d, a, temp[6], 23, 0x04881d05);
a = r3(a, b, c, d, temp[9], 4, 0xd9d4d039);
d = r3(d, a, b, c, temp[12], 11, 0xe6db99e5);
c = r3(c, d, a, b, temp[15], 16, 0x1fa27cf8);
b = r3(b, c, d, a, temp[2], 23, 0xc4ac5665);
a = r4(a, b, c, d, temp[0], 6, 0xf4292244);
d = r4(d, a, b, c, temp[7], 10, 0x432aff97);
c = r4(c, d, a, b, temp[14], 15, 0xab9423a7);
b = r4(b, c, d, a, temp[5], 21, 0xfc93a039);
a = r4(a, b, c, d, temp[12], 6, 0x655b59c3);
d = r4(d, a, b, c, temp[3], 10, 0x8f0ccc92);
c = r4(c, d, a, b, temp[10], 15, 0xffeff47d);
b = r4(b, c, d, a, temp[1], 21, 0x85845dd1);
a = r4(a, b, c, d, temp[8], 6, 0x6fa87e4f);
d = r4(d, a, b, c, temp[15], 10, 0xfe2ce6e0);
c = r4(c, d, a, b, temp[6], 15, 0xa3014314);
b = r4(b, c, d, a, temp[13], 21, 0x4e0811a1);
a = r4(a, b, c, d, temp[4], 6, 0xf7537e82);
d = r4(d, a, b, c, temp[11], 10, 0xbd3af235);
c = r4(c, d, a, b, temp[2], 15, 0x2ad7d2bb);
b = r4(b, c, d, a, temp[9], 21, 0xeb86d391);
ABCDValue.A = unchecked(a + ABCDValue.A);
ABCDValue.B = unchecked(b + ABCDValue.B);
ABCDValue.C = unchecked(c + ABCDValue.C);
ABCDValue.D = unchecked(d + ABCDValue.D);
return;
}
//Manually unrolling these equations nets us a 20% performance improvement
private static uint r1(uint a, uint b, uint c, uint d, uint x, int s, uint t)
{
// (b + LSR((a + F(b, c, d) + x + t), s))
//F(x, y, z) ((x & y) | ((x ^ 0xFFFFFFFF) & z))
return unchecked(b + LSR((a + ((b & c) | ((b ^ 0xFFFFFFFF) & d)) + x + t), s));
}
private static uint r2(uint a, uint b, uint c, uint d, uint x, int s, uint t)
{
// (b + LSR((a + G(b, c, d) + x + t), s))
//G(x, y, z) ((x & z) | (y & (z ^ 0xFFFFFFFF)))
return unchecked(b + LSR((a + ((b & d) | (c & (d ^ 0xFFFFFFFF))) + x + t), s));
}
private static uint r3(uint a, uint b, uint c, uint d, uint x, int s, uint t)
{
// (b + LSR((a + H(b, c, d) + k + i), s))
//H(x, y, z) (x ^ y ^ z)
return unchecked(b + LSR((a + (b ^ c ^ d) + x + t), s));
}
private static uint r4(uint a, uint b, uint c, uint d, uint x, int s, uint t)
{
// (b + LSR((a + I(b, c, d) + k + i), s))
//I(x, y, z) (y ^ (x | (z ^ 0xFFFFFFFF)))
return unchecked(b + LSR((a + (c ^ (b | (d ^ 0xFFFFFFFF))) + x + t), s));
}
// Implementation of left rotate
// s is an int instead of a uint because the CLR requires the argument passed to >>/<< is of
// type int. Doing the demoting inside this function would add overhead.
private static uint LSR(uint i, int s)
{
return ((i << s) | (i >> (32 - s)));
}
//Convert input array into array of UInts
private static uint[] Converter(byte[] input, int ibStart)
{
if (null == input)
throw new System.ArgumentNullException("input", "Unable convert null array to array of uInts");
uint[] result = new uint[16];
for (int i = 0; i < 16; i++)
{
result[i] = (uint)input[ibStart + i * 4];
result[i] += (uint)input[ibStart + i * 4 + 1] << 8;
result[i] += (uint)input[ibStart + i * 4 + 2] << 16;
result[i] += (uint)input[ibStart + i * 4 + 3] << 24;
}
return result;
}
}
#if SILVERLIGHT
/// <summary>
/// Create a managed MD5 hash calculator
/// </summary>
public class MD5Managed : HashAlgorithm
#else
/// <summary>
/// Create a managed MD5 hash calculator
/// </summary>
public class MD5Managed : System.Security.Cryptography.MD5
#endif
{
private byte[] _data;
private ABCDStruct _abcd;
private Int64 _totalLength;
private int _dataSize;
/// <summary>
/// Create a new instance of the MD5 hash calculator
/// </summary>
public MD5Managed()
{
base.HashSizeValue = 0x80;
this.Initialize();
}
/// <summary>
/// Initialise the MD5 hash calculator
/// </summary>
public override void Initialize()
{
_data = new byte[64];
_dataSize = 0;
_totalLength = 0;
_abcd = new ABCDStruct();
//Initial values as defined in RFC 1321
_abcd.A = 0x67452301;
_abcd.B = 0xefcdab89;
_abcd.C = 0x98badcfe;
_abcd.D = 0x10325476;
}
/// <summary>
/// Calculate the core hash
/// </summary>
/// <param name="array"></param>
/// <param name="ibStart"></param>
/// <param name="cbSize"></param>
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
int startIndex = ibStart;
int totalArrayLength = _dataSize + cbSize;
if (totalArrayLength >= 64)
{
Array.Copy(array, startIndex, _data, _dataSize, 64 - _dataSize);
// Process message of 64 bytes (512 bits)
MD5Core.GetHashBlock(_data, ref _abcd, 0);
startIndex += 64 - _dataSize;
totalArrayLength -= 64;
while (totalArrayLength >= 64)
{
Array.Copy(array, startIndex, _data, 0, 64);
MD5Core.GetHashBlock(array, ref _abcd, startIndex);
totalArrayLength -= 64;
startIndex += 64;
}
_dataSize = totalArrayLength;
Array.Copy(array, startIndex, _data, 0, totalArrayLength);
}
else
{
Array.Copy(array, startIndex, _data, _dataSize, cbSize);
_dataSize = totalArrayLength;
}
_totalLength += cbSize;
}
/// <summary>
/// Get the final hash
/// </summary>
/// <returns></returns>
protected override byte[] HashFinal()
{
base.HashValue = MD5Core.GetHashFinalBlock(_data, 0, _dataSize, _abcd, _totalLength * 8);
return base.HashValue;
}
}
}
#endif
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Redis
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Operations operations.
/// </summary>
internal partial class Operations : IServiceOperations<RedisManagementClient>, IOperations
{
/// <summary>
/// Initializes a new instance of the Operations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal Operations(RedisManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RedisManagementClient
/// </summary>
public RedisManagementClient Client { get; private set; }
/// <summary>
/// Lists all of the available REST API operations of the Microsoft.Cache
/// provider.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Operation>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Headers.TryAddWithoutValidation("redirect", "true");
_httpRequest.Method = new HttpMethod("Operations_List");
_httpRequest.RequestUri = new System.Uri("https://bogus");
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
var @params = new Dictionary<string, object>
{
{ "subscriptionId", Client.SubscriptionId },
};
string _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(@params, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Operation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
return _result;
}
/// <summary>
/// Lists all of the available REST API operations of the Microsoft.Cache
/// provider.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Operation>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Headers.TryAddWithoutValidation("redirect", "true");
_httpRequest.Method = new HttpMethod("Operations_List");
_httpRequest.RequestUri = new System.Uri("https://bogus");
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
var @params = new Dictionary<string, object>
{
{ "subscriptionId", Client.SubscriptionId },
{ "nextPageLink", nextPageLink },
};
string _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(@params, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Operation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Internal.Reflection.Core.Execution.Binder;
using Internal.Reflection.Extensions.NonPortable;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace System.Reflection
{
/// <summary>
/// Extension methods offering source-code compatibility with certain instance methods of <see cref="System.Type"/> on other platforms.
/// </summary>
public static class TypeExtensions
{
/// <summary>
/// Searches for a public instance constructor whose parameters match the types in the specified array.
/// </summary>
/// <param name="type">Type from which to get constructor</param>
/// <param name="types"> An array of Type objects representing the number, order, and type of the parameters for the desired constructor.
/// -or-
/// An empty array of Type objects, to get a constructor that takes no parameters. Such an empty array is provided by the Array.Empty method. </param>
/// <returns>Specific ConstructorInfo for type specified in "type" parameter</returns>
public static ConstructorInfo GetConstructor(this Type type, Type[] types)
{
if (types == null)
{
throw new ArgumentNullException(nameof(types));
}
GetTypeInfoOrThrow(type);
IEnumerable<ConstructorInfo> constructors = MemberEnumerator.GetMembers<ConstructorInfo>(type, MemberEnumerator.AnyName, Helpers.DefaultLookup);
return Disambiguate(constructors, types);
}
/// <summary>
/// Returns all the public constructors defined for the current Type.
/// </summary>
/// <param name="type">Type to retrieve constructors for</param>
/// <returns>An array of ConstructorInfo objects representing all the public instance constructors defined for the current Type, but not including the type initializer (static constructor). If no public instance constructors are defined for the current Type, or if the current Type represents a type parameter in the definition of a generic type or generic method, an empty array of type ConstructorInfo is returned.</returns>
public static ConstructorInfo[] GetConstructors(this Type type)
{
return GetConstructors(type, Helpers.DefaultLookup);
}
/// <summary>
/// Searches for the constructors defined for the current Type, using the specified BindingFlags.
/// </summary>
/// <param name="type">Type to retrieve constructors for</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
/// -or-
/// Zero, to return null. </param>
/// <returns>An array of ConstructorInfo objects representing all constructors defined for the current Type that match the specified binding constraints, including the type initializer if it is defined. Returns an empty array of type ConstructorInfo if no constructors are defined for the current Type, if none of the defined constructors match the binding constraints, or if the current Type represents a type parameter in the definition of a generic type or generic method.</returns>
public static ConstructorInfo[] GetConstructors(this Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<ConstructorInfo> constructors = type.GetMembers<ConstructorInfo>(MemberEnumerator.AnyName, bindingAttr);
return constructors.ToArray();
}
/// <summary>
/// Searches for the members defined for the current Type whose DefaultMemberAttribute is set.
/// </summary>
/// <param name="type">Type to be queried</param>
/// <returns>An array of MemberInfo objects representing all default members of the current Type.
/// -or-
/// An empty array of type MemberInfo, if the current Type does not have default members.</returns>
public static MemberInfo[] GetDefaultMembers(this Type type)
{
TypeInfo typeInfo = GetTypeInfoOrThrow(type);
string defaultMemberName = GetDefaultMemberName(typeInfo);
if (defaultMemberName == null)
{
return Array.Empty<MemberInfo>();
}
return GetMember(type, defaultMemberName);
}
/// <summary>
/// Returns the EventInfo object representing the specified public event.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of an event that is declared or inherited by the current Type. </param>
/// <returns>The object representing the specified public event that is declared or inherited by the current Type, if found; otherwise, null.</returns>
public static EventInfo GetEvent(this Type type, string name)
{
return GetEvent(type, name, Helpers.DefaultLookup);
}
/// <summary>
/// Returns the EventInfo object representing the specified event, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of an event which is declared or inherited by the current Type. </param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
/// -or-
/// Zero, to return null. </param>
/// <returns>The object representing the specified event that is declared or inherited by the current Type, if found; otherwise, null.</returns>
public static EventInfo GetEvent(this Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<EventInfo> events = MemberEnumerator.GetMembers<EventInfo>(type, name, bindingAttr);
return Disambiguate(events);
}
/// <summary>
/// Returns all the public events that are declared or inherited by the current Type.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <returns>An array of EventInfo objects representing all the public events which are declared or inherited by the current Type.
/// -or-
/// An empty array of type EventInfo, if the current Type does not have public events.</returns>
public static EventInfo[] GetEvents(this Type type)
{
return GetEvents(type, Helpers.DefaultLookup);
}
/// <summary>
/// Searches for events that are declared or inherited by the current Type, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
/// -or-
/// Zero, to return null. </param>
/// <returns>An array of EventInfo objects representing all events that are declared or inherited by the current Type that match the specified binding constraints.
/// -or-
/// An empty array of type EventInfo, if the current Type does not have events, or if none of the events match the binding constraints.</returns>
public static EventInfo[] GetEvents(this Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<EventInfo> events = MemberEnumerator.GetMembers<EventInfo>(type, MemberEnumerator.AnyName, bindingAttr);
return events.ToArray();
}
/// <summary>
/// Searches for the public field with the specified name.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the data field to get. </param>
/// <returns>An object representing the public field with the specified name, if found; otherwise, null.</returns>
public static FieldInfo GetField(this Type type, string name)
{
return GetField(type, name, Helpers.DefaultLookup);
}
/// <summary>
/// Searches for the specified field, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the data field to get. </param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
/// -or-
/// Zero, to return null.</param>
/// <returns>An object representing the field that matches the specified requirements, if found; otherwise, null.</returns>
public static FieldInfo GetField(this Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<FieldInfo> fields = MemberEnumerator.GetMembers<FieldInfo>(type, name, bindingAttr);
return Disambiguate(fields);
}
/// <summary>
/// Returns all the public fields of the current Type.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <returns>An array of FieldInfo objects representing all the public fields defined for the current Type.
/// -or-
/// An empty array of type FieldInfo, if no public fields are defined for the current Type.</returns>
public static FieldInfo[] GetFields(this Type type)
{
return GetFields(type, Helpers.DefaultLookup);
}
/// <summary>
/// Searches for the fields defined for the current Type, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return an empty array. </param>
/// <returns>An array of FieldInfo objects representing all fields defined for the current Type that match the specified binding constraints.
/// -or-
/// An empty array of type FieldInfo, if no fields are defined for the current Type, or if none of the defined fields match the binding constraints.</returns>
public static FieldInfo[] GetFields(this Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
return MemberEnumerator.GetMembers<FieldInfo>(type, MemberEnumerator.AnyName, bindingAttr).ToArray();
}
/// <summary>
/// Returns an array of Type objects that represent the type arguments of a generic type or the type parameters of a generic type definition
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <returns>An array of Type objects that represent the type arguments of a generic type. Returns an empty array if the current type is not a generic type.</returns>
public static Type[] GetGenericArguments(this Type type)
{
TypeInfo typeInfo = GetTypeInfoOrThrow(type);
if (type.IsConstructedGenericType)
{
return type.GenericTypeArguments;
}
if (typeInfo.IsGenericTypeDefinition)
{
return typeInfo.GenericTypeParameters;
}
return Array.Empty<Type>();
}
/// <summary>
/// Gets all the interfaces implemented or inherited by the current Type.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <returns>An array of Type objects representing all the interfaces implemented or inherited by the current Type.
/// -or-
/// An empty array of type Type, if no interfaces are implemented or inherited by the current Type.</returns>
public static Type[] GetInterfaces(this Type type)
{
TypeInfo typeInfo = GetTypeInfoOrThrow(type);
return typeInfo.ImplementedInterfaces.ToArray();
}
/// <summary>
/// Searches for the public members with the specified name.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the public members to get.</param>
/// <returns>An array of MemberInfo objects representing the public members with the specified name, if found; otherwise, an empty array.</returns>
public static MemberInfo[] GetMember(this Type type, string name)
{
return GetMember(type, name, Helpers.DefaultLookup);
}
/// <summary>
/// Searches for the public members with the specified name.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name"> The string containing the name of the public members to get. </param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return an empty array. </param>
/// <returns>An array of MemberInfo objects representing the public members with the specified name, if found; otherwise, an empty array.</returns>
public static MemberInfo[] GetMember(this Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
LowLevelList<MemberInfo> members = GetMembers(type, name, bindingAttr);
return members.ToArray();
}
/// <summary>
/// Returns all the public members of the current Type.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <returns>An array of MemberInfo objects representing all the public members of the current Type
/// -or-
/// An empty array of type MemberInfo, if the current Type does not have public members.</returns>
public static MemberInfo[] GetMembers(this Type type)
{
return GetMembers(type, Helpers.DefaultLookup);
}
/// <summary>
/// Searches for the members defined for the current Type, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return an empty array. </param>
/// <returns>An array of MemberInfo objects representing all members defined for the current Type that match the specified binding constraints.
/// -or-
/// An empty array of type MemberInfo, if no members are defined for the current Type, or if none of the defined members match the binding constraints.</returns>
public static MemberInfo[] GetMembers(this Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
LowLevelList<MemberInfo> members = GetMembers(type, MemberEnumerator.AnyName, bindingAttr);
return members.ToArray();
}
/// <summary>
/// Searches for the public method with the specified name.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the public method to get. </param>
/// <returns>An object that represents the public method with the specified name, if found; otherwise, null</returns>
public static MethodInfo GetMethod(this Type type, string name)
{
return GetMethod(type, name, Helpers.DefaultLookup);
}
/// <summary>
/// Searches for the specified method, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the method to get.</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return null. </param>
/// <returns>An object representing the method that matches the specified requirements, if found; otherwise, null.</returns>
public static MethodInfo GetMethod(this Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<MethodInfo> methods = MemberEnumerator.GetMembers<MethodInfo>(type, name, bindingAttr);
return Disambiguate(methods);
}
/// <summary>
/// Searches for the specified public method whose parameters match the specified argument types.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the public method to get. </param>
/// <param name="types">An array of Type objects representing the number, order, and type of the parameters for the method to get
/// -or- An empty array of Type objects (as provided by the Array.Empty method) to get a method that takes no parameters. </param>
/// <returns>An object representing the public method whose parameters match the specified argument types, if found; otherwise, null.</returns>
public static MethodInfo GetMethod(this Type type, string name, Type[] types)
{
if (types == null)
{
throw new ArgumentNullException(nameof(types));
}
GetTypeInfoOrThrow(type);
IEnumerable<MethodInfo> methods = MemberEnumerator.GetMembers<MethodInfo>(type, name, Helpers.DefaultLookup);
return Disambiguate(methods, types);
}
/// <summary>
/// Returns all the public methods of the current Type.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <returns>An array of MethodInfo objects representing all the public methods defined for the current Type.
/// -or-
/// An empty array of type MethodInfo, if no public methods are defined for the current Type.</returns>
public static MethodInfo[] GetMethods(this Type type)
{
return GetMethods(type, Helpers.DefaultLookup);
}
/// <summary>
/// Returns all the public methods of the current Type.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return an empty array. </param>
/// <returns>An array of MethodInfo objects representing all the public methods defined for the current Type
/// -or-
/// An empty array of type MethodInfo, if no public methods are defined for the current Type.</returns>
public static MethodInfo[] GetMethods(this Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<MethodInfo> methods = MemberEnumerator.GetMembers<MethodInfo>(type, MemberEnumerator.AnyName, bindingAttr);
return methods.ToArray();
}
/// <summary>
/// Searches for the specified nested type, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the nested type to get. </param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted
/// -or-
/// Zero, to return null. </param>
/// <returns>An object representing the nested type that matches the specified requirements, if found; otherwise, null.</returns>
public static Type GetNestedType(this Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<TypeInfo> nestedTypes = MemberEnumerator.GetMembers<TypeInfo>(type, name, bindingAttr);
TypeInfo nestedType = Disambiguate(nestedTypes);
return nestedType == null ? null : nestedType.AsType();
}
/// <summary>
/// Searches for the types nested in the current Type, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted -or- Zero, to return null. </param>
/// <returns>An array of Type objects representing all the types nested in the current Type that match the specified binding constraints (the search is not recursive), or an empty array of type Type, if no nested types are found that match the binding constraints.</returns>
public static Type[] GetNestedTypes(this Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<TypeInfo> types = MemberEnumerator.GetMembers<TypeInfo>(type, MemberEnumerator.AnyName, bindingAttr);
return types.Select(t => t.AsType()).ToArray();
}
/// <summary>
/// Returns all the public properties of the current Type.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <returns>An array of PropertyInfo objects representing all public properties of the current Type -or- An empty array of type PropertyInfo, if the current Type does not have public properties</returns>
public static PropertyInfo[] GetProperties(this Type type)
{
return GetProperties(type, Helpers.DefaultLookup);
}
/// <summary>
/// Searches for the properties of the current Type, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted -or- Zero, to return null. </param>
/// <returns>An array of PropertyInfo objects representing all properties of the current Type that match the specified binding constraints.
/// -or-
/// An empty array of type PropertyInfo, if the current Type does not have properties, or if none of the properties match the binding constraints.</returns>
public static PropertyInfo[] GetProperties(this Type type, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<PropertyInfo> properties = MemberEnumerator.GetMembers<PropertyInfo>(type, MemberEnumerator.AnyName, bindingAttr);
return properties.ToArray();
}
/// <summary>
/// Searches for the public property with the specified name.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the public property to get. </param>
/// <returns>An object representing the public property with the specified name, if found; otherwise, null.</returns>
public static PropertyInfo GetProperty(this Type type, string name)
{
return GetProperty(type, name, Helpers.DefaultLookup);
}
/// <summary>
/// Searches for the specified property, using the specified binding constraints.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the property to get. </param>
/// <param name="bindingAttr">A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
/// -or-
/// Zero, to return null. </param>
/// <returns>A bitmask comprised of one or more BindingFlags that specify how the search is conducted.
/// -or-
/// Zero, to return null. </returns>
public static PropertyInfo GetProperty(this Type type, string name, BindingFlags bindingAttr)
{
GetTypeInfoOrThrow(type);
IEnumerable<PropertyInfo> properties = MemberEnumerator.GetMembers<PropertyInfo>(type, name, bindingAttr);
return Disambiguate(properties);
}
/// <summary>
/// Searches for the public property with the specified name and return type.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the public property to get. </param>
/// <param name="returnType">The return type of the property. </param>
/// <returns>An object representing the public property with the specified name, if found; otherwise, null</returns>
public static PropertyInfo GetProperty(this Type type, string name, Type returnType)
{
return GetProperty(type, name, returnType, Array.Empty<Type>());
}
/// <summary>
/// Searches for the specified public property whose parameters match the specified argument types.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="name">The string containing the name of the public property to get. </param>
/// <param name="returnType">The return type of the property. </param>
/// <param name="types">
/// An array of Type objects representing the number, order, and type of the parameters for the indexed property to get.
/// -or-
/// An empty array of the type Type (that is, Type[] types = new Type[0]) to get a property that is not indexed.
/// </param>
/// <returns>
/// An object representing the public property with the specified name, return type, and indexing types, if found; otherwise, null.
/// </returns>
public static PropertyInfo GetProperty(this Type type, string name, Type returnType, Type[] types)
{
if (types == null)
{
throw new ArgumentNullException(nameof(types));
}
GetTypeInfoOrThrow(type);
IEnumerable<PropertyInfo> properties = MemberEnumerator.GetMembers<PropertyInfo>(type, name, Helpers.DefaultLookup);
return Disambiguate(properties, returnType, types);
}
/// <summary>
/// Determines whether an instance of the current Type can be assigned from an instance of the specified Type.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="c">The type to compare with the current type. </param>
/// <returns>true if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c, or if c represents a value type and the current Type represents Nullable<c> (Nullable(Of c) in Visual Basic). false if none of these conditions are true, or if c is null.</returns>
public static bool IsAssignableFrom(this Type type, Type c)
{
TypeInfo typeInfo = GetTypeInfoOrThrow(type);
return c != null && typeInfo.IsAssignableFrom(GetTypeInfoOrThrow(c, "c"));
}
/// <summary>
/// Determines whether the specified object is an instance of the current Type.
/// </summary>
/// <param name="type">Type on which to perform lookup</param>
/// <param name="o">The object to compare with the current type</param>
/// <returns>true if the current Type is in the inheritance hierarchy of the object represented by o, or if the current Type is an interface that o supports. false if neither of these conditions is the case, or if o is null, or if the current Type is an open generic type (that is, ContainsGenericParameters returns true).</returns>
public static bool IsInstanceOfType(this Type type, object o)
{
Debug.Assert(o == null || o.GetType().GetTypeInfo() != null, "Type obtained from object instance should implement IReflectableType on all platforms that support reflection.");
return o != null && IsAssignableFrom(type, o.GetType());
}
private static LowLevelList<MemberInfo> GetMembers(Type type, object nameFilterOrAnyName, BindingFlags bindingAttr)
{
LowLevelList<MemberInfo> members = new LowLevelList<MemberInfo>();
members.AddRange(MemberEnumerator.GetMembers<MethodInfo>(type, nameFilterOrAnyName, bindingAttr));
members.AddRange(MemberEnumerator.GetMembers<ConstructorInfo>(type, nameFilterOrAnyName, bindingAttr));
members.AddRange(MemberEnumerator.GetMembers<PropertyInfo>(type, nameFilterOrAnyName, bindingAttr));
members.AddRange(MemberEnumerator.GetMembers<EventInfo>(type, nameFilterOrAnyName, bindingAttr));
members.AddRange(MemberEnumerator.GetMembers<FieldInfo>(type, nameFilterOrAnyName, bindingAttr));
members.AddRange(MemberEnumerator.GetMembers<TypeInfo>(type, nameFilterOrAnyName, bindingAttr));
return members;
}
private static string GetDefaultMemberName(TypeInfo typeInfo)
{
TypeInfo t = typeInfo;
while (t != null)
{
CustomAttributeData attribute = GetDefaultMemberAttribute(typeInfo);
if (attribute != null)
{
// NOTE: Neither indexing nor cast can fail here. Any attempt to use fewer than 1 argument
// or a non-string argument would correctly trigger MissingMethodException before
// we reach here as that would be an attempt to reference a non-existent DefaultMemberAttribute
// constructor.
Debug.Assert(attribute.ConstructorArguments.Count == 1 && attribute.ConstructorArguments[0].Value is string);
return (string)attribute.ConstructorArguments[0].Value;
}
Type baseType = t.BaseType;
if (baseType == null)
{
break;
}
t = baseType.GetTypeInfo();
}
return null;
}
private static CustomAttributeData GetDefaultMemberAttribute(TypeInfo typeInfo)
{
foreach (CustomAttributeData attribute in typeInfo.CustomAttributes)
{
if (attribute.AttributeType == typeof(DefaultMemberAttribute))
{
return attribute;
}
}
return null;
}
private static TypeInfo GetTypeInfoOrThrow(Type type, string parameterName = "type")
{
Requires.NotNull(type, parameterName);
TypeInfo typeInfo = type.GetTypeInfo();
if (typeInfo == null)
{
throw new ArgumentException(SR.TypeIsNotReflectable, parameterName);
}
return typeInfo;
}
private static T Disambiguate<T>(IEnumerable<T> members) where T : MemberInfo
{
IEnumerator<T> enumerator = members.GetEnumerator();
if (!enumerator.MoveNext())
{
return null;
}
T result = enumerator.Current;
if (!enumerator.MoveNext())
{
return result;
}
T anotherResult = enumerator.Current;
if (anotherResult.DeclaringType.Equals(result.DeclaringType))
{
throw new AmbiguousMatchException();
}
return result;
}
private static T Disambiguate<T>(IEnumerable<T> members, Type[] parameterTypes) where T : MethodBase
{
return (T)DefaultBinder.SelectMethod(members.ToArray(), parameterTypes);
}
private static PropertyInfo Disambiguate(IEnumerable<PropertyInfo> members, Type returnType, Type[] parameterTypes)
{
PropertyInfo[] memberArray = members.ToArray();
if(memberArray.Length == 0)
{
return null;
}
return DefaultBinder.SelectProperty(memberArray, returnType, parameterTypes);
}
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
namespace FluentValidation {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Internal;
using Results;
using Validators;
/// <summary>
/// Base class for entity validator classes.
/// </summary>
/// <typeparam name="T">The type of the object being validated</typeparam>
public abstract class AbstractValidator<T> : IValidator<T>, IEnumerable<IValidationRule> {
readonly TrackingCollection<IValidationRule> nestedValidators = new TrackingCollection<IValidationRule>();
// Work-around for reflection bug in .NET 4.5
static Func<CascadeMode> s_cascadeMode = () => ValidatorOptions.CascadeMode;
Func<CascadeMode> cascadeMode = s_cascadeMode;
/// <summary>
/// Sets the cascade mode for all rules within this validator.
/// </summary>
public CascadeMode CascadeMode {
get { return cascadeMode(); }
set { cascadeMode = () => value; }
}
ValidationResult IValidator.Validate(object instance) {
instance.Guard("Cannot pass null to Validate.");
if(! ((IValidator)this).CanValidateInstancesOfType(instance.GetType())) {
throw new InvalidOperationException(string.Format("Cannot validate instances of type '{0}'. This validator can only validate instances of type '{1}'.", instance.GetType().Name, typeof(T).Name));
}
return Validate((T)instance);
}
Task<ValidationResult> IValidator.ValidateAsync(object instance) {
instance.Guard("Cannot pass null to Validate.");
if (!((IValidator) this).CanValidateInstancesOfType(instance.GetType())) {
throw new InvalidOperationException(string.Format("Cannot validate instances of type '{0}'. This validator can only validate instances of type '{1}'.", instance.GetType().Name, typeof (T).Name));
}
return ValidateAsync((T) instance);
}
ValidationResult IValidator.Validate(ValidationContext context)
{
context.Guard("Cannot pass null to Validate");
var newContext = new ValidationContext<T>((T)context.InstanceToValidate, context.PropertyChain, context.Selector) {
IsChildContext = context.IsChildContext
};
return Validate(newContext);
}
Task<ValidationResult> IValidator.ValidateAsync(ValidationContext context) {
context.Guard("Cannot pass null to Validate");
var newContext = new ValidationContext<T>((T) context.InstanceToValidate, context.PropertyChain, context.Selector) {
IsChildContext = context.IsChildContext
};
return ValidateAsync(newContext);
}
/// <summary>
/// Validates the specified instance
/// </summary>
/// <param name="instance">The object to validate</param>
/// <returns>A ValidationResult object containing any validation failures</returns>
public virtual ValidationResult Validate(T instance) {
return Validate(new ValidationContext<T>(instance, new PropertyChain(), new DefaultValidatorSelector()));
}
/// <summary>
/// Validates the specified instance asynchronously
/// </summary>
/// <param name="instance">The object to validate</param>
/// <returns>A ValidationResult object containing any validation failures</returns>
public Task<ValidationResult> ValidateAsync(T instance) {
return ValidateAsync(new ValidationContext<T>(instance, new PropertyChain(), new DefaultValidatorSelector()));
}
/// <summary>
/// Validates the specified instance.
/// </summary>
/// <param name="context">Validation Context</param>
/// <returns>A ValidationResult object containing any validation failures.</returns>
public virtual ValidationResult Validate(ValidationContext<T> context) {
context.Guard("Cannot pass null to Validate");
var failures = nestedValidators.SelectMany(x => x.Validate(context)).ToList();
return new ValidationResult(failures);
}
/// <summary>
/// Validates the specified instance asynchronously.
/// </summary>
/// <param name="context">Validation Context</param>
/// <returns>A ValidationResult object containing any validation failures.</returns>
public virtual Task<ValidationResult> ValidateAsync(ValidationContext<T> context) {
context.Guard("Cannot pass null to Validate");
var failures = new List<ValidationFailure>();
return TaskHelpers.Iterate(
nestedValidators
.Select(v => v.ValidateAsync(context).Then(fs => failures.AddRange(fs), runSynchronously: true)))
.Then(() => new ValidationResult(failures)
);
}
/// <summary>
/// Adds a rule to the current validator.
/// </summary>
/// <param name="rule"></param>
public void AddRule(IValidationRule rule) {
nestedValidators.Add(rule);
}
/// <summary>
/// Creates a <see cref="IValidatorDescriptor" /> that can be used to obtain metadata about the current validator.
/// </summary>
public virtual IValidatorDescriptor CreateDescriptor() {
return new ValidatorDescriptor<T>(nestedValidators);
}
bool IValidator.CanValidateInstancesOfType(Type type) {
return typeof(T).IsAssignableFrom(type);
}
/// <summary>
/// Defines a validation rule for a specify property.
/// </summary>
/// <example>
/// RuleFor(x => x.Surname)...
/// </example>
/// <typeparam name="TProperty">The type of property being validated</typeparam>
/// <param name="expression">The expression representing the property to validate</param>
/// <returns>an IRuleBuilder instance on which validators can be defined</returns>
public IRuleBuilderInitial<T, TProperty> RuleFor<TProperty>(Expression<Func<T, TProperty>> expression) {
expression.Guard("Cannot pass null to RuleFor");
var rule = PropertyRule.Create(expression, () => CascadeMode);
AddRule(rule);
var ruleBuilder = new RuleBuilder<T, TProperty>(rule);
return ruleBuilder;
}
public IRuleBuilderInitial<T, TProperty> RuleForEach<TProperty>(Expression<Func<T, IEnumerable<TProperty>>> expression) {
expression.Guard("Cannot pass null to RuleForEach");
var rule = CollectionPropertyRule<TProperty>.Create(expression, () => CascadeMode);
AddRule(rule);
var ruleBuilder = new RuleBuilder<T, TProperty>(rule);
return ruleBuilder;
}
/// <summary>
/// Defines a custom validation rule using a lambda expression.
/// If the validation rule fails, it should return a instance of a <see cref="ValidationFailure">ValidationFailure</see>
/// If the validation rule succeeds, it should return null.
/// </summary>
/// <param name="customValidator">A lambda that executes custom validation rules.</param>
public void Custom(Func<T, ValidationFailure> customValidator) {
customValidator.Guard("Cannot pass null to Custom");
AddRule(new DelegateValidator<T>(x => new[] { customValidator(x) }));
}
/// <summary>
/// Defines a custom validation rule using a lambda expression.
/// If the validation rule fails, it should return an instance of <see cref="ValidationFailure">ValidationFailure</see>
/// If the validation rule succeeds, it should return null.
/// </summary>
/// <param name="customValidator">A lambda that executes custom validation rules</param>
public void Custom(Func<T, ValidationContext<T>, ValidationFailure> customValidator) {
customValidator.Guard("Cannot pass null to Custom");
AddRule(new DelegateValidator<T>((x, ctx) => new[] { customValidator(x, ctx) }));
}
/// <summary>
/// Defines a custom asynchronous validation rule using a lambda expression.
/// If the validation rule fails, it should asynchronously return a instance of a <see cref="ValidationFailure">ValidationFailure</see>
/// If the validation rule succeeds, it should return null.
/// </summary>
/// <param name="customValidator">A lambda that executes custom validation rules.</param>
public void CustomAsync(Func<T, Task<ValidationFailure>> customValidator) {
customValidator.Guard("Cannot pass null to Custom");
AddRule(new DelegateValidator<T>(x => customValidator(x).Then(f => new[] {f}.AsEnumerable(), runSynchronously: true)));
}
/// <summary>
/// Defines a custom asynchronous validation rule using a lambda expression.
/// If the validation rule fails, it should asynchronously return an instance of <see cref="ValidationFailure">ValidationFailure</see>
/// If the validation rule succeeds, it should return null.
/// </summary>
/// <param name="customValidator">A lambda that executes custom validation rules</param>
public void CustomAsync(Func<T, ValidationContext<T>, Task<ValidationFailure>> customValidator) {
customValidator.Guard("Cannot pass null to Custom");
AddRule(new DelegateValidator<T>((x, ctx) => customValidator(x, ctx).Then(f => new[] {f}.AsEnumerable(), runSynchronously: true)));
}
/// <summary>
/// Defines a RuleSet that can be used to group together several validators.
/// </summary>
/// <param name="ruleSetName">The name of the ruleset.</param>
/// <param name="action">Action that encapsulates the rules in the ruleset.</param>
public void RuleSet(string ruleSetName, Action action) {
ruleSetName.Guard("A name must be specified when calling RuleSet.");
action.Guard("A ruleset definition must be specified when calling RuleSet.");
using (nestedValidators.OnItemAdded(r => r.RuleSet = ruleSetName)) {
action();
}
}
/// <summary>
/// Defines a condition that applies to several rules
/// </summary>
/// <param name="predicate">The condition that should apply to multiple rules</param>
/// <param name="action">Action that encapsulates the rules.</param>
/// <returns></returns>
public void When(Func<T, bool> predicate, Action action) {
var propertyRules = new List<IValidationRule>();
Action<IValidationRule> onRuleAdded = propertyRules.Add;
using(nestedValidators.OnItemAdded(onRuleAdded)) {
action();
}
// Must apply the predictae after the rule has been fully created to ensure any rules-specific conditions have already been applied.
propertyRules.ForEach(x => x.ApplyCondition(predicate.CoerceToNonGeneric()));
}
/// <summary>
/// Defiles an inverse condition that applies to several rules
/// </summary>
/// <param name="predicate">The condition that should be applied to multiple rules</param>
/// <param name="action">Action that encapsulates the rules</param>
public void Unless(Func<T, bool> predicate, Action action) {
When(x => !predicate(x), action);
}
/// <summary>
/// Returns an enumerator that iterates through the collection of validation rules.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>1</filterpriority>
public IEnumerator<IValidationRule> GetEnumerator() {
return nestedValidators.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
}
| |
//! \file ImagePreview.cs
//! \date Sun Jul 06 06:34:56 2014
//! \brief preview images.
//
// Copyright (C) 2014-2018 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using GARbro.GUI.Strings;
using GARbro.GUI.Properties;
using GameRes;
using System.Text;
using System.Windows.Documents;
using System.Windows.Media;
using System.Globalization;
namespace GARbro.GUI
{
public partial class MainWindow : Window
{
private readonly BackgroundWorker m_preview_worker = new BackgroundWorker();
private PreviewFile m_current_preview = new PreviewFile();
private bool m_preview_pending = false;
private UIElement m_active_viewer;
public UIElement ActiveViewer
{
get { return m_active_viewer; }
set
{
if (value == m_active_viewer)
return;
m_active_viewer = value;
m_active_viewer.Visibility = Visibility.Visible;
bool exists = false;
foreach (UIElement c in PreviewPane.Children)
{
if (c != m_active_viewer)
c.Visibility = Visibility.Collapsed;
else
exists = true;
}
if (!exists)
PreviewPane.Children.Add (m_active_viewer);
}
}
class PreviewFile
{
public IEnumerable<string> Path { get; set; }
public string Name { get; set; }
public Entry Entry { get; set; }
public bool IsEqual (IEnumerable<string> path, string name)
{
return Path != null && path.SequenceEqual (Path) && name.Equals (Name);
}
}
private void InitPreviewPane ()
{
m_preview_worker.DoWork += (s, e) => LoadPreviewImage (e.Argument as PreviewFile);
m_preview_worker.RunWorkerCompleted += (s, e) => {
if (m_preview_pending)
RefreshPreviewPane();
};
ActiveViewer = ImageView;
TextView.IsWordWrapEnabled = true;
}
private IEnumerable<Encoding> m_encoding_list = GetEncodingList();
public IEnumerable<Encoding> TextEncodings { get { return m_encoding_list; } }
internal static IEnumerable<Encoding> GetEncodingList (bool exclude_utf16 = false)
{
var list = new HashSet<Encoding>();
try
{
list.Add(Encoding.Default);
var oem = CultureInfo.CurrentCulture.TextInfo.OEMCodePage;
list.Add(Encoding.GetEncoding(oem));
}
catch (Exception X)
{
if (X is ArgumentException || X is NotSupportedException)
list.Add(Encoding.GetEncoding(20127)); //default to US-ASCII
else
throw;
}
list.Add (Encoding.GetEncoding (932));
list.Add (Encoding.GetEncoding (936));
list.Add (Encoding.UTF8);
if (!exclude_utf16)
{
list.Add (Encoding.Unicode);
list.Add (Encoding.BigEndianUnicode);
}
return list;
}
private void OnEncodingSelect (object sender, SelectionChangedEventArgs e)
{
var enc = this.EncodingChoice.SelectedItem as Encoding;
if (null == enc || null == CurrentTextInput)
return;
TextView.CurrentEncoding = enc;
}
/// <summary>
/// Display entry in preview panel
/// </summary>
private void PreviewEntry (Entry entry)
{
if (m_current_preview.IsEqual (ViewModel.Path, entry.Name))
return;
UpdatePreviewPane (entry);
}
void RefreshPreviewPane ()
{
m_preview_pending = false;
var current = CurrentDirectory.SelectedItem as EntryViewModel;
if (null != current)
UpdatePreviewPane (current.Source);
else
ResetPreviewPane();
}
void ResetPreviewPane ()
{
ActiveViewer = ImageView;
ImageCanvas.Source = null;
TextView.Clear();
CurrentTextInput = null;
}
bool IsPreviewPossible (Entry entry)
{
return "image" == entry.Type || "script" == entry.Type
|| (string.IsNullOrEmpty (entry.Type) && entry.Size < 0x100000);
}
void UpdatePreviewPane (Entry entry)
{
SetStatusText ("");
var vm = ViewModel;
m_current_preview = new PreviewFile { Path = vm.Path, Name = entry.Name, Entry = entry };
if (!IsPreviewPossible (entry))
{
ResetPreviewPane();
return;
}
if ("image" != entry.Type)
LoadPreviewText (m_current_preview);
else if (!m_preview_worker.IsBusy)
m_preview_worker.RunWorkerAsync (m_current_preview);
else
m_preview_pending = true;
}
private Stream m_current_text;
private Stream CurrentTextInput
{
get { return m_current_text; }
set
{
if (value == m_current_text)
return;
if (null != m_current_text)
m_current_text.Dispose();
m_current_text = value;
}
}
void LoadPreviewText (PreviewFile preview)
{
Stream file = null;
try
{
file = VFS.OpenBinaryStream (preview.Entry).AsStream;
if (!TextView.IsTextFile (file))
{
ResetPreviewPane();
return;
}
var enc = EncodingChoice.SelectedItem as Encoding;
if (null == enc)
{
enc = TextView.GuessEncoding (file);
EncodingChoice.SelectedItem = enc;
}
TextView.DisplayStream (file, enc);
ActiveViewer = TextView;
CurrentTextInput = file;
file = null;
}
catch (Exception X)
{
ResetPreviewPane();
SetStatusText (X.Message);
}
finally
{
if (file != null)
file.Dispose();
}
}
void LoadPreviewImage (PreviewFile preview)
{
try
{
using (var data = VFS.OpenImage (preview.Entry))
{
SetPreviewImage (preview, data.Image.Bitmap);
}
}
catch (Exception X)
{
Dispatcher.Invoke (ResetPreviewPane);
SetStatusText (X.Message);
}
}
void SetPreviewImage (PreviewFile preview, BitmapSource bitmap)
{
if (bitmap.DpiX != Desktop.DpiX || bitmap.DpiY != Desktop.DpiY)
{
int stride = bitmap.PixelWidth * ((bitmap.Format.BitsPerPixel + 7) / 8);
var pixels = new byte[stride*bitmap.PixelHeight];
bitmap.CopyPixels (pixels, stride, 0);
var fixed_bitmap = BitmapSource.Create (bitmap.PixelWidth, bitmap.PixelHeight,
Desktop.DpiX, Desktop.DpiY, bitmap.Format, bitmap.Palette, pixels, stride);
bitmap = fixed_bitmap;
}
if (!bitmap.IsFrozen)
bitmap.Freeze();
Dispatcher.Invoke (() =>
{
if (m_current_preview == preview) // compare by reference
{
ActiveViewer = ImageView;
ImageCanvas.Source = bitmap;
ApplyDownScaleSetting();
SetStatusText (string.Format (guiStrings.MsgImageSize, bitmap.PixelWidth,
bitmap.PixelHeight, bitmap.Format.BitsPerPixel));
}
});
}
/// <summary>
/// Fit window size to image.
/// </summary>
private void FitWindowExec (object sender, ExecutedRoutedEventArgs e)
{
var image = ImageCanvas.Source;
if (null == image)
return;
var width = image.Width + Settings.Default.lvPanelWidth.Value + 1;
var height = image.Height;
width = Math.Max (ContentGrid.ActualWidth, width);
height = Math.Max (ContentGrid.ActualHeight, height);
if (width > ContentGrid.ActualWidth || height > ContentGrid.ActualHeight)
{
ContentGrid.Width = width;
ContentGrid.Height = height;
this.SizeToContent = SizeToContent.WidthAndHeight;
Dispatcher.InvokeAsync (() => {
this.SizeToContent = SizeToContent.Manual;
ContentGrid.Width = double.NaN;
ContentGrid.Height = double.NaN;
}, DispatcherPriority.ContextIdle);
}
}
private void SetImageScaleMode (bool scale)
{
if (scale)
{
ImageCanvas.Stretch = Stretch.Uniform;
RenderOptions.SetBitmapScalingMode (ImageCanvas, BitmapScalingMode.HighQuality);
ImageView.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
ImageView.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
}
else
{
ImageCanvas.Stretch = Stretch.None;
RenderOptions.SetBitmapScalingMode (ImageCanvas, BitmapScalingMode.NearestNeighbor);
ImageView.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
ImageView.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
}
}
private void ApplyDownScaleSetting ()
{
bool image_need_scale = DownScaleImage.Get<bool>();
if (image_need_scale && ImageCanvas.Source != null)
{
var image = ImageCanvas.Source;
image_need_scale = image.Width > ImageView.ActualWidth || image.Height > ImageView.ActualHeight;
}
SetImageScaleMode (image_need_scale);
}
private void PreviewSizeChanged (object sender, SizeChangedEventArgs e)
{
var image = ImageCanvas.Source;
if (null == image || !DownScaleImage.Get<bool>())
return;
SetImageScaleMode (image.Width > e.NewSize.Width || image.Height > e.NewSize.Height);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using TNT.Exceptions.ContractImplementation;
using TNT.Exceptions.Local;
using TNT.Exceptions.Remote;
using TNT.Presentation.Deserializers;
using TNT.Presentation.Serializers;
using TNT.Transport;
namespace TNT.Presentation
{
/// <summary>
/// Incapsulates basic Tnt IO operations
/// </summary>
public class Messenger : IMessenger
{
public const short ExceptionMessageTypeId = 30400;
public const short GeneralExceptionMessageTypeId = 0;
private readonly Sender _sender;
private readonly Transporter _channel;
private readonly Dictionary<int, InputMessageDeserializeInfo> _inputSayMessageDeserializeInfos
= new Dictionary<int, InputMessageDeserializeInfo>();
public event Action<IMessenger, short, short, object> OnAns;
public event Action<IMessenger, Exception> OnException;
public event Action<IMessenger, ErrorMessage> ChannelIsDisconnected;
public event Action<IMessenger, RequestMessage> OnRequest;
public Messenger(
Transporter channel,
SerializerFactory serializerFactory,
DeserializerFactory deserializerFactory,
MessageTypeInfo[] outputMessages,
MessageTypeInfo[] inputMessages)
{
_channel = channel;
_channel.OnReceive += _channel_OnReceive;
_channel.OnDisconnect += (c, e) => ChannelIsDisconnected?.Invoke(this, e);
var outputSayMessageSerializes = new Dictionary<int, ISerializer>();
foreach (var messageSayInfo in outputMessages)
{
var serializer = serializerFactory.Create(messageSayInfo.ArgumentTypes);
var hasReturnType = messageSayInfo.ReturnType != typeof(void);
outputSayMessageSerializes.Add(messageSayInfo.MessageId, serializer);
if (hasReturnType)
{
_inputSayMessageDeserializeInfos.Add(
-messageSayInfo.MessageId,
InputMessageDeserializeInfo.CreateForAnswer(
deserializerFactory.Create(messageSayInfo.ReturnType)));
}
}
foreach (var messageSayInfo in inputMessages)
{
var hasReturnType = messageSayInfo.ReturnType != typeof(void);
var deserializer = deserializerFactory.Create(messageSayInfo.ArgumentTypes);
_inputSayMessageDeserializeInfos.Add(
messageSayInfo.MessageId,
InputMessageDeserializeInfo.CreateForAsk(messageSayInfo.ArgumentTypes.Length, hasReturnType,
deserializer));
if (hasReturnType)
{
outputSayMessageSerializes.Add(-messageSayInfo.MessageId,
serializerFactory.Create(messageSayInfo.ReturnType));
}
}
_inputSayMessageDeserializeInfos.Add(Messenger.ExceptionMessageTypeId,
InputMessageDeserializeInfo.CreateForExceptionHandling());
_sender = new Sender(_channel, outputSayMessageSerializes);
}
/// <summary>
/// Handles the error, occured during the input message handling.
/// try to send an error message to remote side
/// </summary>
///<exception cref="InvalidOperationException">Critical implementation exception</exception>
public void HandleRequestProcessingError(ErrorMessage errorInfo, bool isFatal)
{
if (!_channel.IsConnected)
return;
try
{
_sender.SendError(errorInfo);
if (isFatal)
_channel.DisconnectBecauseOf(errorInfo);
}
catch (LocalSerializationException e)
{
throw new InvalidOperationException("Error-serializer exception", e);
}
catch (ConnectionIsNotEstablishedYet)
{
throw new InvalidOperationException("Channel implementation error. Chanel " + _channel.GetType().Name +
" throws ConnectionIsNotEstablishedYet when it was connected");
}
catch (ConnectionIsLostException)
{
_channel.Disconnect();
}
}
/// <summary>
/// Sends "Say" message with "values" arguments
/// </summary>
///<exception cref="ArgumentException"></exception>
///<exception cref="ConnectionIsLostException"></exception>
///<exception cref="LocalSerializationException">one of the argument type serializers is not implemented, or not the same as specified in the contract</exception>
public void Say(short messageId, object[] values)
{
_sender.Say(messageId, values);
}
/// <summary>
/// Sends "ans value" message
/// </summary>
///<exception cref="ArgumentException"></exception>
///<exception cref="ConnectionIsLostException"></exception>
///<exception cref="LocalSerializationException">answer type serializer is not implemented, or not the same as specified in the contract</exception>
public void Ans(short id, short askId, object value)
{
_sender.Ans(id, askId, value);
}
/// <summary>
/// Sends "Say" message with "values" arguments
/// </summary>
///<exception cref="ArgumentException"></exception>
///<exception cref="ConnectionIsLostException"></exception>
///<exception cref="LocalSerializationException">one of the argument type serializers is not implemented, or not the same as specified in the contract</exception>
public void Ask(short id, short askId, object[] values)
{
_sender.Ask(id, askId, values);
}
private void _channel_OnReceive(Transporter arg1, MemoryStream data)
{
short id;
if (!data.TryReadShort(out id))
{
HandleRequestProcessingError(
new ErrorMessage(
null, null,
ErrorType.SerializationError,
"Messae type id missed"), true);
return;
}
InputMessageDeserializeInfo sayDeserializer;
_inputSayMessageDeserializeInfos.TryGetValue(id, out sayDeserializer);
if (sayDeserializer == null)
{
HandleRequestProcessingError(
new ErrorMessage(id, data.TryReadShort(),
ErrorType.ContractSignatureError,
$"Message type id {id} is not implemented"), false);
return;
}
short? askId = null;
if (id < 0 || sayDeserializer.HasReturnType)
{
askId = data.TryReadShort();
if (!askId.HasValue)
{
HandleRequestProcessingError(
new ErrorMessage(
id, null,
ErrorType.SerializationError,
"Ask Id missed"), true);
return;
}
}
object[] deserialized;
try
{
deserialized = sayDeserializer.Deserialize(data);
}
catch (Exception ex)
{
if (id < 0)
{
//Answer deserialization failed. Send LocalSerializerException to upper layer as result of the ASK call
OnException?.Invoke(
this,
new LocalSerializationException(id, askId, "Answer deserialization failed: " + ex.Message, ex));
_channel.Disconnect();
return;
}
HandleRequestProcessingError(
new ErrorMessage(
id, askId,
ErrorType.SerializationError,
$"Message type id{id} with could not be deserialized. InnerException: {ex.ToString()}"), true);
return;
}
if (id < 0)
{
//input answer message handling
OnAns?.Invoke(this, id, askId.Value, deserialized.Single());
}
else if (id == Messenger.ExceptionMessageTypeId)
{
var exceptionMessage = (ErrorMessage) deserialized.First();
if (exceptionMessage.Exception.IsFatal)
_channel.DisconnectBecauseOf(exceptionMessage);
OnException?.Invoke(this, exceptionMessage.Exception);
}
else
{
//input ask / say messageHandling
OnRequest?.Invoke(this, new RequestMessage(id, askId, deserialized));
}
}
}
public class MessageTypeInfo
{
public Type[] ArgumentTypes;
public Type ReturnType;
public short MessageId;
}
class InputMessageDeserializeInfo
{
public static InputMessageDeserializeInfo CreateForAnswer(IDeserializer deserializer)
{
return new InputMessageDeserializeInfo(1, false, deserializer);
}
public static InputMessageDeserializeInfo CreateForAsk(int argumentsCount, bool hasReturnType,
IDeserializer deserializer)
{
return new InputMessageDeserializeInfo(argumentsCount, hasReturnType, deserializer);
}
public static InputMessageDeserializeInfo CreateForExceptionHandling()
{
return new InputMessageDeserializeInfo(1, false, new ErrorMessageDeserializer());
}
private InputMessageDeserializeInfo(int argumentsCount, bool hasReturnType, IDeserializer deserializer)
{
ArgumentsCount = argumentsCount;
HasReturnType = hasReturnType;
Deserializer = deserializer;
}
public int ArgumentsCount { get; }
public IDeserializer Deserializer { get; }
public bool HasReturnType { get; }
public object[] Deserialize(MemoryStream data)
{
object[] arg = null;
if (ArgumentsCount == 0)
arg = new object[0];
else if (ArgumentsCount == 1)
arg = new[] {Deserializer.Deserialize(data, (int) (data.Length - data.Position))};
else
arg = (object[]) Deserializer.Deserialize(data, (int) (data.Length - data.Position));
return arg;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.