context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System.ComponentModel;
using System.Collections.Generic;
using SharpGL.SceneGraph.Cameras;
using SharpGL.SceneGraph.Core;
using SharpGL.SceneGraph.Assets;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
namespace SharpGL.SceneGraph
{
[TypeConverter(typeof(ExpandableObjectConverter))]
[XmlInclude(typeof(PerspectiveCamera))]
[XmlInclude(typeof(OrthographicCamera))]
[XmlInclude(typeof(FrustumCamera))]
[XmlInclude(typeof(LookAtCamera))]
public class Scene : IHasOpenGLContext
{
/// <summary>
/// Initializes a new instance of the <see cref="Scene"/> class.
/// </summary>
public Scene()
{
RenderBoundingVolumes = true;
// The SceneContainer must have it's parent scene set.
SceneContainer.ParentScene = this;
}
/// <summary>
/// Performs a hit test on the scene. All elements that implement IVolumeBound will
/// be hit tested.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <returns>The elements hit.</returns>
public virtual IEnumerable<SceneElement> DoHitTest(int x, int y)
{
// Create a result set.
List<SceneElement> resultSet = new List<SceneElement>();
// Create a hitmap.
Dictionary<uint, SceneElement> hitMap = new Dictionary<uint, SceneElement>();
// If we don't have a current camera, we cannot hit test.
if (CurrentCamera == null)
return resultSet;
// Create an array that will be the viewport.
int[] viewport = new int[4];
// Get the viewport, then convert the mouse point to an opengl point.
gl.GetInteger(OpenGL.GL_VIEWPORT, viewport);
y = viewport[3] - y;
// Create a select buffer.
uint[] selectBuffer = new uint[512];
gl.SelectBuffer(512, selectBuffer);
// Enter select mode.
gl.RenderMode(OpenGL.GL_SELECT);
// Initialise the names, and add the first name.
gl.InitNames();
gl.PushName(0);
// Push matrix, set up projection, then load matrix.
gl.MatrixMode(OpenGL.GL_PROJECTION);
gl.PushMatrix();
gl.LoadIdentity();
gl.PickMatrix(x, y, 4, 4, viewport);
CurrentCamera.TransformProjectionMatrix(gl);
gl.MatrixMode(OpenGL.GL_MODELVIEW);
gl.LoadIdentity();
// Create the name.
uint currentName = 1;
// Render the root for hit testing.
RenderElementForHitTest(SceneContainer, hitMap, ref currentName);
// Pop matrix and flush commands.
gl.MatrixMode(OpenGL.GL_PROJECTION);
gl.PopMatrix();
gl.MatrixMode(OpenGL.GL_MODELVIEW);
gl.Flush();
// End selection.
int hits = gl.RenderMode(OpenGL.GL_RENDER);
uint posinarray = 0;
// Go through each name.
for (int hit = 0; hit < hits; hit++)
{
uint nameCount = selectBuffer[posinarray++];
uint unused = selectBuffer[posinarray++];
uint unused1 = selectBuffer[posinarray++];
if (nameCount == 0)
continue;
// Add each hit element to the result set to the array.
for (int name = 0; name < nameCount; name++)
{
uint hitName = selectBuffer[posinarray++];
resultSet.Add(hitMap[hitName]);
}
}
// Return the result set.
return resultSet;
}
/// <summary>
/// This function draws all of the objects in the scene (i.e. every quadric
/// in the quadrics arraylist etc).
/// </summary>
public virtual void Draw(Camera camera = null)
{
// TODO: we must decide what to do about drawing - are
// cameras completely outside of the responsibility of the scene?
// If no camera has been provided, use the current one.
if (camera == null)
camera = CurrentCamera;
// Set the clear color.
float[] clear = _clearColour;
gl.ClearColor(clear[0], clear[1], clear[2], clear[3]);
// Reproject.
if (camera != null)
camera.Project(gl);
// Clear.
gl.Clear(OpenGL.GL_COLOR_BUFFER_BIT | OpenGL.GL_DEPTH_BUFFER_BIT |
OpenGL.GL_STENCIL_BUFFER_BIT);
//gl.BindTexture(OpenGL.GL_TEXTURE_2D, 0);
// Render the root element, this will then render the whole
// of the scene tree.
RenderElement(SceneContainer, RenderMode.Design);
// TODO: Adding this code here re-enables textures- it should work without it but it
// doesn't, look into this.
//gl.BindTexture(OpenGL.GL_TEXTURE_2D, 0);
//gl.Enable(OpenGL.GL_TEXTURE_2D);
gl.Flush();
}
/// <summary>
/// Renders the element.
/// </summary>
/// <param name="sceneElement">The secene element to render.</param>
/// <param name="renderMode">The render mode.</param>
public void RenderElement(SceneElement sceneElement, RenderMode renderMode)
{
// If the element is disabled, we're done.
if (sceneElement.IsEnabled == false)
return;
// Push each effect.
foreach (var effect in sceneElement.Effects)
if(effect.IsEnabled)
effect.Push(gl, sceneElement);
// If the element can be bound, bind it.
if (sceneElement is IBindable)
((IBindable)sceneElement).Bind(gl);
// If the element has an object space, transform into it.
if (sceneElement is IHasObjectSpace)
((IHasObjectSpace)sceneElement).PushObjectSpace(gl);
// If the element has a material, push it.
if (sceneElement is IHasMaterial && ((IHasMaterial)sceneElement).Material != null)
((IHasMaterial)sceneElement).Material.Push(gl);
// If the element can be rendered, render it.
if (sceneElement is IRenderable)
((IRenderable)sceneElement).Render(gl, renderMode);
// If the element has a material, pop it.
if (sceneElement is IHasMaterial && ((IHasMaterial)sceneElement).Material != null)
((IHasMaterial)sceneElement).Material.Pop(gl);
// IF the element is volume bound and we are rendering volumes, render the volume.
if (RenderBoundingVolumes && sceneElement is IVolumeBound)
((IVolumeBound)sceneElement).BoundingVolume.Render(gl, renderMode);
// Recurse through the children.
foreach (var childElement in sceneElement.Children)
RenderElement(childElement, renderMode);
// If the element has an object space, transform out of it.
if (sceneElement is IHasObjectSpace)
((IHasObjectSpace)sceneElement).PopObjectSpace(gl);
// Pop each effect.
for (int i = sceneElement.Effects.Count - 1; i >= 0; i--)
if(sceneElement.Effects[i].IsEnabled)
sceneElement.Effects[i].Pop(gl, sceneElement);
}
/// <summary>
/// Renders the element for hit test.
/// </summary>
/// <param name="sceneElement">The scene element.</param>
/// <param name="hitMap">The hit map.</param>
/// <param name="currentName">Current hit name.</param>
private void RenderElementForHitTest(SceneElement sceneElement,
Dictionary<uint, SceneElement> hitMap, ref uint currentName)
{
// If the element is disabled, we're done.
// Also, never hit test the current camera.
if (sceneElement.IsEnabled == false || sceneElement == CurrentCamera)
return;
// Push each effect.
foreach (var effect in sceneElement.Effects)
if (effect.IsEnabled)
effect.Push(gl, sceneElement);
// If the element has an object space, transform into it.
if (sceneElement is IHasObjectSpace)
((IHasObjectSpace)sceneElement).PushObjectSpace(gl);
// If the element is volume bound, render the volume.
if (sceneElement is IVolumeBound)
{
// Load and map the name.
gl.LoadName(currentName);
hitMap[currentName] = sceneElement;
// Render the bounding volume.
((IVolumeBound)sceneElement).BoundingVolume.Render(gl, RenderMode.HitTest);
// Increment the name.
currentName++;
}
// Recurse through the children.
foreach (var childElement in sceneElement.Children)
RenderElementForHitTest(childElement, hitMap, ref currentName);
// If the element has an object space, transform out of it.
if (sceneElement is IHasObjectSpace)
((IHasObjectSpace)sceneElement).PopObjectSpace(gl);
// Pop each effect.
for (int i = sceneElement.Effects.Count - 1; i >= 0; i--)
if (sceneElement.Effects[i].IsEnabled)
sceneElement.Effects[i].Pop(gl, sceneElement);
}
/// <summary>
/// Use this function to resize the scene window, and also to look through
/// the current camera.
/// </summary>
/// <param name="width">Width of the screen.</param>
/// <param name="height">Height of the screen.</param>
public virtual void Resize(int width, int height)
{
if(width != -1 && height != -1 && gl != null)
{
// Resize.
gl.Viewport(0, 0, width, height);
if (CurrentCamera != null)
{
// Set aspect ratio.
CurrentCamera.AspectRatio = width / (float)height;
// Then project.
CurrentCamera.Project(gl);
}
}
}
/// <summary>
/// This is the OpenGL class, use it to call OpenGL functions.
/// Only set when the context is set.
/// </summary>
private OpenGL gl;
/// <summary>
/// This is the colour of the background of the scene.
/// </summary>
private GLColor _clearColour = new GLColor(0, 0, 0, 0);
/// <summary>
/// Gets or sets the scene container.
/// </summary>
/// <value>
/// The scene container.
/// </value>
[Description("The top-level object in the Scene Tree"), Category("Scene")]
public SceneContainer SceneContainer { get; set; } = new SceneContainer();
/// <summary>
/// Gets the assets.
/// </summary>
[Description("The scene assets."), Category("Scene")]
public ObservableCollection<Asset> Assets { get; } = new ObservableCollection<Asset>();
/// <summary>
/// Gets or sets the current camera.
/// </summary>
/// <value>
/// The current camera.
/// </value>
[Description("The current camera being used to view the scene."), Category("Scene")]
public Camera CurrentCamera { get; set; }
/// <summary>
/// Gets or sets a value indicating whether [render bounding volumes].
/// </summary>
/// <value>
/// <c>true</c> if [render bounding volumes]; otherwise, <c>false</c>.
/// </value>
//todo tidy up (into render options?)
public bool RenderBoundingVolumes
{
get;
set;
}
public void CreateInContext(OpenGL gl)
{
// Set our current context.
this.gl = gl;
// Create every scene element.
var openGLContextElements = SceneContainer.Traverse<SceneElement>(
se => se is IHasOpenGLContext);
foreach (var openGLContextElement in openGLContextElements)
((IHasOpenGLContext)openGLContextElement).CreateInContext(gl);
}
public void DestroyInContext(OpenGL gl)
{
// Create every scene element.
var openGLContextElements = SceneContainer.Traverse<SceneElement>(
se => se is IHasOpenGLContext);
foreach (var openGLContextElement in openGLContextElements)
((IHasOpenGLContext)openGLContextElement).CreateInContext(gl);
}
public OpenGL CurrentOpenGLContext => gl;
}
}
| |
using System;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
namespace Domain.Data.Query
{
public partial class Node
{
public static PurchaseOrderHeaderNode PurchaseOrderHeader { get { return new PurchaseOrderHeaderNode(); } }
}
public partial class PurchaseOrderHeaderNode : Blueprint41.Query.Node
{
protected override string GetNeo4jLabel()
{
return "PurchaseOrderHeader";
}
internal PurchaseOrderHeaderNode() { }
internal PurchaseOrderHeaderNode(PurchaseOrderHeaderAlias alias, bool isReference = false)
{
NodeAlias = alias;
IsReference = isReference;
}
internal PurchaseOrderHeaderNode(RELATIONSHIP relationship, DirectionEnum direction, string neo4jLabel = null) : base(relationship, direction, neo4jLabel) { }
public PurchaseOrderHeaderNode Alias(out PurchaseOrderHeaderAlias alias)
{
alias = new PurchaseOrderHeaderAlias(this);
NodeAlias = alias;
return this;
}
public PurchaseOrderHeaderNode UseExistingAlias(AliasResult alias)
{
NodeAlias = alias;
return this;
}
public PurchaseOrderHeaderIn In { get { return new PurchaseOrderHeaderIn(this); } }
public class PurchaseOrderHeaderIn
{
private PurchaseOrderHeaderNode Parent;
internal PurchaseOrderHeaderIn(PurchaseOrderHeaderNode parent)
{
Parent = parent;
}
public IFromIn_PURCHASEORDERHEADER_HAS_SHIPMETHOD_REL PURCHASEORDERHEADER_HAS_SHIPMETHOD { get { return new PURCHASEORDERHEADER_HAS_SHIPMETHOD_REL(Parent, DirectionEnum.In); } }
public IFromIn_PURCHASEORDERHEADER_HAS_VENDOR_REL PURCHASEORDERHEADER_HAS_VENDOR { get { return new PURCHASEORDERHEADER_HAS_VENDOR_REL(Parent, DirectionEnum.In); } }
}
public PurchaseOrderHeaderOut Out { get { return new PurchaseOrderHeaderOut(this); } }
public class PurchaseOrderHeaderOut
{
private PurchaseOrderHeaderNode Parent;
internal PurchaseOrderHeaderOut(PurchaseOrderHeaderNode parent)
{
Parent = parent;
}
public IFromOut_PURCHASEORDERDETAIL_HAS_PURCHASEORDERHEADER_REL PURCHASEORDERDETAIL_HAS_PURCHASEORDERHEADER { get { return new PURCHASEORDERDETAIL_HAS_PURCHASEORDERHEADER_REL(Parent, DirectionEnum.Out); } }
}
}
public class PurchaseOrderHeaderAlias : AliasResult
{
internal PurchaseOrderHeaderAlias(PurchaseOrderHeaderNode parent)
{
Node = parent;
}
public override IReadOnlyDictionary<string, FieldResult> AliasFields
{
get
{
if (m_AliasFields == null)
{
m_AliasFields = new Dictionary<string, FieldResult>()
{
{ "RevisionNumber", new StringResult(this, "RevisionNumber", Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"], Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["RevisionNumber"]) },
{ "Status", new StringResult(this, "Status", Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"], Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["Status"]) },
{ "OrderDate", new DateTimeResult(this, "OrderDate", Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"], Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["OrderDate"]) },
{ "ShipDate", new DateTimeResult(this, "ShipDate", Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"], Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["ShipDate"]) },
{ "SubTotal", new FloatResult(this, "SubTotal", Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"], Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["SubTotal"]) },
{ "TaxAmt", new FloatResult(this, "TaxAmt", Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"], Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["TaxAmt"]) },
{ "Freight", new StringResult(this, "Freight", Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"], Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["Freight"]) },
{ "TotalDue", new FloatResult(this, "TotalDue", Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"], Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"].Properties["TotalDue"]) },
{ "ModifiedDate", new DateTimeResult(this, "ModifiedDate", Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"], Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]) },
{ "Uid", new StringResult(this, "Uid", Datastore.AdventureWorks.Model.Entities["PurchaseOrderHeader"], Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]) },
};
}
return m_AliasFields;
}
}
private IReadOnlyDictionary<string, FieldResult> m_AliasFields = null;
public PurchaseOrderHeaderNode.PurchaseOrderHeaderIn In { get { return new PurchaseOrderHeaderNode.PurchaseOrderHeaderIn(new PurchaseOrderHeaderNode(this, true)); } }
public PurchaseOrderHeaderNode.PurchaseOrderHeaderOut Out { get { return new PurchaseOrderHeaderNode.PurchaseOrderHeaderOut(new PurchaseOrderHeaderNode(this, true)); } }
public StringResult RevisionNumber
{
get
{
if ((object)m_RevisionNumber == null)
m_RevisionNumber = (StringResult)AliasFields["RevisionNumber"];
return m_RevisionNumber;
}
}
private StringResult m_RevisionNumber = null;
public StringResult Status
{
get
{
if ((object)m_Status == null)
m_Status = (StringResult)AliasFields["Status"];
return m_Status;
}
}
private StringResult m_Status = null;
public DateTimeResult OrderDate
{
get
{
if ((object)m_OrderDate == null)
m_OrderDate = (DateTimeResult)AliasFields["OrderDate"];
return m_OrderDate;
}
}
private DateTimeResult m_OrderDate = null;
public DateTimeResult ShipDate
{
get
{
if ((object)m_ShipDate == null)
m_ShipDate = (DateTimeResult)AliasFields["ShipDate"];
return m_ShipDate;
}
}
private DateTimeResult m_ShipDate = null;
public FloatResult SubTotal
{
get
{
if ((object)m_SubTotal == null)
m_SubTotal = (FloatResult)AliasFields["SubTotal"];
return m_SubTotal;
}
}
private FloatResult m_SubTotal = null;
public FloatResult TaxAmt
{
get
{
if ((object)m_TaxAmt == null)
m_TaxAmt = (FloatResult)AliasFields["TaxAmt"];
return m_TaxAmt;
}
}
private FloatResult m_TaxAmt = null;
public StringResult Freight
{
get
{
if ((object)m_Freight == null)
m_Freight = (StringResult)AliasFields["Freight"];
return m_Freight;
}
}
private StringResult m_Freight = null;
public FloatResult TotalDue
{
get
{
if ((object)m_TotalDue == null)
m_TotalDue = (FloatResult)AliasFields["TotalDue"];
return m_TotalDue;
}
}
private FloatResult m_TotalDue = null;
public DateTimeResult ModifiedDate
{
get
{
if ((object)m_ModifiedDate == null)
m_ModifiedDate = (DateTimeResult)AliasFields["ModifiedDate"];
return m_ModifiedDate;
}
}
private DateTimeResult m_ModifiedDate = null;
public StringResult Uid
{
get
{
if ((object)m_Uid == null)
m_Uid = (StringResult)AliasFields["Uid"];
return m_Uid;
}
}
private StringResult m_Uid = null;
}
}
| |
/*
* 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.Linq;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Capabilities;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Capabilities.Handlers
{
public class FetchInvDescHandler
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IInventoryService m_InventoryService;
private ILibraryService m_LibraryService;
private IScene m_Scene;
// private object m_fetchLock = new Object();
public FetchInvDescHandler(IInventoryService invService, ILibraryService libService, IScene s)
{
m_InventoryService = invService;
m_LibraryService = libService;
m_Scene = s;
}
public string FetchInventoryDescendentsRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
//m_log.DebugFormat("[XXX]: FetchInventoryDescendentsRequest in {0}, {1}", (m_Scene == null) ? "none" : m_Scene.Name, request);
// nasty temporary hack here, the linden client falsely
// identifies the uuid 00000000-0000-0000-0000-000000000000
// as a string which breaks us
//
// correctly mark it as a uuid
//
request = request.Replace("<string>00000000-0000-0000-0000-000000000000</string>", "<uuid>00000000-0000-0000-0000-000000000000</uuid>");
// another hack <integer>1</integer> results in a
// System.ArgumentException: Object type System.Int32 cannot
// be converted to target type: System.Boolean
//
request = request.Replace("<key>fetch_folders</key><integer>0</integer>", "<key>fetch_folders</key><boolean>0</boolean>");
request = request.Replace("<key>fetch_folders</key><integer>1</integer>", "<key>fetch_folders</key><boolean>1</boolean>");
Hashtable hash = new Hashtable();
try
{
hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
}
catch (LLSD.LLSDParseException e)
{
m_log.ErrorFormat("[WEB FETCH INV DESC HANDLER]: Fetch error: {0}{1}" + e.Message, e.StackTrace);
m_log.Error("Request: " + request);
}
ArrayList foldersrequested = (ArrayList)hash["folders"];
string response = "";
string bad_folders_response = "";
List<LLSDFetchInventoryDescendents> folders = new List<LLSDFetchInventoryDescendents>();
for (int i = 0; i < foldersrequested.Count; i++)
{
Hashtable inventoryhash = (Hashtable)foldersrequested[i];
LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents();
try
{
LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest);
}
catch (Exception e)
{
m_log.Debug("[WEB FETCH INV DESC HANDLER]: caught exception doing OSD deserialize" + e);
continue;
}
// Filter duplicate folder ids that bad viewers may send
if (folders.Find(f => f.folder_id == llsdRequest.folder_id) == null)
folders.Add(llsdRequest);
}
if (folders.Count > 0)
{
List<UUID> bad_folders = new List<UUID>();
List<InventoryCollectionWithDescendents> invcollSet = Fetch(folders, bad_folders);
//m_log.DebugFormat("[XXX]: Got {0} folders from a request of {1}", invcollSet.Count, folders.Count);
if (invcollSet == null)
{
m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Multiple folder fetch failed. Trying old protocol.");
#pragma warning disable 0612
return FetchInventoryDescendentsRequest(foldersrequested, httpRequest, httpResponse);
#pragma warning restore 0612
}
string inventoryitemstr = string.Empty;
foreach (InventoryCollectionWithDescendents icoll in invcollSet)
{
LLSDInventoryDescendents reply = ToLLSD(icoll.Collection, icoll.Descendents);
inventoryitemstr = LLSDHelpers.SerialiseLLSDReply(reply);
inventoryitemstr = inventoryitemstr.Replace("<llsd><map><key>folders</key><array>", "");
inventoryitemstr = inventoryitemstr.Replace("</array></map></llsd>", "");
response += inventoryitemstr;
}
//m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Bad folders {0}", string.Join(", ", bad_folders));
foreach (UUID bad in bad_folders)
bad_folders_response += "<uuid>" + bad + "</uuid>";
}
if (response.Length == 0)
{
/* Viewers expect a bad_folders array when not available */
if (bad_folders_response.Length != 0)
{
response = "<llsd><map><key>bad_folders</key><array>" + bad_folders_response + "</array></map></llsd>";
}
else
{
response = "<llsd><map><key>folders</key><array /></map></llsd>";
}
}
else
{
if (bad_folders_response.Length != 0)
{
response = "<llsd><map><key>folders</key><array>" + response + "</array><key>bad_folders</key><array>" + bad_folders_response + "</array></map></llsd>";
}
else
{
response = "<llsd><map><key>folders</key><array>" + response + "</array></map></llsd>";
}
}
//m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Replying to CAPS fetch inventory request for {0} folders. Item count {1}", folders.Count, item_count);
//m_log.Debug("[WEB FETCH INV DESC HANDLER] " + response);
return response;
}
/// <summary>
/// Construct an LLSD reply packet to a CAPS inventory request
/// </summary>
/// <param name="invFetch"></param>
/// <returns></returns>
private LLSDInventoryDescendents FetchInventoryReply(LLSDFetchInventoryDescendents invFetch)
{
LLSDInventoryDescendents reply = new LLSDInventoryDescendents();
LLSDInventoryFolderContents contents = new LLSDInventoryFolderContents();
contents.agent_id = invFetch.owner_id;
contents.owner_id = invFetch.owner_id;
contents.folder_id = invFetch.folder_id;
reply.folders.Array.Add(contents);
InventoryCollection inv = new InventoryCollection();
inv.Folders = new List<InventoryFolderBase>();
inv.Items = new List<InventoryItemBase>();
int version = 0;
int descendents = 0;
#pragma warning disable 0612
inv = Fetch(
invFetch.owner_id, invFetch.folder_id, invFetch.owner_id,
invFetch.fetch_folders, invFetch.fetch_items, invFetch.sort_order, out version, out descendents);
#pragma warning restore 0612
if (inv != null && inv.Folders != null)
{
foreach (InventoryFolderBase invFolder in inv.Folders)
{
contents.categories.Array.Add(ConvertInventoryFolder(invFolder));
}
descendents += inv.Folders.Count;
}
if (inv != null && inv.Items != null)
{
foreach (InventoryItemBase invItem in inv.Items)
{
contents.items.Array.Add(ConvertInventoryItem(invItem));
}
}
contents.descendents = descendents;
contents.version = version;
//m_log.DebugFormat(
// "[WEB FETCH INV DESC HANDLER]: Replying to request for folder {0} (fetch items {1}, fetch folders {2}) with {3} items and {4} folders for agent {5}",
// invFetch.folder_id,
// invFetch.fetch_items,
// invFetch.fetch_folders,
// contents.items.Array.Count,
// contents.categories.Array.Count,
// invFetch.owner_id);
return reply;
}
private LLSDInventoryDescendents ToLLSD(InventoryCollection inv, int descendents)
{
LLSDInventoryDescendents reply = new LLSDInventoryDescendents();
LLSDInventoryFolderContents contents = new LLSDInventoryFolderContents();
contents.agent_id = inv.OwnerID;
contents.owner_id = inv.OwnerID;
contents.folder_id = inv.FolderID;
reply.folders.Array.Add(contents);
if (inv.Folders != null)
{
foreach (InventoryFolderBase invFolder in inv.Folders)
{
contents.categories.Array.Add(ConvertInventoryFolder(invFolder));
}
descendents += inv.Folders.Count;
}
if (inv.Items != null)
{
foreach (InventoryItemBase invItem in inv.Items)
{
contents.items.Array.Add(ConvertInventoryItem(invItem));
}
}
contents.descendents = descendents;
contents.version = inv.Version;
return reply;
}
/// <summary>
/// Old style. Soon to be deprecated.
/// </summary>
/// <param name="request"></param>
/// <param name="httpRequest"></param>
/// <param name="httpResponse"></param>
/// <returns></returns>
[Obsolete]
private string FetchInventoryDescendentsRequest(ArrayList foldersrequested, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
//m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Received request for {0} folders", foldersrequested.Count);
string response = "";
string bad_folders_response = "";
for (int i = 0; i < foldersrequested.Count; i++)
{
string inventoryitemstr = "";
Hashtable inventoryhash = (Hashtable)foldersrequested[i];
LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents();
try
{
LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest);
}
catch (Exception e)
{
m_log.Debug("[WEB FETCH INV DESC HANDLER]: caught exception doing OSD deserialize" + e);
}
LLSDInventoryDescendents reply = FetchInventoryReply(llsdRequest);
if (null == reply)
{
bad_folders_response += "<uuid>" + llsdRequest.folder_id.ToString() + "</uuid>";
}
else
{
inventoryitemstr = LLSDHelpers.SerialiseLLSDReply(reply);
inventoryitemstr = inventoryitemstr.Replace("<llsd><map><key>folders</key><array>", "");
inventoryitemstr = inventoryitemstr.Replace("</array></map></llsd>", "");
}
response += inventoryitemstr;
}
if (response.Length == 0)
{
/* Viewers expect a bad_folders array when not available */
if (bad_folders_response.Length != 0)
{
response = "<llsd><map><key>bad_folders</key><array>" + bad_folders_response + "</array></map></llsd>";
}
else
{
response = "<llsd><map><key>folders</key><array /></map></llsd>";
}
}
else
{
if (bad_folders_response.Length != 0)
{
response = "<llsd><map><key>folders</key><array>" + response + "</array><key>bad_folders</key><array>" + bad_folders_response + "</array></map></llsd>";
}
else
{
response = "<llsd><map><key>folders</key><array>" + response + "</array></map></llsd>";
}
}
// m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Replying to CAPS fetch inventory request");
//m_log.Debug("[WEB FETCH INV DESC HANDLER] "+response);
return response;
// }
}
/// <summary>
/// Handle the caps inventory descendents fetch.
/// </summary>
/// <param name="agentID"></param>
/// <param name="folderID"></param>
/// <param name="ownerID"></param>
/// <param name="fetchFolders"></param>
/// <param name="fetchItems"></param>
/// <param name="sortOrder"></param>
/// <param name="version"></param>
/// <returns>An empty InventoryCollection if the inventory look up failed</returns>
[Obsolete]
private InventoryCollection Fetch(
UUID agentID, UUID folderID, UUID ownerID,
bool fetchFolders, bool fetchItems, int sortOrder, out int version, out int descendents)
{
//m_log.DebugFormat(
// "[WEB FETCH INV DESC HANDLER]: Fetching folders ({0}), items ({1}) from {2} for agent {3}",
// fetchFolders, fetchItems, folderID, agentID);
// FIXME MAYBE: We're not handling sortOrder!
version = 0;
descendents = 0;
InventoryFolderImpl fold;
if (m_LibraryService != null && m_LibraryService.LibraryRootFolder != null && agentID == m_LibraryService.LibraryRootFolder.Owner)
{
if ((fold = m_LibraryService.LibraryRootFolder.FindFolder(folderID)) != null)
{
InventoryCollection ret = new InventoryCollection();
ret.Folders = new List<InventoryFolderBase>();
ret.Items = fold.RequestListOfItems();
descendents = ret.Folders.Count + ret.Items.Count;
return ret;
}
}
InventoryCollection contents = new InventoryCollection();
if (folderID != UUID.Zero)
{
InventoryCollection fetchedContents = m_InventoryService.GetFolderContent(agentID, folderID);
if (fetchedContents == null)
{
m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: Could not get contents of folder {0} for user {1}", folderID, agentID);
return contents;
}
contents = fetchedContents;
InventoryFolderBase containingFolder = new InventoryFolderBase();
containingFolder.ID = folderID;
containingFolder.Owner = agentID;
containingFolder = m_InventoryService.GetFolder(containingFolder);
if (containingFolder != null)
{
//m_log.DebugFormat(
// "[WEB FETCH INV DESC HANDLER]: Retrieved folder {0} {1} for agent id {2}",
// containingFolder.Name, containingFolder.ID, agentID);
version = containingFolder.Version;
if (fetchItems)
{
List<InventoryItemBase> itemsToReturn = contents.Items;
List<InventoryItemBase> originalItems = new List<InventoryItemBase>(itemsToReturn);
// descendents must only include the links, not the linked items we add
descendents = originalItems.Count;
// Add target items for links in this folder before the links themselves.
foreach (InventoryItemBase item in originalItems)
{
if (item.AssetType == (int)AssetType.Link)
{
InventoryItemBase linkedItem = m_InventoryService.GetItem(new InventoryItemBase(item.AssetID));
// Take care of genuinely broken links where the target doesn't exist
// HACK: Also, don't follow up links that just point to other links. In theory this is legitimate,
// but no viewer has been observed to set these up and this is the lazy way of avoiding cycles
// rather than having to keep track of every folder requested in the recursion.
if (linkedItem != null && linkedItem.AssetType != (int)AssetType.Link)
itemsToReturn.Insert(0, linkedItem);
}
}
// Now scan for folder links and insert the items they target and those links at the head of the return data
foreach (InventoryItemBase item in originalItems)
{
if (item.AssetType == (int)AssetType.LinkFolder)
{
InventoryCollection linkedFolderContents = m_InventoryService.GetFolderContent(ownerID, item.AssetID);
List<InventoryItemBase> links = linkedFolderContents.Items;
itemsToReturn.InsertRange(0, links);
foreach (InventoryItemBase link in linkedFolderContents.Items)
{
// Take care of genuinely broken links where the target doesn't exist
// HACK: Also, don't follow up links that just point to other links. In theory this is legitimate,
// but no viewer has been observed to set these up and this is the lazy way of avoiding cycles
// rather than having to keep track of every folder requested in the recursion.
if (link != null)
{
// m_log.DebugFormat(
// "[WEB FETCH INV DESC HANDLER]: Adding item {0} {1} from folder {2} linked from {3}",
// link.Name, (AssetType)link.AssetType, item.AssetID, containingFolder.Name);
InventoryItemBase linkedItem
= m_InventoryService.GetItem(new InventoryItemBase(link.AssetID));
if (linkedItem != null)
itemsToReturn.Insert(0, linkedItem);
}
}
}
}
}
// foreach (InventoryItemBase item in contents.Items)
// {
// m_log.DebugFormat(
// "[WEB FETCH INV DESC HANDLER]: Returning item {0}, type {1}, parent {2} in {3} {4}",
// item.Name, (AssetType)item.AssetType, item.Folder, containingFolder.Name, containingFolder.ID);
// }
// =====
//
// foreach (InventoryItemBase linkedItem in linkedItemsToAdd)
// {
// m_log.DebugFormat(
// "[WEB FETCH INV DESC HANDLER]: Inserted linked item {0} for link in folder {1} for agent {2}",
// linkedItem.Name, folderID, agentID);
//
// contents.Items.Add(linkedItem);
// }
//
// // If the folder requested contains links, then we need to send those folders first, otherwise the links
// // will be broken in the viewer.
// HashSet<UUID> linkedItemFolderIdsToSend = new HashSet<UUID>();
// foreach (InventoryItemBase item in contents.Items)
// {
// if (item.AssetType == (int)AssetType.Link)
// {
// InventoryItemBase linkedItem = m_InventoryService.GetItem(new InventoryItemBase(item.AssetID));
//
// // Take care of genuinely broken links where the target doesn't exist
// // HACK: Also, don't follow up links that just point to other links. In theory this is legitimate,
// // but no viewer has been observed to set these up and this is the lazy way of avoiding cycles
// // rather than having to keep track of every folder requested in the recursion.
// if (linkedItem != null && linkedItem.AssetType != (int)AssetType.Link)
// {
// // We don't need to send the folder if source and destination of the link are in the same
// // folder.
// if (linkedItem.Folder != containingFolder.ID)
// linkedItemFolderIdsToSend.Add(linkedItem.Folder);
// }
// }
// }
//
// foreach (UUID linkedItemFolderId in linkedItemFolderIdsToSend)
// {
// m_log.DebugFormat(
// "[WEB FETCH INV DESC HANDLER]: Recursively fetching folder {0} linked by item in folder {1} for agent {2}",
// linkedItemFolderId, folderID, agentID);
//
// int dummyVersion;
// InventoryCollection linkedCollection
// = Fetch(
// agentID, linkedItemFolderId, ownerID, fetchFolders, fetchItems, sortOrder, out dummyVersion);
//
// InventoryFolderBase linkedFolder = new InventoryFolderBase(linkedItemFolderId);
// linkedFolder.Owner = agentID;
// linkedFolder = m_InventoryService.GetFolder(linkedFolder);
//
//// contents.Folders.AddRange(linkedCollection.Folders);
//
// contents.Folders.Add(linkedFolder);
// contents.Items.AddRange(linkedCollection.Items);
// }
// }
}
}
else
{
// Lost items don't really need a version
version = 1;
}
return contents;
}
private void AddLibraryFolders(List<LLSDFetchInventoryDescendents> fetchFolders, List<InventoryCollectionWithDescendents> result)
{
InventoryFolderImpl fold;
if (m_LibraryService != null && m_LibraryService.LibraryRootFolder != null)
{
List<LLSDFetchInventoryDescendents> libfolders = fetchFolders.FindAll(f => f.owner_id == m_LibraryService.LibraryRootFolder.Owner);
fetchFolders.RemoveAll(f => libfolders.Contains(f));
//m_log.DebugFormat("[XXX]: Found {0} library folders in request", libfolders.Count);
foreach (LLSDFetchInventoryDescendents f in libfolders)
{
if ((fold = m_LibraryService.LibraryRootFolder.FindFolder(f.folder_id)) != null)
{
InventoryCollectionWithDescendents ret = new InventoryCollectionWithDescendents();
ret.Collection = new InventoryCollection();
ret.Collection.Folders = new List<InventoryFolderBase>();
ret.Collection.Items = fold.RequestListOfItems();
ret.Collection.OwnerID = m_LibraryService.LibraryRootFolder.Owner;
ret.Collection.FolderID = f.folder_id;
ret.Collection.Version = fold.Version;
ret.Descendents = ret.Collection.Items.Count;
result.Add(ret);
//m_log.DebugFormat("[XXX]: Added libfolder {0} ({1}) {2}", ret.Collection.FolderID, ret.Collection.OwnerID);
}
}
}
}
private List<InventoryCollectionWithDescendents> Fetch(List<LLSDFetchInventoryDescendents> fetchFolders, List<UUID> bad_folders)
{
//m_log.DebugFormat(
// "[WEB FETCH INV DESC HANDLER]: Fetching {0} folders for owner {1}", fetchFolders.Count, fetchFolders[0].owner_id);
// FIXME MAYBE: We're not handling sortOrder!
List<InventoryCollectionWithDescendents> result = new List<InventoryCollectionWithDescendents>();
AddLibraryFolders(fetchFolders, result);
// Filter folder Zero right here. Some viewers (Firestorm) send request for folder Zero, which doesn't make sense
// and can kill the sim (all root folders have parent_id Zero)
LLSDFetchInventoryDescendents zero = fetchFolders.Find(f => f.folder_id == UUID.Zero);
if (zero != null)
{
fetchFolders.Remove(zero);
BadFolder(zero, null, bad_folders);
}
if (fetchFolders.Count > 0)
{
UUID[] fids = new UUID[fetchFolders.Count];
int i = 0;
foreach (LLSDFetchInventoryDescendents f in fetchFolders)
fids[i++] = f.folder_id;
//m_log.DebugFormat("[XXX]: {0}", string.Join(",", fids));
InventoryCollection[] fetchedContents = m_InventoryService.GetMultipleFoldersContent(fetchFolders[0].owner_id, fids);
if (fetchedContents == null || (fetchedContents != null && fetchedContents.Length == 0))
{
m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: Could not get contents of multiple folders for user {0}", fetchFolders[0].owner_id);
foreach (LLSDFetchInventoryDescendents freq in fetchFolders)
BadFolder(freq, null, bad_folders);
return null;
}
i = 0;
// Do some post-processing. May need to fetch more from inv server for links
foreach (InventoryCollection contents in fetchedContents)
{
// Find the original request
LLSDFetchInventoryDescendents freq = fetchFolders[i++];
InventoryCollectionWithDescendents coll = new InventoryCollectionWithDescendents();
coll.Collection = contents;
if (BadFolder(freq, contents, bad_folders))
continue;
// Next: link management
ProcessLinks(freq, coll);
result.Add(coll);
}
}
return result;
}
private bool BadFolder(LLSDFetchInventoryDescendents freq, InventoryCollection contents, List<UUID> bad_folders)
{
bool bad = false;
if (contents == null)
{
bad_folders.Add(freq.folder_id);
bad = true;
}
// The inventory server isn't sending FolderID in the collection...
// Must fetch it individually
else if (contents.FolderID == UUID.Zero)
{
InventoryFolderBase containingFolder = new InventoryFolderBase();
containingFolder.ID = freq.folder_id;
containingFolder.Owner = freq.owner_id;
containingFolder = m_InventoryService.GetFolder(containingFolder);
if (containingFolder != null)
{
contents.FolderID = containingFolder.ID;
contents.OwnerID = containingFolder.Owner;
contents.Version = containingFolder.Version;
}
else
{
// Was it really a request for folder Zero?
// This is an overkill, but Firestorm really asks for folder Zero.
// I'm leaving the code here for the time being, but commented.
if (freq.folder_id == UUID.Zero)
{
//coll.Collection.OwnerID = freq.owner_id;
//coll.Collection.FolderID = contents.FolderID;
//containingFolder = m_InventoryService.GetRootFolder(freq.owner_id);
//if (containingFolder != null)
//{
// m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: Request for parent of folder {0}", containingFolder.ID);
// coll.Collection.Folders.Clear();
// coll.Collection.Folders.Add(containingFolder);
// if (m_LibraryService != null && m_LibraryService.LibraryRootFolder != null)
// {
// InventoryFolderBase lib = new InventoryFolderBase(m_LibraryService.LibraryRootFolder.ID, m_LibraryService.LibraryRootFolder.Owner);
// lib.Name = m_LibraryService.LibraryRootFolder.Name;
// lib.Type = m_LibraryService.LibraryRootFolder.Type;
// lib.Version = m_LibraryService.LibraryRootFolder.Version;
// coll.Collection.Folders.Add(lib);
// }
// coll.Collection.Items.Clear();
//}
}
else
{
m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: Unable to fetch folder {0}", freq.folder_id);
bad_folders.Add(freq.folder_id);
}
bad = true;
}
}
return bad;
}
private void ProcessLinks(LLSDFetchInventoryDescendents freq, InventoryCollectionWithDescendents coll)
{
InventoryCollection contents = coll.Collection;
if (freq.fetch_items && contents.Items != null)
{
List<InventoryItemBase> itemsToReturn = contents.Items;
// descendents must only include the links, not the linked items we add
coll.Descendents = itemsToReturn.Count;
// Add target items for links in this folder before the links themselves.
List<UUID> itemIDs = new List<UUID>();
List<UUID> folderIDs = new List<UUID>();
foreach (InventoryItemBase item in itemsToReturn)
{
//m_log.DebugFormat("[XXX]: {0} {1}", item.Name, item.AssetType);
if (item.AssetType == (int)AssetType.Link)
itemIDs.Add(item.AssetID);
else if (item.AssetType == (int)AssetType.LinkFolder)
folderIDs.Add(item.AssetID);
}
//m_log.DebugFormat("[XXX]: folder {0} has {1} links and {2} linkfolders", contents.FolderID, itemIDs.Count, folderIDs.Count);
// Scan for folder links and insert the items they target and those links at the head of the return data
if (folderIDs.Count > 0)
{
InventoryCollection[] linkedFolders = m_InventoryService.GetMultipleFoldersContent(coll.Collection.OwnerID, folderIDs.ToArray());
foreach (InventoryCollection linkedFolderContents in linkedFolders)
{
if (linkedFolderContents == null)
continue;
List<InventoryItemBase> links = linkedFolderContents.Items;
itemsToReturn.InsertRange(0, links);
}
}
if (itemIDs.Count > 0)
{
InventoryItemBase[] linked = m_InventoryService.GetMultipleItems(freq.owner_id, itemIDs.ToArray());
if (linked == null)
{
// OMG!!! One by one!!! This is fallback code, in case the backend isn't updated
m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: GetMultipleItems failed. Falling back to fetching inventory items one by one.");
linked = new InventoryItemBase[itemIDs.Count];
int i = 0;
InventoryItemBase item = new InventoryItemBase();
item.Owner = freq.owner_id;
foreach (UUID id in itemIDs)
{
item.ID = id;
linked[i++] = m_InventoryService.GetItem(item);
}
}
//m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Processing folder {0}. Existing items:", freq.folder_id);
//foreach (InventoryItemBase item in itemsToReturn)
// m_log.DebugFormat("[XXX]: {0} {1} {2}", item.Name, item.AssetType, item.Folder);
if (linked != null)
{
foreach (InventoryItemBase linkedItem in linked)
{
// Take care of genuinely broken links where the target doesn't exist
// HACK: Also, don't follow up links that just point to other links. In theory this is legitimate,
// but no viewer has been observed to set these up and this is the lazy way of avoiding cycles
// rather than having to keep track of every folder requested in the recursion.
if (linkedItem != null && linkedItem.AssetType != (int)AssetType.Link)
{
itemsToReturn.Insert(0, linkedItem);
//m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Added {0} {1} {2}", linkedItem.Name, linkedItem.AssetType, linkedItem.Folder);
}
}
}
}
}
}
/// <summary>
/// Convert an internal inventory folder object into an LLSD object.
/// </summary>
/// <param name="invFolder"></param>
/// <returns></returns>
private LLSDInventoryFolder ConvertInventoryFolder(InventoryFolderBase invFolder)
{
LLSDInventoryFolder llsdFolder = new LLSDInventoryFolder();
llsdFolder.folder_id = invFolder.ID;
llsdFolder.parent_id = invFolder.ParentID;
llsdFolder.name = invFolder.Name;
llsdFolder.type = invFolder.Type;
llsdFolder.preferred_type = -1;
return llsdFolder;
}
/// <summary>
/// Convert an internal inventory item object into an LLSD object.
/// </summary>
/// <param name="invItem"></param>
/// <returns></returns>
private LLSDInventoryItem ConvertInventoryItem(InventoryItemBase invItem)
{
LLSDInventoryItem llsdItem = new LLSDInventoryItem();
llsdItem.asset_id = invItem.AssetID;
llsdItem.created_at = invItem.CreationDate;
llsdItem.desc = invItem.Description;
llsdItem.flags = (int)invItem.Flags;
llsdItem.item_id = invItem.ID;
llsdItem.name = invItem.Name;
llsdItem.parent_id = invItem.Folder;
llsdItem.type = invItem.AssetType;
llsdItem.inv_type = invItem.InvType;
llsdItem.permissions = new LLSDPermissions();
llsdItem.permissions.creator_id = invItem.CreatorIdAsUuid;
llsdItem.permissions.base_mask = (int)invItem.CurrentPermissions;
llsdItem.permissions.everyone_mask = (int)invItem.EveryOnePermissions;
llsdItem.permissions.group_id = invItem.GroupID;
llsdItem.permissions.group_mask = (int)invItem.GroupPermissions;
llsdItem.permissions.is_owner_group = invItem.GroupOwned;
llsdItem.permissions.next_owner_mask = (int)invItem.NextPermissions;
llsdItem.permissions.owner_id = invItem.Owner;
llsdItem.permissions.owner_mask = (int)invItem.CurrentPermissions;
llsdItem.sale_info = new LLSDSaleInfo();
llsdItem.sale_info.sale_price = invItem.SalePrice;
llsdItem.sale_info.sale_type = invItem.SaleType;
return llsdItem;
}
}
class InventoryCollectionWithDescendents
{
public InventoryCollection Collection;
public int Descendents;
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2008 Jonathan Skeet. 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.
#endregion
namespace MoreLinq
{
#region Imports
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
static partial class MoreEnumerable
{
/// <summary>
/// Merges two ordered sequences into one. Where the elements equal
/// in both sequences, the element from the first sequence is
/// returned in the resulting sequence.
/// </summary>
/// <typeparam name="T">Type of elements in input and output sequences.</typeparam>
/// <param name="first">The first input sequence.</param>
/// <param name="second">The second input sequence.</param>
/// <returns>
/// A sequence with elements from the two input sequences merged, as
/// in a full outer join.</returns>
/// <remarks>
/// This method uses deferred execution. The behavior is undefined
/// if the sequences are unordered as inputs.
/// </remarks>
public static IEnumerable<T> OrderedMerge<T>(
this IEnumerable<T> first,
IEnumerable<T> second)
{
return OrderedMerge(first, second, null);
}
/// <summary>
/// Merges two ordered sequences into one with an additional
/// parameter specifying how to compare the elements of the
/// sequences. Where the elements equal in both sequences, the
/// element from the first sequence is returned in the resulting
/// sequence.
/// </summary>
/// <typeparam name="T">Type of elements in input and output sequences.</typeparam>
/// <param name="first">The first input sequence.</param>
/// <param name="second">The second input sequence.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> to compare elements.</param>
/// <returns>
/// A sequence with elements from the two input sequences merged, as
/// in a full outer join.</returns>
/// <remarks>
/// This method uses deferred execution. The behavior is undefined
/// if the sequences are unordered as inputs.
/// </remarks>
public static IEnumerable<T> OrderedMerge<T>(
this IEnumerable<T> first,
IEnumerable<T> second,
IComparer<T> comparer)
{
return OrderedMerge(first, second, e => e, f => f, s => s, (a, _) => a, comparer);
}
/// <summary>
/// Merges two ordered sequences into one with an additional
/// parameter specifying the element key by which the sequences are
/// ordered. Where the keys equal in both sequences, the
/// element from the first sequence is returned in the resulting
/// sequence.
/// </summary>
/// <typeparam name="T">Type of elements in input and output sequences.</typeparam>
/// <typeparam name="TKey">Type of keys used for merging.</typeparam>
/// <param name="first">The first input sequence.</param>
/// <param name="second">The second input sequence.</param>
/// <param name="keySelector">Function to extract a key given an element.</param>
/// <returns>
/// A sequence with elements from the two input sequences merged
/// according to a key, as in a full outer join.</returns>
/// <remarks>
/// This method uses deferred execution. The behavior is undefined
/// if the sequences are unordered (by key) as inputs.
/// </remarks>
public static IEnumerable<T> OrderedMerge<T, TKey>(
this IEnumerable<T> first,
IEnumerable<T> second,
Func<T, TKey> keySelector)
{
return OrderedMerge(first, second, keySelector, a => a, b => b, (a, _) => a, null);
}
/// <summary>
/// Merges two ordered sequences into one. Additional parameters
/// specify the element key by which the sequences are ordered,
/// the result when element is found in first sequence but not in
/// the second, the result when element is found in second sequence
/// but not in the first and the result when elements are found in
/// both sequences.
/// </summary>
/// <typeparam name="T">Type of elements in source sequences.</typeparam>
/// <typeparam name="TKey">Type of keys used for merging.</typeparam>
/// <typeparam name="TResult">Type of elements in the returned sequence.</typeparam>
/// <param name="first">The first input sequence.</param>
/// <param name="second">The second input sequence.</param>
/// <param name="keySelector">Function to extract a key given an element.</param>
/// <param name="firstSelector">Function to project the result element
/// when only the first sequence yields a source element.</param>
/// <param name="secondSelector">Function to project the result element
/// when only the second sequence yields a source element.</param>
/// <param name="bothSelector">Function to project the result element
/// when only both sequences yield a source element whose keys are
/// equal.</param>
/// <returns>
/// A sequence with projections from the two input sequences merged
/// according to a key, as in a full outer join.</returns>
/// <remarks>
/// This method uses deferred execution. The behavior is undefined
/// if the sequences are unordered (by key) as inputs.
/// </remarks>
public static IEnumerable<TResult> OrderedMerge<T, TKey, TResult>(
this IEnumerable<T> first,
IEnumerable<T> second,
Func<T, TKey> keySelector,
Func<T, TResult> firstSelector,
Func<T, TResult> secondSelector,
Func<T, T, TResult> bothSelector)
{
return OrderedMerge(first, second, keySelector, firstSelector, secondSelector, bothSelector, null);
}
/// <summary>
/// Merges two ordered sequences into one. Additional parameters
/// specify the element key by which the sequences are ordered,
/// the result when element is found in first sequence but not in
/// the second, the result when element is found in second sequence
/// but not in the first, the result when elements are found in
/// both sequences and a method for comparing keys.
/// </summary>
/// <typeparam name="T">Type of elements in source sequences.</typeparam>
/// <typeparam name="TKey">Type of keys used for merging.</typeparam>
/// <typeparam name="TResult">Type of elements in the returned sequence.</typeparam>
/// <param name="first">The first input sequence.</param>
/// <param name="second">The second input sequence.</param>
/// <param name="keySelector">Function to extract a key given an element.</param>
/// <param name="firstSelector">Function to project the result element
/// when only the first sequence yields a source element.</param>
/// <param name="secondSelector">Function to project the result element
/// when only the second sequence yields a source element.</param>
/// <param name="bothSelector">Function to project the result element
/// when only both sequences yield a source element whose keys are
/// equal.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param>
/// <returns>
/// A sequence with projections from the two input sequences merged
/// according to a key, as in a full outer join.</returns>
/// <remarks>
/// This method uses deferred execution. The behavior is undefined
/// if the sequences are unordered (by key) as inputs.
/// </remarks>
public static IEnumerable<TResult> OrderedMerge<T, TKey, TResult>(
this IEnumerable<T> first,
IEnumerable<T> second,
Func<T, TKey> keySelector,
Func<T, TResult> firstSelector,
Func<T, TResult> secondSelector,
Func<T, T, TResult> bothSelector,
IComparer<TKey> comparer)
{
if (keySelector == null) throw new ArgumentNullException("keySelector"); // Argument name changes to 'firstKeySelector'
return OrderedMerge(first, second, keySelector, keySelector, firstSelector, secondSelector, bothSelector, comparer);
}
/// <summary>
/// Merges two heterogeneous sequences ordered by a common key type
/// into a homogeneous one. Additional parameters specify the
/// element key by which the sequences are ordered, the result when
/// element is found in first sequence but not in the second and
/// the result when element is found in second sequence but not in
/// the first, the result when elements are found in both sequences.
/// </summary>
/// <typeparam name="TFirst">Type of elements in the first sequence.</typeparam>
/// <typeparam name="TSecond">Type of elements in the second sequence.</typeparam>
/// <typeparam name="TKey">Type of keys used for merging.</typeparam>
/// <typeparam name="TResult">Type of elements in the returned sequence.</typeparam>
/// <param name="first">The first input sequence.</param>
/// <param name="second">The second input sequence.</param>
/// <param name="firstKeySelector">Function to extract a key given an
/// element from the first sequence.</param>
/// <param name="secondKeySelector">Function to extract a key given an
/// element from the second sequence.</param>
/// <param name="firstSelector">Function to project the result element
/// when only the first sequence yields a source element.</param>
/// <param name="secondSelector">Function to project the result element
/// when only the second sequence yields a source element.</param>
/// <param name="bothSelector">Function to project the result element
/// when only both sequences yield a source element whose keys are
/// equal.</param>
/// <returns>
/// A sequence with projections from the two input sequences merged
/// according to a key, as in a full outer join.</returns>
/// <remarks>
/// This method uses deferred execution. The behavior is undefined
/// if the sequences are unordered (by key) as inputs.
/// </remarks>
public static IEnumerable<TResult> OrderedMerge<TFirst, TSecond, TKey, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TKey> firstKeySelector,
Func<TSecond, TKey> secondKeySelector,
Func<TFirst, TResult> firstSelector,
Func<TSecond, TResult> secondSelector,
Func<TFirst, TSecond, TResult> bothSelector)
{
return OrderedMerge(first, second, firstKeySelector, secondKeySelector, firstSelector, secondSelector, bothSelector, null);
}
/// <summary>
/// Merges two heterogeneous sequences ordered by a common key type
/// into a homogeneous one. Additional parameters specify the
/// element key by which the sequences are ordered, the result when
/// element is found in first sequence but not in the second,
/// the result when element is found in second sequence but not in
/// the first, the result when elements are found in both sequences
/// and a method for comparing keys.
/// </summary>
/// <typeparam name="TFirst">Type of elements in the first sequence.</typeparam>
/// <typeparam name="TSecond">Type of elements in the second sequence.</typeparam>
/// <typeparam name="TKey">Type of keys used for merging.</typeparam>
/// <typeparam name="TResult">Type of elements in the returned sequence.</typeparam>
/// <param name="first">The first input sequence.</param>
/// <param name="second">The second input sequence.</param>
/// <param name="firstKeySelector">Function to extract a key given an
/// element from the first sequence.</param>
/// <param name="secondKeySelector">Function to extract a key given an
/// element from the second sequence.</param>
/// <param name="firstSelector">Function to project the result element
/// when only the first sequence yields a source element.</param>
/// <param name="secondSelector">Function to project the result element
/// when only the second sequence yields a source element.</param>
/// <param name="bothSelector">Function to project the result element
/// when only both sequences yield a source element whose keys are
/// equal.</param>
/// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param>
/// <returns>
/// A sequence with projections from the two input sequences merged
/// according to a key, as in a full outer join.</returns>
/// <remarks>
/// This method uses deferred execution. The behavior is undefined
/// if the sequences are unordered (by key) as inputs.
/// </remarks>
public static IEnumerable<TResult> OrderedMerge<TFirst, TSecond, TKey, TResult>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TKey> firstKeySelector,
Func<TSecond, TKey> secondKeySelector,
Func<TFirst, TResult> firstSelector,
Func<TSecond, TResult> secondSelector,
Func<TFirst, TSecond, TResult> bothSelector,
IComparer<TKey> comparer)
{
if (first == null) throw new ArgumentNullException("first");
if (second == null) throw new ArgumentNullException("second");
if (firstKeySelector == null) throw new ArgumentNullException("firstKeySelector");
if (secondKeySelector == null) throw new ArgumentNullException("secondKeySelector");
if (firstSelector == null) throw new ArgumentNullException("firstSelector");
if (bothSelector == null) throw new ArgumentNullException("bothSelector");
if (secondSelector == null) throw new ArgumentNullException("secondSelector");
return OrderedMergeImpl(first, second,
firstKeySelector, secondKeySelector,
firstSelector, secondSelector, bothSelector,
comparer ?? Comparer<TKey>.Default);
}
static IEnumerable<TResult> OrderedMergeImpl<TFirst, TSecond, TKey, TResult>(
IEnumerable<TFirst> first,
IEnumerable<TSecond> second,
Func<TFirst, TKey> firstKeySelector,
Func<TSecond, TKey> secondKeySelector,
Func<TFirst, TResult> firstSelector,
Func<TSecond, TResult> secondSelector,
Func<TFirst, TSecond, TResult> bothSelector,
IComparer<TKey> comparer)
{
Debug.Assert(first != null);
Debug.Assert(second != null);
Debug.Assert(firstKeySelector != null);
Debug.Assert(secondKeySelector != null);
Debug.Assert(firstSelector != null);
Debug.Assert(secondSelector != null);
Debug.Assert(bothSelector != null);
Debug.Assert(comparer != null);
using (var e1 = first.GetEnumerator())
using (var e2 = second.GetEnumerator())
{
var gotFirst = e1.MoveNext();
var gotSecond = e2.MoveNext();
while (gotFirst || gotSecond)
{
if (gotFirst && gotSecond)
{
var element1 = e1.Current;
var key1 = firstKeySelector(element1);
var element2 = e2.Current;
var key2 = secondKeySelector(element2);
var comparison = comparer.Compare(key1, key2);
if (comparison < 0)
{
yield return firstSelector(element1);
gotFirst = e1.MoveNext();
}
else if (comparison > 0)
{
yield return secondSelector(element2);
gotSecond = e2.MoveNext();
}
else
{
yield return bothSelector(element1, element2);
gotFirst = e1.MoveNext();
gotSecond = e2.MoveNext();
}
}
else if (gotSecond)
{
yield return secondSelector(e2.Current);
gotSecond = e2.MoveNext();
}
else // (gotFirst)
{
yield return firstSelector(e1.Current);
gotFirst = e1.MoveNext();
}
}
}
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon 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.Linq;
using System.Text;
using ProtoBuf;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Scenes.Serialization;
namespace InWorldz.Region.Data.Thoosa.Serialization
{
/// <summary>
/// A snapshot in time of the current state of a SceneObjectPart that is
/// also protobuf serializable
/// </summary>
[ProtoContract]
public class SceneObjectPartSnapshot
{
[ProtoMember(1)]
public Guid Id;
[ProtoMember(2)]
public string Name;
[ProtoMember(3)]
public string Description;
[ProtoMember(4)]
public int[] PayPrice;
[ProtoMember(5)]
public Guid Sound;
[ProtoMember(6)]
public byte SoundFlags;
[ProtoMember(7)]
public float SoundGain;
[ProtoMember(8)]
public float SoundRadius;
[ProtoMember(9)]
public byte[] SerializedPhysicsData;
[ProtoMember(10)]
public Guid CreatorId;
[ProtoMember(11)]
public TaskInventorySnapshot Inventory;
[ProtoMember(12)]
public OpenMetaverse.PrimFlags ObjectFlags;
[ProtoMember(13)]
public uint LocalId;
[ProtoMember(14)]
public OpenMetaverse.Material Material;
[ProtoMember(15)]
public bool PassTouches;
[ProtoMember(16)]
public ulong RegionHandle;
[ProtoMember(17)]
public int ScriptAccessPin;
[ProtoMember(18)]
public byte[] TextureAnimation;
[ProtoMember(19)]
public OpenMetaverse.Vector3 GroupPosition;
[ProtoMember(20)]
public OpenMetaverse.Vector3 OffsetPosition;
[ProtoMember(21)]
public OpenMetaverse.Quaternion RotationOffset;
[ProtoMember(22)]
public OpenMetaverse.Vector3 Velocity;
/// <summary>
/// This maps to the old angular velocity property on the prim which
/// now is used only to store omegas
/// </summary>
[ProtoMember(23)]
public OpenMetaverse.Vector3 AngularVelocityTarget;
/// <summary>
/// This is the new physical angular velocity
/// </summary>
[ProtoMember(24)]
public OpenMetaverse.Vector3 AngularVelocity;
public System.Drawing.Color TextColor {get; set;}
[ProtoMember(25, DataFormat=DataFormat.FixedSize)]
private int SerializedTextColor
{
get { return TextColor.ToArgb(); }
set { TextColor = System.Drawing.Color.FromArgb(value); }
}
[ProtoMember(26)]
public string HoverText;
[ProtoMember(27)]
public string SitName;
[ProtoMember(28)]
public string TouchName;
[ProtoMember(29)]
public int LinkNumber;
[ProtoMember(30)]
public byte ClickAction;
[ProtoMember(31)]
public PrimShapeSnapshot Shape;
[ProtoMember(32)]
public OpenMetaverse.Vector3 Scale;
[ProtoMember(33)]
public OpenMetaverse.Quaternion SitTargetOrientation;
[ProtoMember(34)]
public OpenMetaverse.Vector3 SitTargetPosition;
[ProtoMember(35)]
public uint ParentId;
[ProtoMember(36)]
public int CreationDate;
[ProtoMember(37)]
public uint Category;
[ProtoMember(38)]
public int SalePrice;
[ProtoMember(39)]
public byte ObjectSaleType;
[ProtoMember(40)]
public int OwnershipCost;
[ProtoMember(41)]
public Guid GroupId;
[ProtoMember(42)]
public Guid OwnerId;
[ProtoMember(43)]
public Guid LastOwnerId;
[ProtoMember(44)]
public uint BaseMask;
[ProtoMember(45)]
public uint OwnerMask;
[ProtoMember(46)]
public uint GroupMask;
[ProtoMember(47)]
public uint EveryoneMask;
[ProtoMember(48)]
public uint NextOwnerMask;
[ProtoMember(49)]
public byte SavedAttachmentPoint;
[ProtoMember(50)]
public OpenMetaverse.Vector3 SavedAttachmentPos;
[ProtoMember(51)]
public OpenMetaverse.Quaternion SavedAttachmentRot;
[ProtoMember(52)]
public OpenMetaverse.PrimFlags Flags;
[ProtoMember(53)]
public Guid CollisionSound;
[ProtoMember(54)]
public float CollisionSoundVolume;
/// <summary>
/// Script states by [Item Id, Data]
/// </summary>
[ProtoMember(55)]
public Dictionary<Guid, byte[]> SerializedScriptStates;
[ProtoMember(56)]
public string MediaUrl;
[ProtoMember(57)]
public byte[] ParticleSystem;
/// <summary>
/// Contains a collection of serialized script bytecode that go with this prim/part
/// May be null if these are not required
/// </summary>
[ProtoMember(58)]
public Dictionary<Guid, byte[]> SeralizedScriptBytecode;
/// <summary>
/// Contains a collection of physx serialized convex meshes that go with this prim/part
/// May be null if these are not requested
/// </summary>
[ProtoMember(59)]
public byte[] SerializedPhysicsShapes;
/// <summary>
/// Stores the item ID that is associated with a worn attachment
/// </summary>
[ProtoMember(60)]
public Guid FromItemId;
[ProtoMember(61)]
public float ServerWeight;
[ProtoMember(62)]
public float StreamingCost;
[ProtoMember(63)]
public KeyframeAnimationSnapshot KeyframeAnimation;
static SceneObjectPartSnapshot()
{
ProtoBuf.Serializer.PrepareSerializer<SceneObjectPartSnapshot>();
}
static public SceneObjectPartSnapshot FromSceneObjectPart(SceneObjectPart part, SerializationFlags flags)
{
bool serializePhysicsShapes = (flags & SerializationFlags.SerializePhysicsShapes) != 0;
bool serializeScriptBytecode = (flags & SerializationFlags.SerializeScriptBytecode) != 0;
StopScriptReason stopScriptReason;
if ((flags & SerializationFlags.StopScripts) == 0)
{
stopScriptReason = StopScriptReason.None;
}
else
{
if ((flags & SerializationFlags.FromCrossing) != 0)
stopScriptReason = StopScriptReason.Crossing;
else
stopScriptReason = StopScriptReason.Derez;
}
SceneObjectPartSnapshot partSnap = new SceneObjectPartSnapshot
{
AngularVelocity = part.PhysicalAngularVelocity,
AngularVelocityTarget = part.AngularVelocity,
BaseMask = part.BaseMask,
Category = part.Category,
ClickAction = part.ClickAction,
CollisionSound = part.CollisionSound.Guid,
CollisionSoundVolume = part.CollisionSoundVolume,
CreationDate = part.CreationDate,
CreatorId = part.CreatorID.Guid,
Description = part.Description,
EveryoneMask = part.EveryoneMask,
Flags = part.Flags,
GroupId = part.GroupID.Guid,
GroupMask = part.GroupMask,
//if this is an attachment, dont fill out the group position. This prevents an issue where
//a user is crossing to a new region and the vehicle has already been sent. Since the attachment's
//group position is actually the wearer's position and the wearer's position is the vehicle position,
//trying to get the attachment grp pos triggers an error and a ton of log spam.
GroupPosition = part.ParentGroup.IsAttachment ? OpenMetaverse.Vector3.Zero : part.GroupPosition,
HoverText = part.Text,
Id = part.UUID.Guid,
Inventory = TaskInventorySnapshot.FromTaskInventory(part),
KeyframeAnimation = KeyframeAnimationSnapshot.FromKeyframeAnimation(part.KeyframeAnimation),
LastOwnerId = part.LastOwnerID.Guid,
LinkNumber = part.LinkNum,
LocalId = part.LocalId,
Material = (OpenMetaverse.Material)part.Material,
MediaUrl = part.MediaUrl,
Name = part.Name,
NextOwnerMask = part.NextOwnerMask,
ObjectFlags = (OpenMetaverse.PrimFlags)part.ObjectFlags,
ObjectSaleType = part.ObjectSaleType,
OffsetPosition = part.OffsetPosition,
OwnerId = part.OwnerID.Guid,
OwnerMask = part.OwnerMask,
OwnershipCost = part.OwnershipCost,
ParentId = part.ParentID,
ParticleSystem = part.ParticleSystem,
PassTouches = part.PassTouches,
PayPrice = part.PayPrice,
RegionHandle = part.RegionHandle,
RotationOffset = part.RotationOffset,
SalePrice = part.SalePrice,
SavedAttachmentPoint = part.SavedAttachmentPoint,
SavedAttachmentPos = part.SavedAttachmentPos,
SavedAttachmentRot = part.SavedAttachmentRot,
Scale = part.Scale,
ScriptAccessPin = part.ScriptAccessPin,
SerializedPhysicsData = part.SerializedPhysicsData,
ServerWeight = part.ServerWeight,
Shape = PrimShapeSnapshot.FromShape(part.Shape),
SitName = part.SitName,
SitTargetOrientation = part.SitTargetOrientation,
SitTargetPosition = part.SitTargetPosition,
Sound = part.Sound.Guid,
SoundFlags = part.SoundOptions,
SoundGain = part.SoundGain,
SoundRadius = part.SoundRadius,
StreamingCost = part.StreamingCost,
TextColor = part.TextColor,
TextureAnimation = part.TextureAnimation,
TouchName = part.TouchName,
Velocity = part.Velocity,
FromItemId = part.FromItemID.Guid
};
Dictionary<OpenMetaverse.UUID, byte[]> states;
Dictionary<OpenMetaverse.UUID, byte[]> byteCode;
if (serializeScriptBytecode)
{
Tuple<Dictionary<OpenMetaverse.UUID, byte[]>, Dictionary<OpenMetaverse.UUID, byte[]>>
statesAndBytecode = part.Inventory.GetBinaryScriptStatesAndCompiledScripts(stopScriptReason);
states = statesAndBytecode.Item1;
byteCode = statesAndBytecode.Item2;
}
else
{
states = part.Inventory.GetBinaryScriptStates(stopScriptReason);
byteCode = null;
}
partSnap.SerializedScriptStates = new Dictionary<Guid, byte[]>(states.Count);
foreach (var kvp in states)
{
//map from UUID to Guid
partSnap.SerializedScriptStates[kvp.Key.Guid] = kvp.Value;
}
if (byteCode != null)
{
partSnap.SeralizedScriptBytecode = new Dictionary<Guid, byte[]>();
foreach (var kvp in byteCode)
{
//map from UUID to Guid
partSnap.SeralizedScriptBytecode[kvp.Key.Guid] = kvp.Value;
}
}
if (serializePhysicsShapes)
{
partSnap.SerializedPhysicsShapes = part.SerializedPhysicsShapes;
}
return partSnap;
}
internal SceneObjectPart ToSceneObjectPart()
{
SceneObjectPart sop = new SceneObjectPart
{
AngularVelocity = this.AngularVelocityTarget,
PhysicalAngularVelocity = this.AngularVelocity,
BaseMask = this.BaseMask,
Category = this.Category,
ClickAction = this.ClickAction,
CollisionSound = new OpenMetaverse.UUID(this.CollisionSound),
CollisionSoundVolume = this.CollisionSoundVolume,
CreationDate = this.CreationDate,
CreatorID = new OpenMetaverse.UUID(this.CreatorId),
Description = this.Description,
EveryoneMask = this.EveryoneMask,
Flags = this.Flags,
GroupID = new OpenMetaverse.UUID(this.GroupId),
GroupMask = this.GroupMask,
GroupPosition = this.GroupPosition,
Text = this.HoverText,
UUID = new OpenMetaverse.UUID(this.Id),
TaskInventory = this.Inventory.ToTaskInventory(),
LastOwnerID = new OpenMetaverse.UUID(this.LastOwnerId),
LinkNum = this.LinkNumber,
LocalId = this.LocalId,
Material = (byte)this.Material,
MediaUrl = this.MediaUrl,
Name = this.Name,
NextOwnerMask = this.NextOwnerMask,
ObjectFlags = (uint)this.ObjectFlags,
ObjectSaleType = this.ObjectSaleType,
OffsetPosition = this.OffsetPosition,
OwnerID = new OpenMetaverse.UUID(this.OwnerId),
OwnerMask = this.OwnerMask,
OwnershipCost = this.OwnershipCost,
ParentID = this.ParentId,
ParticleSystem = this.ParticleSystem,
PassTouches = this.PassTouches,
PayPrice = this.PayPrice,
RegionHandle = this.RegionHandle,
RotationOffset = this.RotationOffset,
SalePrice = this.SalePrice,
SavedAttachmentPoint = this.SavedAttachmentPoint,
SavedAttachmentPos = this.SavedAttachmentPos,
SavedAttachmentRot = this.SavedAttachmentRot,
Scale = this.Scale,
ScriptAccessPin = this.ScriptAccessPin,
SerializedPhysicsData = this.SerializedPhysicsData,
ServerWeight = this.ServerWeight,
Shape = this.Shape.ToPrimitiveBaseShape(),
SitName = this.SitName,
SitTargetOrientation = this.SitTargetOrientation,
SitTargetPosition = this.SitTargetPosition,
Sound = new OpenMetaverse.UUID(this.Sound),
SoundOptions = this.SoundFlags,
SoundGain = this.SoundGain,
SoundRadius = this.SoundRadius,
StreamingCost = this.StreamingCost,
TextColor = this.TextColor,
TextureAnimation = this.TextureAnimation,
TouchName = this.TouchName,
Velocity = this.Velocity,
SerializedPhysicsShapes = this.SerializedPhysicsShapes,
FromItemID = new OpenMetaverse.UUID(this.FromItemId),
KeyframeAnimation = this.KeyframeAnimation == null ? null : this.KeyframeAnimation.ToKeyframeAnimation()
};
if (SerializedScriptStates != null)
{
var states = new Dictionary<OpenMetaverse.UUID, byte[]>(SerializedScriptStates.Count);
foreach (var kvp in SerializedScriptStates)
{
//map from Guid to UUID
states.Add(new OpenMetaverse.UUID(kvp.Key), kvp.Value);
}
sop.SetSavedScriptStates(states);
}
if (SeralizedScriptBytecode != null)
{
var byteCode = new Dictionary<OpenMetaverse.UUID, byte[]>(SeralizedScriptBytecode.Count);
foreach (var kvp in SeralizedScriptBytecode)
{
//map from Guid to UUID
byteCode.Add(new OpenMetaverse.UUID(kvp.Key), kvp.Value);
}
sop.SerializedScriptByteCode = byteCode;
}
return sop;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Buffers;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal.AnyOS
{
internal sealed partial class ManagedPkcsPal : PkcsPal
{
private static readonly byte[] s_rsaPkcsParameters = { 0x05, 0x00 };
private static readonly byte[] s_rsaOaepSha1Parameters = { 0x30, 0x00 };
internal sealed class ManagedKeyTransPal : KeyTransRecipientInfoPal
{
private readonly KeyTransRecipientInfoAsn _asn;
internal ManagedKeyTransPal(KeyTransRecipientInfoAsn asn)
{
_asn = asn;
}
public override byte[] EncryptedKey =>
_asn.EncryptedKey.ToArray();
public override AlgorithmIdentifier KeyEncryptionAlgorithm =>
_asn.KeyEncryptionAlgorithm.ToPresentationObject();
public override SubjectIdentifier RecipientIdentifier =>
new SubjectIdentifier(_asn.Rid.IssuerAndSerialNumber, _asn.Rid.SubjectKeyIdentifier);
public override int Version => _asn.Version;
internal byte[] DecryptCek(X509Certificate2 cert, RSA privateKey, out Exception exception)
{
ReadOnlyMemory<byte>? parameters = _asn.KeyEncryptionAlgorithm.Parameters;
string keyEncryptionAlgorithm = _asn.KeyEncryptionAlgorithm.Algorithm.Value;
switch (keyEncryptionAlgorithm)
{
case Oids.Rsa:
if (parameters != null &&
!parameters.Value.Span.SequenceEqual(s_rsaPkcsParameters))
{
exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
return null;
}
break;
case Oids.RsaOaep:
if (parameters != null &&
!parameters.Value.Span.SequenceEqual(s_rsaOaepSha1Parameters))
{
exception = new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
return null;
}
break;
default:
exception = new CryptographicException(
SR.Cryptography_Cms_UnknownAlgorithm,
_asn.KeyEncryptionAlgorithm.Algorithm.Value);
return null;
}
return DecryptCekCore(cert, privateKey, _asn.EncryptedKey.Span, keyEncryptionAlgorithm, out exception);
}
internal static byte[] DecryptCekCore(
X509Certificate2 cert,
RSA privateKey,
ReadOnlySpan<byte> encrypedKey,
string keyEncryptionAlgorithm,
out Exception exception)
{
RSAEncryptionPadding encryptionPadding;
switch (keyEncryptionAlgorithm)
{
case Oids.Rsa:
encryptionPadding = RSAEncryptionPadding.Pkcs1;
break;
case Oids.RsaOaep:
encryptionPadding = RSAEncryptionPadding.OaepSHA1;
break;
default:
exception = new CryptographicException(
SR.Cryptography_Cms_UnknownAlgorithm,
keyEncryptionAlgorithm);
return null;
}
if (privateKey != null)
{
return DecryptKey(privateKey, encryptionPadding, encrypedKey, out exception);
}
else
{
using (RSA rsa = cert.GetRSAPrivateKey())
{
return DecryptKey(rsa, encryptionPadding, encrypedKey, out exception);
}
}
}
}
private KeyTransRecipientInfoAsn MakeKtri(
byte[] cek,
CmsRecipient recipient,
out bool v0Recipient)
{
KeyTransRecipientInfoAsn ktri = new KeyTransRecipientInfoAsn();
if (recipient.RecipientIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier)
{
ktri.Version = 2;
ktri.Rid.SubjectKeyIdentifier = GetSubjectKeyIdentifier(recipient.Certificate);
}
else if (recipient.RecipientIdentifierType == SubjectIdentifierType.IssuerAndSerialNumber)
{
byte[] serial = recipient.Certificate.GetSerialNumber();
Array.Reverse(serial);
IssuerAndSerialNumberAsn iasn = new IssuerAndSerialNumberAsn
{
Issuer = recipient.Certificate.IssuerName.RawData,
SerialNumber = serial,
};
ktri.Rid.IssuerAndSerialNumber = iasn;
}
else
{
throw new CryptographicException(
SR.Cryptography_Cms_Invalid_Subject_Identifier_Type,
recipient.RecipientIdentifierType.ToString());
}
RSAEncryptionPadding padding;
switch (recipient.Certificate.GetKeyAlgorithm())
{
case Oids.RsaOaep:
padding = RSAEncryptionPadding.OaepSHA1;
ktri.KeyEncryptionAlgorithm.Algorithm = new Oid(Oids.RsaOaep, Oids.RsaOaep);
ktri.KeyEncryptionAlgorithm.Parameters = s_rsaOaepSha1Parameters;
break;
default:
padding = RSAEncryptionPadding.Pkcs1;
ktri.KeyEncryptionAlgorithm.Algorithm = new Oid(Oids.Rsa, Oids.Rsa);
ktri.KeyEncryptionAlgorithm.Parameters = s_rsaPkcsParameters;
break;
}
using (RSA rsa = recipient.Certificate.GetRSAPublicKey())
{
ktri.EncryptedKey = rsa.Encrypt(cek, padding);
}
v0Recipient = (ktri.Version == 0);
return ktri;
}
private static byte[] DecryptKey(
RSA privateKey,
RSAEncryptionPadding encryptionPadding,
ReadOnlySpan<byte> encryptedKey,
out Exception exception)
{
if (privateKey == null)
{
exception = new CryptographicException(SR.Cryptography_Cms_Signing_RequiresPrivateKey);
return null;
}
#if netcoreapp
byte[] cek = null;
int cekLength = 0;
try
{
cek = ArrayPool<byte>.Shared.Rent(privateKey.KeySize / 8);
if (!privateKey.TryDecrypt(encryptedKey, cek, encryptionPadding, out cekLength))
{
Debug.Fail("TryDecrypt wanted more space than the key size");
exception = new CryptographicException();
return null;
}
exception = null;
return new Span<byte>(cek, 0, cekLength).ToArray();
}
catch (CryptographicException e)
{
exception = e;
return null;
}
finally
{
if (cek != null)
{
Array.Clear(cek, 0, cekLength);
ArrayPool<byte>.Shared.Return(cek);
}
}
#else
try
{
exception = null;
return privateKey.Decrypt(encryptedKey.ToArray(), encryptionPadding);
}
catch (CryptographicException e)
{
exception = e;
return null;
}
#endif
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
/// Blends between the scene and the tone mapped scene.
$HDRPostFX::enableToneMapping = 0.5;
/// The tone mapping middle grey or exposure value used
/// to adjust the overall "balance" of the image.
///
/// 0.18 is fairly common value.
///
$HDRPostFX::keyValue = 0.18;
/// The minimum luninace value to allow when tone mapping
/// the scene. Is particularly useful if your scene very
/// dark or has a black ambient color in places.
$HDRPostFX::minLuminace = 0.001;
/// The lowest luminance value which is mapped to white. This
/// is usually set to the highest visible luminance in your
/// scene. By setting this to smaller values you get a contrast
/// enhancement.
$HDRPostFX::whiteCutoff = 1.0;
/// The rate of adaptation from the previous and new
/// average scene luminance.
$HDRPostFX::adaptRate = 2.0;
/// Blends between the scene and the blue shifted version
/// of the scene for a cinematic desaturated night effect.
$HDRPostFX::enableBlueShift = 0.0;
/// The blue shift color value.
$HDRPostFX::blueShiftColor = "1.05 0.97 1.27";
/// Blends between the scene and the bloomed scene.
$HDRPostFX::enableBloom = 1.0;
/// The threshold luminace value for pixels which are
/// considered "bright" and need to be bloomed.
$HDRPostFX::brightPassThreshold = 1.0;
/// These are used in the gaussian blur of the
/// bright pass for the bloom effect.
$HDRPostFX::gaussMultiplier = 0.3;
$HDRPostFX::gaussMean = 0.0;
$HDRPostFX::gaussStdDev = 0.8;
/// The 1x255 color correction ramp texture used
/// by both the HDR shader and the GammaPostFx shader
/// for doing full screen color correction.
$HDRPostFX::colorCorrectionRamp = "core/postFX/images/null_color_ramp.png";
singleton ShaderData( HDR_BrightPassShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/postFxV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/brightPassFilterP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/gl/postFxV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/gl/brightPassFilterP.glsl";
samplerNames[0] = "$inputTex";
samplerNames[1] = "$luminanceTex";
pixVersion = 3.0;
};
singleton ShaderData( HDR_DownScale4x4Shader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/downScale4x4V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/downScale4x4P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/gl/downScale4x4V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/gl/downScale4x4P.glsl";
samplerNames[0] = "$inputTex";
pixVersion = 2.0;
};
singleton ShaderData( HDR_BloomGaussBlurHShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/postFxV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/bloomGaussBlurHP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/gl/postFxV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/gl/bloomGaussBlurHP.glsl";
samplerNames[0] = "$inputTex";
pixVersion = 3.0;
};
singleton ShaderData( HDR_BloomGaussBlurVShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/postFxV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/bloomGaussBlurVP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/gl/postFxV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/gl/bloomGaussBlurVP.glsl";
samplerNames[0] = "$inputTex";
pixVersion = 3.0;
};
singleton ShaderData( HDR_SampleLumShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/postFxV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/sampleLumInitialP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/gl/postFxV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/gl/sampleLumInitialP.glsl";
samplerNames[0] = "$inputTex";
pixVersion = 3.0;
};
singleton ShaderData( HDR_DownSampleLumShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/postFxV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/sampleLumIterativeP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/gl/postFxV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/gl/sampleLumIterativeP.glsl";
samplerNames[0] = "$inputTex";
pixVersion = 3.0;
};
singleton ShaderData( HDR_CalcAdaptedLumShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/postFxV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/calculateAdaptedLumP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/gl/postFxV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/gl/calculateAdaptedLumP.glsl";
samplerNames[0] = "$currLum";
samplerNames[1] = "$lastAdaptedLum";
pixVersion = 3.0;
};
singleton ShaderData( HDR_CombineShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/postFxV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/finalPassCombineP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/gl/postFxV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/gl/finalPassCombineP.glsl";
samplerNames[0] = "$sceneTex";
samplerNames[1] = "$luminanceTex";
samplerNames[2] = "$bloomTex";
samplerNames[3] = "$colorCorrectionTex";
samplerNames[4] = "deferredTex";
pixVersion = 3.0;
};
singleton GFXStateBlockData( HDR_SampleStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerClampPoint;
};
singleton GFXStateBlockData( HDR_DownSampleStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
};
singleton GFXStateBlockData( HDR_CombineStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerClampLinear;
samplerStates[2] = SamplerClampLinear;
samplerStates[3] = SamplerClampLinear;
};
singleton GFXStateBlockData( HDRStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampLinear;
samplerStates[2] = SamplerClampLinear;
samplerStates[3] = SamplerClampLinear;
blendDefined = true;
blendDest = GFXBlendOne;
blendSrc = GFXBlendZero;
zDefined = true;
zEnable = false;
zWriteEnable = false;
cullDefined = true;
cullMode = GFXCullNone;
};
function HDRPostFX::setShaderConsts( %this )
{
%this.setShaderConst( "$brightPassThreshold", $HDRPostFX::brightPassThreshold );
%this.setShaderConst( "$g_fMiddleGray", $HDRPostFX::keyValue );
%bloomH = %this-->bloomH;
%bloomH.setShaderConst( "$gaussMultiplier", $HDRPostFX::gaussMultiplier );
%bloomH.setShaderConst( "$gaussMean", $HDRPostFX::gaussMean );
%bloomH.setShaderConst( "$gaussStdDev", $HDRPostFX::gaussStdDev );
%bloomV = %this-->bloomV;
%bloomV.setShaderConst( "$gaussMultiplier", $HDRPostFX::gaussMultiplier );
%bloomV.setShaderConst( "$gaussMean", $HDRPostFX::gaussMean );
%bloomV.setShaderConst( "$gaussStdDev", $HDRPostFX::gaussStdDev );
%minLuminace = $HDRPostFX::minLuminace;
if ( %minLuminace <= 0.0 )
{
// The min should never be pure zero else the
// log() in the shader will generate INFs.
%minLuminace = 0.00001;
}
%this-->adaptLum.setShaderConst( "$g_fMinLuminace", %minLuminace );
%this-->finalLum.setShaderConst( "$adaptRate", $HDRPostFX::adaptRate );
%combinePass = %this-->combinePass;
%combinePass.setShaderConst( "$g_fEnableToneMapping", $HDRPostFX::enableToneMapping );
%combinePass.setShaderConst( "$g_fMiddleGray", $HDRPostFX::keyValue );
%combinePass.setShaderConst( "$g_fBloomScale", $HDRPostFX::enableBloom );
%combinePass.setShaderConst( "$g_fEnableBlueShift", $HDRPostFX::enableBlueShift );
%combinePass.setShaderConst( "$g_fBlueShiftColor", $HDRPostFX::blueShiftColor );
%clampedGamma = mClamp( $pref::Video::Gamma, 2.0, 2.5);
%combinePass.setShaderConst( "$g_fOneOverGamma", 1 / %clampedGamma );
%combinePass.setShaderConst( "$Brightness", $pref::Video::Brightness );
%combinePass.setShaderConst( "$Contrast", $pref::Video::Contrast );
%whiteCutoff = ( $HDRPostFX::whiteCutoff * $HDRPostFX::whiteCutoff ) *
( $HDRPostFX::whiteCutoff * $HDRPostFX::whiteCutoff );
%combinePass.setShaderConst( "$g_fWhiteCutoff", %whiteCutoff );
}
function HDRPostFX::preProcess( %this )
{
%combinePass = %this-->combinePass;
if ( %combinePass.texture[3] !$= $HDRPostFX::colorCorrectionRamp )
%combinePass.setTexture( 3, $HDRPostFX::colorCorrectionRamp );
}
function HDRPostFX::onEnabled( %this )
{
// See what HDR format would be best.
%format = getBestHDRFormat();
if ( %format $= "" || %format $= "GFXFormatR8G8B8A8" )
{
// We didn't get a valid HDR format... so fail.
return false;
}
// HDR does it's own gamma calculation so
// disable this postFx.
GammaPostFX.disable();
// Set the right global shader define for HDR.
if ( %format $= "GFXFormatR10G10B10A2" )
addGlobalShaderMacro( "TORQUE_HDR_RGB10" );
else if ( %format $= "GFXFormatR16G16B16A16" )
addGlobalShaderMacro( "TORQUE_HDR_RGB16" );
echo( "HDR FORMAT: " @ %format );
// Change the format of the offscreen surface
// to an HDR compatible format.
AL_FormatToken.format = %format;
setReflectFormat( %format );
// Reset the light manager which will ensure the new
// hdr encoding takes effect in all the shaders and
// that the offscreen surface is enabled.
resetLightManager();
return true;
}
function HDRPostFX::onDisabled( %this )
{
// Enable a special GammaCorrection PostFX when this is disabled.
GammaPostFX.enable();
// Restore the non-HDR offscreen surface format.
%format = getBestHDRFormat();
AL_FormatToken.format = %format;
setReflectFormat( %format );
removeGlobalShaderMacro( "TORQUE_HDR_RGB10" );
removeGlobalShaderMacro( "TORQUE_HDR_RGB16" );
// Reset the light manager which will ensure the new
// hdr encoding takes effect in all the shaders.
resetLightManager();
}
singleton PostEffect( HDRPostFX )
{
isEnabled = false;
allowReflectPass = false;
// Resolve the HDR before we render any editor stuff
// and before we resolve the scene to the backbuffer.
renderTime = "PFXBeforeBin";
renderBin = "EditorBin";
renderPriority = 9999;
// The bright pass generates a bloomed version of
// the scene for pixels which are brighter than a
// fixed threshold value.
//
// This is then used in the final HDR combine pass
// at the end of this post effect chain.
//
shader = HDR_BrightPassShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$backBuffer";
texture[1] = "#adaptedLum";
target = "$outTex";
targetFormat = "GFXFormatR16G16B16A16F";
targetScale = "0.5 0.5";
new PostEffect()
{
allowReflectPass = false;
shader = HDR_DownScale4x4Shader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
target = "$outTex";
targetFormat = "GFXFormatR16G16B16A16F";
targetScale = "0.25 0.25";
};
new PostEffect()
{
allowReflectPass = false;
internalName = "bloomH";
shader = HDR_BloomGaussBlurHShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
target = "$outTex";
targetFormat = "GFXFormatR16G16B16A16F";
};
new PostEffect()
{
allowReflectPass = false;
internalName = "bloomV";
shader = HDR_BloomGaussBlurVShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
target = "#bloomFinal";
targetFormat = "GFXFormatR16G16B16A16F";
};
// BrightPass End
// Now calculate the adapted luminance.
new PostEffect()
{
allowReflectPass = false;
internalName = "adaptLum";
shader = HDR_SampleLumShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$backBuffer";
target = "$outTex";
targetScale = "0.0625 0.0625"; // 1/16th
targetFormat = "GFXFormatR16F";
new PostEffect()
{
allowReflectPass = false;
shader = HDR_DownSampleLumShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
target = "$outTex";
targetScale = "0.25 0.25"; // 1/4
targetFormat = "GFXFormatR16F";
};
new PostEffect()
{
allowReflectPass = false;
shader = HDR_DownSampleLumShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
target = "$outTex";
targetScale = "0.25 0.25"; // 1/4
targetFormat = "GFXFormatR16F";
};
new PostEffect()
{
allowReflectPass = false;
shader = HDR_DownSampleLumShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
target = "$outTex";
targetScale = "0.25 0.25"; // At this point the target should be 1x1.
targetFormat = "GFXFormatR16F";
};
// Note that we're reading the adapted luminance
// from the previous frame when generating this new
// one... PostEffect takes care to manage that.
new PostEffect()
{
allowReflectPass = false;
internalName = "finalLum";
shader = HDR_CalcAdaptedLumShader;
stateBlock = HDR_DownSampleStateBlock;
texture[0] = "$inTex";
texture[1] = "#adaptedLum";
target = "#adaptedLum";
targetFormat = "GFXFormatR16F";
targetClear = "PFXTargetClear_OnCreate";
targetClearColor = "1 1 1 1";
};
};
// Output the combined bloom and toned mapped
// version of the scene.
new PostEffect()
{
allowReflectPass = false;
internalName = "combinePass";
shader = HDR_CombineShader;
stateBlock = HDR_CombineStateBlock;
texture[0] = "$backBuffer";
texture[1] = "#adaptedLum";
texture[2] = "#bloomFinal";
texture[3] = $HDRPostFX::colorCorrectionRamp;
target = "$backBuffer";
};
};
singleton ShaderData( LuminanceVisShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/postFxV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/luminanceVisP.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/gl/postFxV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/hdr/gl/luminanceVisP.glsl";
samplerNames[0] = "$inputTex";
pixVersion = 3.0;
};
singleton GFXStateBlockData( LuminanceVisStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
};
function LuminanceVisPostFX::setShaderConsts( %this )
{
%this.setShaderConst( "$brightPassThreshold", $HDRPostFX::brightPassThreshold );
}
singleton PostEffect( LuminanceVisPostFX )
{
isEnabled = false;
allowReflectPass = false;
// Render before we do any editor rendering.
renderTime = "PFXBeforeBin";
renderBin = "EditorBin";
renderPriority = 9999;
shader = LuminanceVisShader;
stateBlock = LuminanceVisStateBlock;
texture[0] = "$backBuffer";
target = "$backBuffer";
//targetScale = "0.0625 0.0625"; // 1/16th
//targetFormat = "GFXFormatR16F";
};
function LuminanceVisPostFX::onEnabled( %this )
{
if ( !HDRPostFX.isEnabled() )
{
HDRPostFX.enable();
}
HDRPostFX.skip = true;
return true;
}
function LuminanceVisPostFX::onDisabled( %this )
{
HDRPostFX.skip = false;
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Globalization {
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
/*=================================KoreanCalendar==========================
**
** Korean calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar.
** That is,
** Korean year = Gregorian year + 2333. So 2000/01/01 A.D. is Korean 4333/01/01
**
** 0001/1/1 A.D. is Korean year 2334.
**
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 0001/01/01 9999/12/31
** Korean 2334/01/01 12332/12/31
============================================================================*/
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable] public class KoreanCalendar: Calendar {
//
// The era value for the current era.
//
public const int KoreanEra = 1;
// Since
// Gregorian Year = Era Year + yearOffset
// Gregorian Year 1 is Korean year 2334, so that
// 1 = 2334 + yearOffset
// So yearOffset = -2333
// Gregorian year 2001 is Korean year 4334.
//m_EraInfo[0] = new EraInfo(1, new DateTime(1, 1, 1).Ticks, -2333, 2334, GregorianCalendar.MaxYear + 2333);
// Initialize our era info.
static internal EraInfo[] koreanEraInfo = new EraInfo[] {
new EraInfo( 1, 1, 1, 1, -2333, 2334, GregorianCalendar.MaxYear + 2333) // era #, start year/month/day, yearOffset, minEraYear
};
internal GregorianCalendarHelper helper;
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
// Return the type of the Korean calendar.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of KoreanCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance() {
if (m_defaultInstance == null) {
m_defaultInstance = new KoreanCalendar();
}
return (m_defaultInstance);
}
*/
public KoreanCalendar() {
try {
new CultureInfo("ko-KR");
} catch (ArgumentException e) {
throw new TypeInitializationException(this.GetType().FullName, e);
}
helper = new GregorianCalendarHelper(this, koreanEraInfo);
}
internal override int ID {
get {
return (CAL_KOREA);
}
}
public override DateTime AddMonths(DateTime time, int months) {
return (helper.AddMonths(time, months));
}
public override DateTime AddYears(DateTime time, int years) {
return (helper.AddYears(time, years));
}
/*=================================GetDaysInMonth==========================
**Action: Returns the number of days in the month given by the year and month arguments.
**Returns: The number of days in the given month.
**Arguments:
** year The year in Korean calendar.
** month The month
** era The Japanese era value.
**Exceptions
** ArgumentException If month is less than 1 or greater * than 12.
============================================================================*/
public override int GetDaysInMonth(int year, int month, int era) {
return (helper.GetDaysInMonth(year, month, era));
}
public override int GetDaysInYear(int year, int era) {
return (helper.GetDaysInYear(year, era));
}
public override int GetDayOfMonth(DateTime time) {
return (helper.GetDayOfMonth(time));
}
public override DayOfWeek GetDayOfWeek(DateTime time) {
return (helper.GetDayOfWeek(time));
}
public override int GetDayOfYear(DateTime time)
{
return (helper.GetDayOfYear(time));
}
public override int GetMonthsInYear(int year, int era) {
return (helper.GetMonthsInYear(year, era));
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
}
public override int GetEra(DateTime time) {
return (helper.GetEra(time));
}
public override int GetMonth(DateTime time) {
return (helper.GetMonth(time));
}
public override int GetYear(DateTime time) {
return (helper.GetYear(time));
}
public override bool IsLeapDay(int year, int month, int day, int era)
{
return (helper.IsLeapDay(year, month, day, era));
}
public override bool IsLeapYear(int year, int era) {
return (helper.IsLeapYear(year, era));
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
return (helper.GetLeapMonth(year, era));
}
public override bool IsLeapMonth(int year, int month, int era) {
return (helper.IsLeapMonth(year, month, era));
}
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
}
public override int[] Eras {
get {
return (helper.Eras);
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 4362;
public override int TwoDigitYearMax {
get {
if (twoDigitYearMax == -1) {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set {
VerifyWritable();
if (value < 99 || value > helper.MaxYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
99,
helper.MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year) {
if (year < 0) {
throw new ArgumentOutOfRangeException("year",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
return (helper.ToFourDigitYear(year, this.TwoDigitYearMax));
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 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 Http.Shared.Contexts;
using Http.Shared.Routing;
using HttpMvc.Controllers;
using Node.Cs.Authorization;
using NodeCs.Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Http.Shared.Authorization
{
public static class SecurityUtils
{
public const string AUTH_COOKIE_ID = "NODECS:AC";
public static void FormSetAuthCookie(IHttpContext ctx, string userName, bool persistent)
{
ctx.Response.AppendCookie(new HttpCookie(AUTH_COOKIE_ID, userName)
{
Expires = DateTime.Now.AddMinutes(30)
});
}
/*
public static RedirectResponse BasicSignOut(IHttpContext ctx)
{
var dataPath = NodeCsSettings.Settings.Listener.RootDir ?? string.Empty;
var routeHandler = ServiceLocator.Locator.Resolve<IRoutingHandler>();
var urlHelper = new UrlHelper(ctx,routeHandler);
var realUrl = urlHelper.MergeUrl(dataPath);
return new RedirectResponse(realUrl);
}*/
public static void FormSignOut(IHttpContext ctx)
{
ctx.Response.SetCookie(new HttpCookie(AUTH_COOKIE_ID, "")
{
Expires = DateTime.Now.AddDays(-1)
});
}
}
public class AuthorizeAttribute : Attribute, IFilter
{
protected bool OnPreExecuteBasicAuthentication(IHttpContext context, bool throwOnError = true)
{
var encodedAuthentication = context.Request.Headers["Authorization"];
if (string.IsNullOrWhiteSpace(encodedAuthentication))
{
return RequireBasicAuthentication(context);
}
var splittedEncoding = encodedAuthentication.Split(' ');
if (splittedEncoding.Length != 2)
{
if (throwOnError)
throw new HttpException(401, "Invalid Basic Authentication header");
return false;
}
var basicData = Encoding.ASCII.GetString(
Convert.FromBase64String(splittedEncoding[1].Trim()));
var splitted = basicData.Split(':');
if (splitted.Length != 2)
{
if (throwOnError)
throw new HttpException(401, "Invalid Basic Authentication header");
return false;
}
var authenticationDataProvider = ServiceLocator.Locator.Resolve<IAuthenticationDataProvider>();
if (!authenticationDataProvider.IsUserAuthorized(splitted[0], splitted[1]))
{
if (throwOnError)
return RequireBasicAuthentication(context);
return false;
}
var userRoles = authenticationDataProvider.GetUserRoles(splitted[0]);
if (userRoles == null) userRoles = new string[] { };
context.User = new NodeCsPrincipal(new NodeCsIdentity(splitted[0], "basic", true), userRoles);
return true;
}
private bool RequireBasicAuthentication(IHttpContext context)
{
var response = context.Response as IForcedHeadersResponse;
if (response == null) return false;
context.Response.StatusCode = 401;
var realmDescription = string.Format("Basic realm=\"{0}\"", _realm);
response.ForceHeader("WWW-Authenticate", realmDescription);
return true;
}
private HttpCookie FormGetAuthCookie(IHttpContext ctx)
{
return ctx.Request.Cookies.Get(SecurityUtils.AUTH_COOKIE_ID);
}
internal readonly string _realm;
internal SecurityDefinition _settings;
private string _roles;
private string[] _rolesExploded;
public AuthorizeAttribute()
{
_rolesExploded = new string[] { };
_settings = ServiceLocator.Locator.Resolve<SecurityDefinition>();
_realm = _settings.Realm;
}
/// <summary>
/// The roles allowed, comma separated
/// </summary>
public string Roles
{
get { return _roles; }
set
{
_roles = value;
_rolesExploded = _roles == null ? new string[] { } : _roles.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}
}
protected bool OnPreExecuteFormAuthentication(IHttpContext context, bool throwOnError = true)
{
var cookie = FormGetAuthCookie(context);
if (cookie == null)
{
if (throwOnError)
return RequireFormAuthentication(context);
return false;
}
var authenticationDataProvider = ServiceLocator.Locator.Resolve<IAuthenticationDataProvider>();
var userName = cookie.Value;
if (userName == null || !authenticationDataProvider.IsUserPresent(userName))
{
if (throwOnError)
return RequireFormAuthentication(context);
return false;
}
var userRoles = authenticationDataProvider.GetUserRoles(userName);
if (userRoles == null) userRoles = new string[] { };
context.User = new NodeCsPrincipal(new NodeCsIdentity(userName, "basic", true), userRoles);
return true;
}
public bool OnPreExecute(IHttpContext context)
{
if (string.Compare(_settings.AuthenticationType, "none", StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
if (context.User == null)
{
if (string.Compare(_settings.AuthenticationType, "basic", StringComparison.OrdinalIgnoreCase) == 0)
{
return OnPreExecuteBasicAuthentication(context);
}
if (string.Compare(_settings.AuthenticationType, "form", StringComparison.OrdinalIgnoreCase) == 0)
{
return OnPreExecuteFormAuthentication(context);
}
return true;
}
for (int i = 0; i < _rolesExploded.Length; i++)
{
if (!context.User.IsInRole(_rolesExploded[i]))
{
if (string.Compare(_settings.AuthenticationType, "basic", StringComparison.OrdinalIgnoreCase) == 0)
{
return OnPreExecuteBasicAuthentication(context);
}
if (string.Compare(_settings.AuthenticationType, "form", StringComparison.OrdinalIgnoreCase) == 0)
{
return OnPreExecuteFormAuthentication(context);
}
}
}
return true;
}
private bool RequireFormAuthentication(IHttpContext context)
{
context.Response.Redirect(_settings.LoginPage);
return true;
}
public void OnPostExecute(IHttpContext context)
{
}
}
}
| |
using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Web.Models;
using Umbraco.Web.Mvc;
namespace Umbraco.Web
{
/// <summary>
/// Extension methods for UrlHelper for use in templates
/// </summary>
public static class UrlHelperRenderExtensions
{
#region GetCropUrl
/// <summary>
/// Gets the ImageProcessor Url of a media item by the crop alias (using default media item property alias of "umbracoFile")
/// </summary>
/// <param name="urlHelper"></param>
/// <param name="mediaItem">
/// The IPublishedContent item.
/// </param>
/// <param name="cropAlias">
/// The crop alias e.g. thumbnail
/// </param>
/// <param name="htmlEncode">
/// Whether to HTML encode this URL - default is true - w3c standards require html attributes to be html encoded but this can be
/// set to false if using the result of this method for CSS.
/// </param>
/// <returns></returns>
public static IHtmlString GetCropUrl(this UrlHelper urlHelper, IPublishedContent mediaItem, string cropAlias, bool htmlEncode = true)
{
var url = mediaItem.GetCropUrl(cropAlias: cropAlias, useCropDimensions: true);
return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url);
}
/// <summary>
/// Gets the ImageProcessor Url by the crop alias using the specified property containing the image cropper Json data on the IPublishedContent item.
/// </summary>
/// <param name="urlHelper"></param>
/// <param name="mediaItem">
/// The IPublishedContent item.
/// </param>
/// <param name="propertyAlias">
/// The property alias of the property containing the Json data e.g. umbracoFile
/// </param>
/// <param name="cropAlias">
/// The crop alias e.g. thumbnail
/// </param>
/// <param name="htmlEncode">
/// Whether to HTML encode this URL - default is true - w3c standards require html attributes to be html encoded but this can be
/// set to false if using the result of this method for CSS.
/// </param>
/// <returns>
/// The ImageProcessor.Web Url.
/// </returns>
public static IHtmlString GetCropUrl(this UrlHelper urlHelper, IPublishedContent mediaItem, string propertyAlias, string cropAlias, bool htmlEncode = true)
{
var url = mediaItem.GetCropUrl(propertyAlias: propertyAlias, cropAlias: cropAlias, useCropDimensions: true);
return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url);
}
/// <summary>
/// Gets the ImageProcessor Url from the image path.
/// </summary>
/// <param name="mediaItem">
/// The IPublishedContent item.
/// </param>
/// <param name="width">
/// The width of the output image.
/// </param>
/// <param name="height">
/// The height of the output image.
/// </param>
/// <param name="propertyAlias">
/// Property alias of the property containing the Json data.
/// </param>
/// <param name="cropAlias">
/// The crop alias.
/// </param>
/// <param name="quality">
/// Quality percentage of the output image.
/// </param>
/// <param name="imageCropMode">
/// The image crop mode.
/// </param>
/// <param name="imageCropAnchor">
/// The image crop anchor.
/// </param>
/// <param name="preferFocalPoint">
/// Use focal point to generate an output image using the focal point instead of the predefined crop if there is one
/// </param>
/// <param name="useCropDimensions">
/// Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters
/// </param>
/// <param name="cacheBuster">
/// Add a serialised date of the last edit of the item to ensure client cache refresh when updated
/// </param>
/// <param name="furtherOptions">
/// The further options.
/// </param>
/// <param name="ratioMode">
/// Use a dimension as a ratio
/// </param>
/// <param name="upScale">
/// If the image should be upscaled to requested dimensions
/// </param>
/// <param name="urlHelper"></param>
/// <param name="htmlEncode">
/// Whether to HTML encode this URL - default is true - w3c standards require html attributes to be html encoded but this can be
/// set to false if using the result of this method for CSS.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static IHtmlString GetCropUrl(this UrlHelper urlHelper,
IPublishedContent mediaItem,
int? width = null,
int? height = null,
string propertyAlias = Umbraco.Core.Constants.Conventions.Media.File,
string cropAlias = null,
int? quality = null,
ImageCropMode? imageCropMode = null,
ImageCropAnchor? imageCropAnchor = null,
bool preferFocalPoint = false,
bool useCropDimensions = false,
bool cacheBuster = true,
string furtherOptions = null,
ImageCropRatioMode? ratioMode = null,
bool upScale = true,
bool htmlEncode = true)
{
var url = mediaItem.GetCropUrl(width, height, propertyAlias, cropAlias, quality, imageCropMode,
imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBuster, furtherOptions, ratioMode,
upScale);
return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url);
}
/// <summary>
/// Gets the ImageProcessor Url from the image path.
/// </summary>
/// <param name="imageUrl">
/// The image url.
/// </param>
/// <param name="width">
/// The width of the output image.
/// </param>
/// <param name="height">
/// The height of the output image.
/// </param>
/// <param name="imageCropperValue">
/// The Json data from the Umbraco Core Image Cropper property editor
/// </param>
/// <param name="cropAlias">
/// The crop alias.
/// </param>
/// <param name="quality">
/// Quality percentage of the output image.
/// </param>
/// <param name="imageCropMode">
/// The image crop mode.
/// </param>
/// <param name="imageCropAnchor">
/// The image crop anchor.
/// </param>
/// <param name="preferFocalPoint">
/// Use focal point to generate an output image using the focal point instead of the predefined crop if there is one
/// </param>
/// <param name="useCropDimensions">
/// Use crop dimensions to have the output image sized according to the predefined crop sizes, this will override the width and height parameters
/// </param>
/// <param name="cacheBusterValue">
/// Add a serialised date of the last edit of the item to ensure client cache refresh when updated
/// </param>
/// <param name="furtherOptions">
/// The further options.
/// </param>
/// <param name="ratioMode">
/// Use a dimension as a ratio
/// </param>
/// <param name="upScale">
/// If the image should be upscaled to requested dimensions
/// </param>
/// <param name="urlHelper"></param>
/// <param name="htmlEncode">
/// Whether to HTML encode this URL - default is true - w3c standards require html attributes to be html encoded but this can be
/// set to false if using the result of this method for CSS.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static IHtmlString GetCropUrl(this UrlHelper urlHelper,
string imageUrl,
int? width = null,
int? height = null,
string imageCropperValue = null,
string cropAlias = null,
int? quality = null,
ImageCropMode? imageCropMode = null,
ImageCropAnchor? imageCropAnchor = null,
bool preferFocalPoint = false,
bool useCropDimensions = false,
string cacheBusterValue = null,
string furtherOptions = null,
ImageCropRatioMode? ratioMode = null,
bool upScale = true,
bool htmlEncode = true)
{
var url = imageUrl.GetCropUrl(width, height, imageCropperValue, cropAlias, quality, imageCropMode,
imageCropAnchor, preferFocalPoint, useCropDimensions, cacheBusterValue, furtherOptions, ratioMode,
upScale);
return htmlEncode ? new HtmlString(HttpUtility.HtmlEncode(url)) : new HtmlString(url);
}
#endregion
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <param name="url"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <returns></returns>
public static string SurfaceAction(this UrlHelper url, string action, string controllerName)
{
return url.SurfaceAction(action, controllerName, null);
}
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <param name="url"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
public static string SurfaceAction(this UrlHelper url, string action, string controllerName, object additionalRouteVals)
{
return url.SurfaceAction(action, controllerName, "", additionalRouteVals);
}
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <param name="url"></param>
/// <param name="action"></param>
/// <param name="controllerName"></param>
/// <param name="area"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
public static string SurfaceAction(this UrlHelper url, string action, string controllerName, string area, object additionalRouteVals)
{
Mandate.ParameterNotNullOrEmpty(action, "action");
Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName");
var encryptedRoute = UmbracoHelper.CreateEncryptedRouteString(controllerName, action, area, additionalRouteVals);
var result = UmbracoContext.Current.OriginalRequestUrl.AbsolutePath.EnsureEndsWith('?') + "ufprt=" + encryptedRoute;
return result;
}
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <param name="url"></param>
/// <param name="action"></param>
/// <param name="surfaceType"></param>
/// <returns></returns>
public static string SurfaceAction(this UrlHelper url, string action, Type surfaceType)
{
return url.SurfaceAction(action, surfaceType, null);
}
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <param name="url"></param>
/// <param name="action"></param>
/// <param name="surfaceType"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
public static string SurfaceAction(this UrlHelper url, string action, Type surfaceType, object additionalRouteVals)
{
Mandate.ParameterNotNullOrEmpty(action, "action");
Mandate.ParameterNotNull(surfaceType, "surfaceType");
var area = "";
var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers
.SingleOrDefault(x => x == surfaceType);
if (surfaceController == null)
throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName);
var metaData = PluginController.GetMetadata(surfaceController);
if (metaData.AreaName.IsNullOrWhiteSpace() == false)
{
//set the area to the plugin area
area = metaData.AreaName;
}
var encryptedRoute = UmbracoHelper.CreateEncryptedRouteString(metaData.ControllerName, action, area, additionalRouteVals);
var result = UmbracoContext.Current.OriginalRequestUrl.AbsolutePath.EnsureEndsWith('?') + "ufprt=" + encryptedRoute;
return result;
}
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="action"></param>
/// <returns></returns>
public static string SurfaceAction<T>(this UrlHelper url, string action)
where T : SurfaceController
{
return url.SurfaceAction(action, typeof (T));
}
/// <summary>
/// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url"></param>
/// <param name="action"></param>
/// <param name="additionalRouteVals"></param>
/// <returns></returns>
public static string SurfaceAction<T>(this UrlHelper url, string action, object additionalRouteVals)
where T : SurfaceController
{
return url.SurfaceAction(action, typeof (T), additionalRouteVals);
}
}
}
| |
// Copyright 2020 The Tilt Brush 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 UnityEngine;
using System;
namespace TiltBrush {
[Serializable]
public enum LightMode {
Ambient = -1,
Shadow,
NoShadow,
NumLights // This should *not* include Ambient light in the count.
}
public class LightsPanel : BasePanel {
[SerializeField] private LightButton[] m_LightButtons;
[SerializeField] private LightGizmo m_MainLightGizmoPrefab;
[SerializeField] private LightGizmo m_SecondaryLightGizmoPrefab;
[SerializeField] private float m_LightSize = 0.6f;
[SerializeField] private Material m_PreviewSphereMaterial;
[SerializeField] private Material m_LightButtonHDRMaterial;
[SerializeField] private Transform m_PreviewSphereParent;
[SerializeField] private float m_ColorPickerPopUpHeightOffset = 0.4f;
[SerializeField] private Transform m_ShadowLightFake;
[SerializeField] private Renderer m_ShadowLightColorIndicator;
[SerializeField] private Transform m_NoShadowLightFake;
[SerializeField] private Renderer m_NoShadowLightColorIndicator;
[SerializeField] private Transform m_PreviewSphere;
[SerializeField] private Transform m_PreviewSphereBase;
// Avoid writing to the actual material, use an instance instead.
// This also avoids exposing the instance to the editor.
private Material m_PreviewSphereMaterialInstance;
private LightGizmo m_LightGizmo_Shadow;
private LightGizmo m_LightGizmo_NoShadow;
private LightGizmo m_GizmoPointedAt;
public Vector3 PreviewCenter {
get {
return m_PreviewSphere.transform.position;
}
}
public Vector3 LightWidgetPosition(Quaternion lightRot) {
var pos = PreviewCenter + lightRot * Vector3.back * m_LightSize *
(1 + m_GazeActivePercent * (m_GazeHighlightScaleMultiplier - 1.0f));
return pos;
}
public bool IsLightGizmoBeingDragged {
get { return m_LightGizmo_Shadow.IsBeingDragged || m_LightGizmo_NoShadow.IsBeingDragged; }
}
public bool IsLightGizmoBeingHovered {
get { return m_LightGizmo_Shadow.IsBeingHovered || m_LightGizmo_NoShadow.IsBeingHovered; }
}
public Vector3 ActiveLightGizmoPosition {
get {
Debug.Assert(IsLightGizmoBeingDragged || IsLightGizmoBeingHovered);
return m_LightGizmo_Shadow.IsBeingHovered || m_LightGizmo_Shadow.IsBeingDragged ?
m_LightGizmo_Shadow.transform.position : m_LightGizmo_NoShadow.transform.position;
}
}
public override void OnPanelMoved() {
m_LightGizmo_Shadow.UpdateTransform();
m_LightGizmo_NoShadow.UpdateTransform();
if (m_GazeActivePercent == 0) {
m_ShadowLightFake.transform.position = m_LightGizmo_Shadow.transform.position;
m_NoShadowLightFake.transform.position = m_LightGizmo_NoShadow.transform.position;
float zOffset = m_PreviewSphere.transform.localPosition.z;
m_ShadowLightFake.transform.localPosition = new Vector3(
m_ShadowLightFake.transform.localPosition.x,
m_ShadowLightFake.transform.localPosition.y,
zOffset + (IsPositionCloserThanPreview(m_ShadowLightFake.transform.position) ? -.1f : .1f));
m_NoShadowLightFake.transform.localPosition = new Vector3(
m_NoShadowLightFake.transform.localPosition.x,
m_NoShadowLightFake.transform.localPosition.y,
zOffset + (IsPositionCloserThanPreview(m_NoShadowLightFake.transform.position) ? -.05f : .05f));
}
}
bool IsPositionCloserThanPreview(Vector3 pos) {
return (pos - ViewpointScript.Head.position).magnitude <
(PreviewCenter - ViewpointScript.Head.position).magnitude;
}
void ActivateButtons(bool show) {
for (int i = 0; i < m_LightButtons.Length; i++) {
m_LightButtons[i].gameObject.SetActive(show);
}
}
override public void OnWidgetShowAnimComplete() {
OnPanelMoved();
for (int i = -1; i < (int)LightMode.NumLights; i++) {
m_LightButtons[i+1].SetDescriptionText(LightModeToString((LightMode)i),
ColorTable.m_Instance.NearestColorTo(GetLightColor((LightMode)i)));
}
m_ShadowLightFake.gameObject.SetActive(true);
m_NoShadowLightFake.gameObject.SetActive(true);
}
public override void OnWidgetShowAnimStart() {
m_LightGizmo_Shadow.Visible = false;
m_LightGizmo_NoShadow.Visible = false;
}
override protected void Awake() {
base.Awake();
// Avoid writing directly to the material, since that will save changes to disk when in editor.
if (m_PreviewSphereMaterial) {
m_PreviewSphereMaterialInstance = Instantiate(m_PreviewSphereMaterial);
}
m_PreviewSphere.GetComponent<MeshRenderer>().material = m_PreviewSphereMaterialInstance;
m_PreviewSphereBase.GetComponent<MeshRenderer>().material = m_PreviewSphereMaterialInstance;
m_ShadowLightColorIndicator.material.SetFloat("_FlattenAmount", 1);
m_NoShadowLightColorIndicator.material.SetFloat("_FlattenAmount", 1);
}
void Start() {
OnPanelMoved();
}
override protected void OnEnablePanel() {
base.OnEnablePanel();
if (m_LightGizmo_Shadow) {
m_LightGizmo_Shadow.gameObject.SetActive(true);
} else {
m_LightGizmo_Shadow = Instantiate(m_MainLightGizmoPrefab);
m_LightGizmo_Shadow.SetParentPanel(this);
}
m_LightGizmo_Shadow.UpdateTint();
if (m_LightGizmo_NoShadow) {
m_LightGizmo_NoShadow.gameObject.SetActive(true);
} else {
m_LightGizmo_NoShadow = Instantiate(m_SecondaryLightGizmoPrefab);
m_LightGizmo_NoShadow.SetParentPanel(this);
}
m_LightGizmo_NoShadow.UpdateTint();
m_ShadowLightFake.gameObject.SetActive(true);
m_NoShadowLightFake.gameObject.SetActive(true);
ActivateButtons(true);
}
override protected void OnDisablePanel() {
base.OnDisablePanel();
if (m_LightGizmo_Shadow) {
m_LightGizmo_Shadow.gameObject.SetActive(false);
}
if (m_LightGizmo_NoShadow) {
m_LightGizmo_NoShadow.gameObject.SetActive(false);
}
ActivateButtons(false);
m_ShadowLightFake.gameObject.SetActive(false);
m_NoShadowLightFake.gameObject.SetActive(false);
}
public Color GetLightColor(LightMode mode) {
switch (mode) {
case LightMode.Ambient:
return RenderSettings.ambientLight;
case LightMode.Shadow:
return m_LightGizmo_Shadow.GetColor();
case LightMode.NoShadow:
return m_LightGizmo_NoShadow.GetColor();
}
return Color.black;
}
public void SetDiscoLights(Color ambient, Color shadow, Color noShadow, bool noRecord) {
SetLightColor(LightMode.Ambient, ambient, noRecord);
SetLightColor(LightMode.Shadow, shadow, noRecord);
SetLightColor(LightMode.NoShadow, noShadow, noRecord);
RefreshLightButtons();
}
void SetLightColor(LightMode mode, Color color, bool noRecord = false) {
ModifyLightCommand command = null;
switch (mode) {
case LightMode.Ambient:
command = new ModifyLightCommand(mode, color, Quaternion.identity);
break;
case LightMode.Shadow:
case LightMode.NoShadow:
command = new ModifyLightCommand(mode, color,
App.Scene.GetLight((int)mode).transform.localRotation);
break;
}
command.Redo();
if (!noRecord) {
SketchMemoryScript.m_Instance.RecordCommand(command);
}
}
public LightGizmo GetLight(LightMode light) {
switch (light) {
case LightMode.Shadow:
return m_LightGizmo_Shadow;
case LightMode.NoShadow:
return m_LightGizmo_NoShadow;
}
return null;
}
Action<Color> OnColorPicked(LightMode mode) {
return delegate(Color c) {
SetLightColor(mode, c);
if (mode == LightMode.Shadow || mode == LightMode.NoShadow) {
SceneSettings.m_Instance.UpdateReflectionIntensity();
}
};
}
void Update() {
UpdateState();
CalculateBounds();
if (m_Fixed || SketchControlsScript.m_Instance.IsUserGrabbingWorld()) {
OnPanelMoved();
}
if (m_PanelDescriptionState != DescriptionState.Closed) {
m_PanelDescriptionTextSpring.Update(m_DescriptionSpringK, m_DescriptionSpringDampen);
//orient text and swatches
Quaternion qAngleOrient = Quaternion.Euler(0.0f, m_PanelDescriptionTextSpring.m_CurrentAngle, 0.0f);
Quaternion qOrient = m_Mesh.transform.rotation * qAngleOrient;
m_PanelDescriptionObject.transform.rotation = qOrient;
//position text and swatches
Vector3 vPanelDescriptionOffset = m_Bounds;
vPanelDescriptionOffset.x *= m_PanelDescriptionOffset.x;
vPanelDescriptionOffset.y *= m_PanelDescriptionOffset.y;
Vector3 vTransformedDescOffset = m_Mesh.transform.rotation * vPanelDescriptionOffset;
m_PanelDescriptionObject.transform.position = m_Mesh.transform.position + vTransformedDescOffset;
//alpha text and swatches
float fDistToClosed = Mathf.Abs(m_PanelDescriptionTextSpring.m_CurrentAngle - m_DescriptionClosedAngle);
Color rItemColor = m_PanelDescriptionColor;
float fRatio = fDistToClosed / m_DescriptionAlphaDistance;
float fAlpha = Mathf.Min(fRatio * fRatio, 1.0f);
rItemColor.a = fAlpha;
if (m_PanelDescriptionTextMeshPro) {
m_PanelDescriptionTextMeshPro.color = rItemColor;
}
if (m_PanelDescriptionState == DescriptionState.Closing) {
float fToDesired = m_PanelDescriptionTextSpring.m_DesiredAngle - m_PanelDescriptionTextSpring.m_CurrentAngle;
if (Mathf.Abs(fToDesired) <= m_CloseAngleThreshold) {
m_PanelDescriptionRenderer.enabled = false;
m_PreviewSphereMaterialInstance.SetFloat("_FlattenAmount", 1.0f);
m_PanelDescriptionState = DescriptionState.Closed;
}
}
}
UpdateGazeBehavior();
UpdateFixedTransition();
}
override public bool RaycastAgainstMeshCollider(Ray rRay, out RaycastHit rHitInfo, float fDist) {
rHitInfo = new RaycastHit();
// If we're dragging a gizmo, we're always colliding with this panel.
if (m_LightGizmo_Shadow.IsBeingDragged) {
rHitInfo.point = m_LightGizmo_Shadow.transform.position;
rHitInfo.normal = (rHitInfo.point - rRay.origin).normalized;
return true;
} else if (m_LightGizmo_NoShadow.IsBeingDragged) {
rHitInfo.point = m_LightGizmo_NoShadow.transform.position;
rHitInfo.normal = (rHitInfo.point - rRay.origin).normalized;
return true;
}
// Precise checks against gizmos.
if (!m_ActivePopUp && m_GazeActive) {
if (m_LightGizmo_Shadow.Collider.Raycast(rRay, out rHitInfo, fDist)) {
rHitInfo.point = m_LightGizmo_Shadow.transform.position;
rHitInfo.normal = (rHitInfo.point - rRay.origin).normalized;
m_GizmoPointedAt = m_LightGizmo_Shadow;
return true;
} else if (m_LightGizmo_NoShadow.Collider.Raycast(rRay, out rHitInfo, fDist)) {
rHitInfo.point = m_LightGizmo_NoShadow.transform.position;
rHitInfo.normal = (rHitInfo.point - rRay.origin).normalized;
m_GizmoPointedAt = m_LightGizmo_NoShadow;
return true;
} else {
m_GizmoPointedAt = null;
}
// Gross checks against broad colliders for gizmos. These checks ensure the user doesn't
// lose focus on the panel when targeting a light gizmo that's angled in a way where pointing
// at it would not satisfy the standard checks below.
if (m_LightGizmo_Shadow.BroadCollider.Raycast(rRay, out rHitInfo, fDist) ||
m_LightGizmo_NoShadow.BroadCollider.Raycast(rRay, out rHitInfo, fDist)) {
// Spoof a collision along the plane of the mesh collider
Plane meshPlane = new Plane(m_MeshCollider.transform.forward,
m_MeshCollider.transform.position);
float rayDist;
meshPlane.Raycast(rRay, out rayDist);
rHitInfo.point = rRay.GetPoint(rayDist);
rHitInfo.normal = m_MeshCollider.transform.forward;
return true;
}
}
// Fall back on standard panel collider.
return base.RaycastAgainstMeshCollider(rRay, out rHitInfo, fDist);
}
override public void OnUpdatePanel(Vector3 vToPanel, Vector3 vHitPoint) {
base.OnUpdatePanel(vToPanel, vHitPoint);
m_LightGizmo_Shadow.UpdateDragState(
m_GizmoPointedAt == m_LightGizmo_Shadow, m_InputValid);
m_LightGizmo_NoShadow.UpdateDragState(
m_GizmoPointedAt == m_LightGizmo_NoShadow, m_InputValid);
TutorialManager.m_Instance.UpdateLightGizmoHint();
}
override public void PanelGazeActive(bool bActive) {
base.PanelGazeActive(bActive);
m_LightGizmo_Shadow.UpdateDragState(false, false);
m_LightGizmo_NoShadow.UpdateDragState(false, false);
for (int i = 0; i < m_LightButtons.Length; ++i) {
m_LightButtons[i].ResetState();
}
m_GizmoPointedAt = null;
if (!bActive) {
TutorialManager.m_Instance.ClearLightGizmoHint();
}
}
public void Refresh() {
var shadowColor = m_LightGizmo_Shadow.SetLight(0);
var noShadowColor = m_LightGizmo_NoShadow.SetLight(1);
m_ShadowLightColorIndicator.material.SetColor("_TrueColor", shadowColor);
m_ShadowLightColorIndicator.material.SetColor("_ClampedColor",
ColorPickerUtils.ClampColorIntensityToLdr(shadowColor));
m_NoShadowLightColorIndicator.material.SetColor("_TrueColor", noShadowColor);
m_NoShadowLightColorIndicator.material.SetColor("_ClampedColor",
ColorPickerUtils.ClampColorIntensityToLdr(noShadowColor));
// TODO : Patch this up.
//if (m_PanelPopUpScript) {
// ColorPickerPopUpWindow picker = m_PanelPopUpScript as ColorPickerPopUpWindow;
// if (picker) {
// picker.RefreshCurrentColor();
// }
//}
RefreshLightButtons();
OnPanelMoved();
}
void RefreshLightButtons() {
Color panelColor = GetGazeColor();
m_LightButtons[0].SetColor(panelColor);
m_LightButtons[1].SetColor(panelColor);
m_LightButtons[2].SetColor(panelColor);
for (int i = -1; i < (int)LightMode.NumLights; i++) {
m_LightButtons[i + 1].SetDescriptionText(LightModeToString((LightMode)i),
ColorTable.m_Instance.NearestColorTo(GetLightColor((LightMode)i)));
}
m_LightButtonHDRMaterial.SetColor(
"_ClampedColor", ColorPickerUtils.ClampColorIntensityToLdr(m_LightGizmo_Shadow.GetColor()));
}
override protected void OnUpdateActive() {
if (m_GazeActive && m_CurrentState == PanelState.Available) {
m_PanelDescriptionState = DescriptionState.Open;
m_PanelDescriptionTextSpring.m_DesiredAngle = m_DescriptionOpenAngle;
m_PanelDescriptionRenderer.enabled = true;
} else {
m_PanelDescriptionState = DescriptionState.Closing;
m_PanelDescriptionTextSpring.m_DesiredAngle = m_DescriptionClosedAngle;
ResetPanelFlair();
}
}
string LightModeToString(LightMode mode) {
switch (mode) {
case LightMode.Ambient:
return "Fill Light";
case LightMode.Shadow:
return "Main Light";
case LightMode.NoShadow:
return "Secondary Light";
}
return "";
}
public void ButtonPressed(LightMode mode) {
m_LightGizmo_Shadow.Visible = false;
m_LightGizmo_NoShadow.Visible = false;
m_PreviewSphereParent.gameObject.SetActive(false);
// Create the popup with callback.
SketchControlsScript.GlobalCommands command =
(mode == LightMode.Shadow || mode == LightMode.NoShadow) ?
SketchControlsScript.GlobalCommands.LightingHdr :
SketchControlsScript.GlobalCommands.LightingLdr;
CreatePopUp(command, -1, -1, LightModeToString(mode), MakeOnPopUpClose(mode));
// Init popup according to current light mode.
var popup = (m_ActivePopUp as ColorPickerPopUpWindow);
popup.transform.localPosition += new Vector3(0, m_ColorPickerPopUpHeightOffset, 0);
ColorPickerUtils.SetLogVRangeForMode(mode);
popup.ColorPicker.ColorPicked += OnColorPicked(mode);
popup.ColorPicker.ColorPicked += delegate(Color c) {
m_LightButtons[(int)mode + 1].SetDescriptionText(LightModeToString(mode),
ColorTable.m_Instance.NearestColorTo(c));
SetLightColor(mode, c);
};
// Init must be called after all popup.ColorPicked actions have been assigned.
popup.ColorPicker.Controller.CurrentColor = GetLightColor(mode);
popup.ColorPicker.ColorFinalized += MakeLightColorFinalized(mode);
popup.CustomColorPalette.ColorPicked += MakeLightColorPickedAsFinal(mode);
m_EatInput = true;
}
Action MakeOnPopUpClose(LightMode mode) {
return delegate {
m_LightGizmo_Shadow.Visible = true;
m_LightGizmo_NoShadow.Visible = true;
m_PreviewSphereParent.gameObject.SetActive(true);
Color lightColor = GetLightColor(mode);
m_LightButtons[(int)mode + 1].SetDescriptionText(
LightModeToString(mode),
ColorTable.m_Instance.NearestColorTo(lightColor));
};
}
Action MakeLightColorFinalized(LightMode mode) {
return delegate {
SketchMemoryScript.m_Instance.PerformAndRecordCommand(mode == LightMode.Ambient ?
new ModifyLightCommand(mode, RenderSettings.ambientLight, Quaternion.identity, final: true) :
new ModifyLightCommand(mode, App.Scene.GetLight((int)mode).color,
App.Scene.GetLight((int)mode).transform.localRotation, final: true));
};
}
Action<Color> MakeLightColorPickedAsFinal(LightMode mode) {
return delegate(Color c) {
SetLightColor(mode, c);
SketchMemoryScript.m_Instance.PerformAndRecordCommand(mode == LightMode.Ambient ?
new ModifyLightCommand(mode, RenderSettings.ambientLight, Quaternion.identity, final: true) :
new ModifyLightCommand(mode, App.Scene.GetLight((int)mode).color,
App.Scene.GetLight((int)mode).transform.localRotation, final: true));
};
}
protected override void UpdateGazeBehavior() {
float fPrevPercent = m_GazeActivePercent;
base.UpdateGazeBehavior();
// When inactive, light gizmos' white outline will tint grey.
m_NoShadowLightColorIndicator.material.SetColor("_Color", Color.gray);
m_ShadowLightColorIndicator.material.SetColor("_Color", Color.gray);
if (m_UseGazeRotation && m_Mesh) {
if (fPrevPercent > 0.0f && fPrevPercent < 1.0f) {
m_LightGizmo_Shadow.Visible = m_GazeActivePercent > 0;
m_LightGizmo_NoShadow.Visible = m_GazeActivePercent > 0;
float fScaleMult = m_GazeActivePercent * (m_GazeHighlightScaleMultiplier - 1.0f);
Vector3 newScale = m_BaseScale * m_AdjustedScale * (1.0f + fScaleMult);
m_LightGizmo_Shadow.transform.localScale = newScale * m_LightSize;
m_LightGizmo_NoShadow.transform.localScale = newScale * m_LightSize;
m_ShadowLightFake.gameObject.SetActive(m_GazeActivePercent == 0);
m_NoShadowLightFake.gameObject.SetActive(m_GazeActivePercent == 0);
OnPanelMoved();
m_PreviewSphereMaterialInstance.SetFloat("_FlattenAmount", 1.0f - m_GazeActivePercent);
m_PreviewSphereParent.localPosition = new Vector3(0, 0, -m_GazeActivePercent);
}
}
}
}
} // namespace TiltBrush
| |
// Copyright (C) 2020 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
//
// 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.Reflection;
using System.Collections.Generic;
using GoogleMobileAds.Api;
using GoogleMobileAds.Common;
using UnityEngine;
using UnityEngine.UI;
namespace GoogleMobileAds.Unity
{
public class BannerClient : BaseAdDummyClient, IBannerClient
{
// Ad event fired when the banner ad has been received.
public event EventHandler<EventArgs> OnAdLoaded;
// Ad event fired when the banner ad has failed to load.
public event EventHandler<LoadAdErrorClientEventArgs> OnAdFailedToLoad;
// Ad event fired when the banner ad is opened.
public event EventHandler<EventArgs> OnAdOpening;
// Ad event fired when the banner ad is closed.
public event EventHandler<EventArgs> OnAdClosed;
// Ad event fired when the banner ad is estimated to have earned money.
public event EventHandler<AdValueEventArgs> OnPaidEvent;
private Dictionary<AdSize, string> prefabAds = new Dictionary<AdSize, string>()
{
{AdSize.Banner, "DummyAds/Banners/BANNER"},
{AdSize.SmartBanner, "DummyAds/Banners/SMART_BANNER" },
{AdSize.MediumRectangle, "DummyAds/Banners/MEDIUM_RECTANGLE" },
{AdSize.IABBanner, "DummyAds/Banners/FULL_BANNER" },
{AdSize.Leaderboard, "DummyAds/Banners/LEADERBOARD" },
{new AdSize (320,100), "DummyAds/Banners/LARGE_BANNER" }
};
private ButtonBehaviour buttonBehaviour;
private void AddClickBehavior(GameObject dummyAd)
{
Image myImage = dummyAd.GetComponentInChildren<Image>();
Button button = myImage.GetComponentInChildren<Button>();
button.onClick.AddListener(() => {
buttonBehaviour.OpenURL();
});
}
private void CreateButtonBehavior()
{
buttonBehaviour = new ButtonBehaviour();
buttonBehaviour.OnAdOpening += OnAdOpening;
}
// Creates a banner view and adds it to the view hierarchy.
public void CreateBannerView(string adUnitId, AdSize adSize, AdPosition position)
{
if (adSize.AdType == AdSize.Type.AnchoredAdaptive)
{
LoadAndSetPrefabAd("DummyAds/Banners/ADAPTIVE");
}
else
{
LoadAndSetPrefabAd(prefabAds[adSize]);
}
if (prefabAd != null) {
if (adSize == AdSize.SmartBanner || adSize.AdType == AdSize.Type.AnchoredAdaptive)
{
SetAndStretchAd(prefabAd, position, adSize);
}
else
{
AnchorAd(prefabAd, position);
}
}
}
// Creates a banner view and adds it to the view hierarchy with a custom position.
public void CreateBannerView(string adUnitId, AdSize adSize, int x, int y)
{
if (adSize.AdType == AdSize.Type.AnchoredAdaptive)
{
LoadAndSetPrefabAd("DummyAds/Banners/ADAPTIVE");
}
else
{
LoadAndSetPrefabAd(prefabAds[adSize]);
}
if (prefabAd != null) {
RectTransform rect = getRectTransform(prefabAd);
if (adSize == AdSize.SmartBanner || adSize.AdType == AdSize.Type.AnchoredAdaptive)
{
SetAndStretchAd(prefabAd, 0, adSize);
rect.anchoredPosition = new Vector3(0, y, 1);
}
else
{
rect.anchoredPosition = new Vector3(x, y, 1);
}
}
}
// Requests a new ad for the banner view.
public void LoadAd(AdRequest request)
{
if (prefabAd != null) {
ShowBannerView();
if (OnAdLoaded != null)
{
OnAdLoaded.Invoke(this, EventArgs.Empty);
}
} else {
if (OnAdFailedToLoad != null)
{
OnAdFailedToLoad.Invoke(this, new LoadAdErrorClientEventArgs()
{
LoadAdErrorClient = new LoadAdErrorClient()
});
}
}
}
// Shows the banner view on the screen.
public void ShowBannerView()
{
dummyAd = AdBehaviour.ShowAd(prefabAd, getRectTransform(prefabAd).anchoredPosition);
CreateButtonBehavior();
AddClickBehavior(dummyAd);
}
// Hides the banner view from the screen.
public void HideBannerView()
{
AdBehaviour.DestroyAd(dummyAd);
}
// Destroys a banner view.
public void DestroyBannerView()
{
AdBehaviour.DestroyAd(dummyAd);
prefabAd = null;
}
// Returns the height of the BannerView in pixels.
public float GetHeightInPixels()
{
if (prefabAd != null) {
return getRectTransform(prefabAd).sizeDelta.y;
}
return 0;
}
// Returns the width of the BannerView in pixels.
public float GetWidthInPixels()
{
if (prefabAd != null) {
return getRectTransform(prefabAd).sizeDelta.x;
}
return 0;
}
// Set the position of the banner view using standard position.
public void SetPosition(AdPosition adPosition)
{
if (dummyAd != null)
{
AnchorAd(dummyAd, adPosition);
} else
{
Debug.Log("No existing banner in game");
}
}
// Set the position of the banner view using custom position.
public void SetPosition(int x, int y)
{
if (dummyAd != null)
{
RectTransform rect = getRectTransform(dummyAd);
rect.anchoredPosition = new Vector2(x, y);
} else
{
Debug.Log("No existing banner in game");
}
}
private void SetAndStretchAd(GameObject dummyAd, AdPosition pos, AdSize adSize)
{
if (dummyAd != null) {
Image myImage = dummyAd.GetComponentInChildren<Image>();
RectTransform rect = myImage.GetComponentInChildren<RectTransform>();
rect.pivot = new Vector2(0.5f, 0.5f);
if (pos == AdPosition.Bottom || pos == AdPosition.BottomLeft || pos == AdPosition.BottomRight)
{
rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Bottom, 0, rect.sizeDelta.y);
rect.anchoredPosition = new Vector2(0, (float)rect.sizeDelta.y/2);
} else if (pos == AdPosition.Top || pos == AdPosition.TopLeft || pos == AdPosition.TopRight)
{
rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, rect.sizeDelta.y);
rect.anchoredPosition = new Vector2(0, -(float)rect.sizeDelta.y/2);
} else if (pos == AdPosition.Center)
{
LoadAndSetPrefabAd("DummyAds/Banners/CENTER");
if (adSize.AdType == AdSize.Type.AnchoredAdaptive)
{
LoadAndSetPrefabAd("DummyAds/Banners/CENTER");
Text adText = prefabAd.GetComponentInChildren<Image>().GetComponentInChildren<Text>();
adText.text = "This is a Test Adaptive Banner";
}
else if (adSize == AdSize.SmartBanner)
{
LoadAndSetPrefabAd("DummyAds/Banners/CENTER");
Text adText = prefabAd.GetComponentInChildren<Image>().GetComponentInChildren<Text>();
adText.text = "This is a Test Smart Banner";
}
else
{
rect.anchoredPosition = new Vector2(0, 0);
}
} else
{
rect.anchoredPosition = rect.position;
}
} else {
Debug.Log("Invalid Dummy Ad");
}
}
private void AnchorAd(GameObject dummyAd, AdPosition position)
{
if (dummyAd != null) {
Image myImage = dummyAd.GetComponentInChildren<Image>();
RectTransform rect = myImage.GetComponentInChildren<RectTransform>();
float x = (float)rect.sizeDelta.x/2;
float y = (float)rect.sizeDelta.y/2;
switch (position)
{
case (AdPosition.TopLeft):
rect.pivot = new Vector2(0.5f, 0.5f);
rect.anchorMin = new Vector2(0, 1);
rect.anchorMax = new Vector2(0, 1);
rect.anchoredPosition = new Vector2(x, -y);
break;
case (AdPosition.TopRight):
rect.pivot = new Vector2(0.5f, 0.5f);
rect.anchorMin = new Vector2(1, 1);
rect.anchorMax = new Vector2(1, 1);
rect.anchoredPosition = new Vector2(-x, -y);
break;
case (AdPosition.Top):
rect.pivot = new Vector2(0.5f, 0.5f);
rect.anchorMin = new Vector2(0.5f, 1);
rect.anchorMax = new Vector2(0.5f, 1);
rect.anchoredPosition = new Vector2(0, -y);
break;
case (AdPosition.Bottom):
rect.pivot = new Vector2(0.5f, 0.5f);
rect.anchorMin = new Vector2(0.5f, 0);
rect.anchorMax = new Vector2(0.5f, 0);
rect.anchoredPosition = new Vector2(0, y);
break;
case (AdPosition.BottomRight):
rect.pivot = new Vector2(0.5f, 0.5f);
rect.anchorMin = new Vector2(1, 0);
rect.anchorMax = new Vector2(1, 0);
rect.anchoredPosition = new Vector2(-x, y);
break;
case (AdPosition.BottomLeft):
rect.pivot = new Vector2(0.5f, 0.5f);
rect.anchorMin = new Vector2(0, 0);
rect.anchorMax = new Vector2(0, 0);
rect.anchoredPosition = new Vector2(x, y);
break;
default:
rect.pivot = new Vector2(0.5f, 0.5f);
rect.anchorMin = new Vector2(0.5f, 0.5f);
rect.anchorMax = new Vector2(0.5f, 0.5f);
rect.anchoredPosition = new Vector2(0, 0);
break;
}
} else {
Debug.Log("Invalid Dummy Ad");
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.NetCore.CSharp.Analyzers.Runtime;
using Microsoft.NetCore.VisualBasic.Analyzers.Runtime;
using Microsoft.CodeAnalysis.Diagnostics;
using Test.Utilities;
using Xunit;
namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests
{
public class InitializeStaticFieldsInlineTests : DiagnosticAnalyzerTestBase
{
#region Unit tests for no analyzer diagnostic
[Fact]
public void CA1810_EmptyStaticConstructor()
{
VerifyCSharp(@"
public class Class1
{
private readonly static int field = 1;
static Class1() // Empty
{
}
}
");
VerifyBasic(@"
Public Class Class1
Private Shared ReadOnly field As Integer = 1
Shared Sub New() ' Empty
End Sub
End Class
");
}
[Fact]
public void CA2207_EmptyStaticConstructor()
{
VerifyCSharp(@"
public struct Struct1
{
private readonly static int field = 1;
static Struct1() // Empty
{
}
}
");
VerifyBasic(@"
Public Structure Struct1
Private Shared ReadOnly field As Integer = 1
Shared Sub New() ' Empty
End Sub
End Structure
");
}
[Fact]
public void CA1810_NoStaticFieldInitializedInStaticConstructor()
{
VerifyCSharp(@"
public class Class1
{
private readonly static int field = 1;
static Class1() // No static field initalization
{
Class1_Method();
var field2 = 1;
}
private static void Class1_Method() { throw new System.NotImplementedException(); }
}
");
VerifyBasic(@"
Public Class Class1
Private Shared ReadOnly field As Integer = 1
Shared Sub New() ' No static field initalization
Class1_Method()
Dim field2 = 1
End Sub
Private Shared Sub Class1_Method()
Throw New System.NotImplementedException()
End Sub
End Class
");
}
[Fact]
public void CA1810_StaticPropertyInStaticConstructor()
{
VerifyCSharp(@"
public class Class1
{
private static int Property { get; set; }
static Class1() // Static property initalization
{
Property = 1;
}
}
");
VerifyBasic(@"
Public Class Class1
Private Shared Property [Property]() As Integer
Get
Return 0
End Get
Set
End Set
End Property
Shared Sub New()
' Static property initalization
[Property] = 1
End Sub
End Class
");
}
[Fact]
public void CA1810_InitializionInNonStaticConstructor()
{
VerifyCSharp(@"
public class Class1
{
private static int field = 1;
public Class1() // Non static constructor
{
field = 0;
}
public static void Class1_Method() // Non constructor
{
field = 0;
}
}
");
VerifyBasic(@"
Public Class Class1
Private Shared field As Integer = 1
Public Sub New() ' Non static constructor
field = 0
End Sub
Public Shared Sub Class1_Method() ' Non constructor
field = 0
End Sub
End Class
");
}
#endregion
#region Unit tests for analyzer diagnostic(s)
[Fact]
public void CA1810_InitializationInStaticConstructor()
{
VerifyCSharp(@"
public class Class1
{
private readonly static int field;
static Class1() // Non static constructor
{
field = 0;
}
}
",
GetCA1810CSharpDefaultResultAt(5, 12, "Class1"));
VerifyBasic(@"
Public Class Class1
Private Shared ReadOnly field As Integer
Shared Sub New()
' Non static constructor
field = 0
End Sub
End Class
",
GetCA1810BasicDefaultResultAt(4, 13, "Class1"));
}
[Fact]
public void CA2207_InitializationInStaticConstructor()
{
VerifyCSharp(@"
public struct Struct1
{
private readonly static int field;
static Struct1() // Non static constructor
{
field = 0;
}
}
",
GetCA2207CSharpDefaultResultAt(5, 12, "Struct1"));
VerifyBasic(@"
Public Structure Struct1
Private Shared ReadOnly field As Integer
Shared Sub New()
' Non static constructor
field = 0
End Sub
End Structure
",
GetCA2207BasicDefaultResultAt(4, 13, "Struct1"));
}
[Fact]
public void CA1810_NoDuplicateDiagnostics()
{
VerifyCSharp(@"
public class Class1
{
private readonly static int field, field2;
static Class1() // Non static constructor
{
field = 0;
field2 = 0;
}
}
",
GetCA1810CSharpDefaultResultAt(5, 12, "Class1"));
VerifyBasic(@"
Public Class Class1
Private Shared ReadOnly field As Integer, field2 As Integer
Shared Sub New()
' Non static constructor
field = 0
field2 = 0
End Sub
End Class",
GetCA1810BasicDefaultResultAt(4, 13, "Class1"));
}
[Fact]
public void CA2207_NoDuplicateDiagnostics()
{
VerifyCSharp(@"
public struct Struct1
{
private readonly static int field, field2;
static Struct1() // Non static constructor
{
field = 0;
field2 = 0;
}
}
",
GetCA2207CSharpDefaultResultAt(5, 12, "Struct1"));
VerifyBasic(@"
Public Structure Struct1
Private Shared ReadOnly field As Integer, field2 As Integer
Shared Sub New()
' Non static constructor
field = 0
field2 = 0
End Sub
End Structure",
GetCA2207BasicDefaultResultAt(4, 13, "Struct1"));
}
#endregion
#region Helpers
protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer()
{
return new BasicInitializeStaticFieldsInlineAnalyzer();
}
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new CSharpInitializeStaticFieldsInlineAnalyzer();
}
private static DiagnosticResult GetCA1810CSharpDefaultResultAt(int line, int column, string typeName)
{
string message = string.Format(SystemRuntimeAnalyzersResources.InitializeStaticFieldsInlineMessage, typeName);
return GetCSharpResultAt(line, column, CSharpInitializeStaticFieldsInlineAnalyzer.CA1810RuleId, message);
}
private static DiagnosticResult GetCA1810BasicDefaultResultAt(int line, int column, string typeName)
{
string message = string.Format(SystemRuntimeAnalyzersResources.InitializeStaticFieldsInlineMessage, typeName);
return GetBasicResultAt(line, column, BasicInitializeStaticFieldsInlineAnalyzer.CA1810RuleId, message);
}
private static DiagnosticResult GetCA2207CSharpDefaultResultAt(int line, int column, string typeName)
{
string message = string.Format(SystemRuntimeAnalyzersResources.InitializeStaticFieldsInlineMessage, typeName);
return GetCSharpResultAt(line, column, CSharpInitializeStaticFieldsInlineAnalyzer.CA2207RuleId, message);
}
private static DiagnosticResult GetCA2207BasicDefaultResultAt(int line, int column, string typeName)
{
string message = string.Format(SystemRuntimeAnalyzersResources.InitializeStaticFieldsInlineMessage, typeName);
return GetBasicResultAt(line, column, BasicInitializeStaticFieldsInlineAnalyzer.CA2207RuleId, message);
}
#endregion
}
}
| |
//
// Frame.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.ComponentModel;
using Xwt.Drawing;
namespace Xwt
{
public class FrameBox: Widget
{
WidgetSpacing borderWidth;
WidgetSpacing padding;
FrameCanvas canvas;
Color borderColor = Colors.Black;
class FrameCanvas: Canvas
{
Widget child;
public void Resize ()
{
OnPreferredSizeChanged ();
QueueDraw ();
}
public Widget Child {
get { return child; }
set {
if (child != null)
RemoveChild (child);
child = value;
if (child != null)
AddChild (child);
Resize ();
QueueForReallocate ();
}
}
protected override Size OnGetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint)
{
FrameBox parent = (FrameBox)Parent;
Size s = new Size (parent.Padding.HorizontalSpacing + parent.BorderWidth.HorizontalSpacing, parent.Padding.VerticalSpacing + parent.BorderWidth.VerticalSpacing);
if (child != null)
s += child.Surface.GetPreferredSize (widthConstraint - s.Width, heightConstraint - s.Height, true);
return s;
}
protected override void OnReallocate ()
{
if (child != null) {
FrameBox parent = (FrameBox)Parent;
Rectangle rect = Bounds;
var padding = parent.padding;
var border = parent.borderWidth;
rect.X += padding.Left + border.Left;
rect.Y += padding.Top + border.Top;
rect.Width -= padding.HorizontalSpacing + border.HorizontalSpacing;
rect.Height -= padding.VerticalSpacing + border.VerticalSpacing;
rect = child.Surface.GetPlacementInRect (rect);
SetChildBounds (child, rect);
}
}
protected override void OnDraw (Context ctx, Rectangle dirtyRect)
{
base.OnDraw (ctx, dirtyRect);
FrameBox parent = (FrameBox)Parent;
var border = parent.borderWidth;
var r = Bounds;
//ctx.SetLineDash (0);
ctx.SetColor (parent.borderColor);
if (border.Top > 0) {
ctx.MoveTo (r.X, r.Y + border.Top / 2);
ctx.RelLineTo (r.Width, 0);
ctx.SetLineWidth (border.Top);
ctx.Stroke ();
}
if (border.Bottom > 0) {
ctx.MoveTo (r.X, r.Bottom - border.Bottom / 2);
ctx.RelLineTo (r.Width, 0);
ctx.SetLineWidth (border.Bottom);
ctx.Stroke ();
}
if (border.Left > 0) {
ctx.MoveTo (r.X + border.Left / 2, r.Y + border.Top);
ctx.RelLineTo (0, r.Height - border.Top - border.Bottom);
ctx.SetLineWidth (border.Left);
ctx.Stroke ();
}
if (border.Right > 0) {
ctx.MoveTo (r.Right - border.Right / 2, r.Y + border.Top);
ctx.RelLineTo (0, r.Height - border.Top - border.Bottom);
ctx.SetLineWidth (border.Right);
ctx.Stroke ();
}
}
}
public FrameBox ()
{
canvas = SetInternalChild (new FrameCanvas ());
base.Content = canvas;
}
public FrameBox (Widget content): this ()
{
VerifyConstructorCall (this);
Content = content;
}
public WidgetSpacing Padding {
get { return padding; }
set {
padding = value;
canvas.Resize ();
}
}
[DefaultValue (0d)]
public double PaddingLeft {
get { return padding.Left; }
set {
padding.Left = value;
canvas.Resize ();
}
}
[DefaultValue (0d)]
public double PaddingRight {
get { return padding.Right; }
set {
padding.Right = value;
canvas.Resize ();
}
}
[DefaultValue (0d)]
public double PaddingTop {
get { return padding.Top; }
set {
padding.Top = value;
canvas.Resize ();
}
}
[DefaultValue (0d)]
public double PaddingBottom {
get { return padding.Bottom; }
set {
padding.Bottom = value;
canvas.Resize ();
}
}
public WidgetSpacing BorderWidth {
get { return borderWidth; }
set {
borderWidth = value;
canvas.Resize ();
}
}
[DefaultValue (0d)]
public double BorderWidthLeft {
get { return borderWidth.Left; }
set {
borderWidth.Left = value;
canvas.Resize ();
}
}
[DefaultValue (0d)]
public double BorderWidthRight {
get { return borderWidth.Right; }
set {
borderWidth.Right = value;
canvas.Resize ();
}
}
[DefaultValue (0d)]
public double BorderWidthTop {
get { return borderWidth.Top; }
set {
borderWidth.Top = value;
canvas.Resize ();
}
}
[DefaultValue (0d)]
public double BorderWidthBottom {
get { return borderWidth.Bottom; }
set {
borderWidth.Bottom = value;
canvas.Resize ();
}
}
public Color BorderColor {
get { return borderColor; }
set { borderColor = value; canvas.QueueDraw (); }
}
/// <summary>
/// Removes all children of the Frame
/// </summary>
public void Clear ()
{
Content = null;
}
[DefaultValue (null)]
public new Widget Content {
get { return canvas.Child; }
set {
var current = canvas.Child;
canvas.Child = null;
UnregisterChild (current);
RegisterChild (value);
canvas.Child = value;
}
}
protected Widget InternalContent {
get {
return canvas;
}
}
}
}
| |
// Artificial Intelligence for Humans
// Volume 2: Nature-Inspired Algorithms
// C# Version
// http://www.aifh.org
// http://www.jeffheaton.com
//
// Code repository:
// https://github.com/jeffheaton/aifh
//
// Copyright 2014 by Jeff Heaton
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Globalization;
using System.IO;
using System.Text;
using AIFH_Vol2.Core.Randomize;
using AIFH_Vol2_MergePhysics.Universe;
namespace AIFH_Vol2_MergePhysics.Physics
{
/// <summary>
/// Merge physics determines how cells are to be populated.
/// For more information on how the physics works see:
/// http://www.codeproject.com/Articles/730362/Using-an-evolutionary-algorithm-to-create-a-cellul
/// </summary>
public class MergePhysics : IPhysics
{
/// <summary>
/// The color table.
/// </summary>
private readonly double[][] _colorTable =
{
new double[] {-1, -1, -1}, new double[] {1, -1, -1},
new double[] {-1, 1, -1}, new double[] {1, 1, -1}, new double[] {-1, -1, 1}, new double[] {1, -1, 1},
new double[] {-1, 1, 1}, new double[] {1, 1, 1}
};
/// <summary>
/// Transformations to move from a cell to the 9 neighboring cells.
/// These are the column values.
/// </summary>
private readonly int[] _colTransform = {0, 0, -1, 1, -1, 1, 1, -1};
/// <summary>
/// The data that defines the physical constants.
/// </summary>
private readonly double[] _data;
/// <summary>
/// The data sorted.
/// </summary>
private readonly int[] _dataOrder;
/// <summary>
/// Transformations to move from a cell to the 9 neighboring cells.
/// These are the row values.
/// </summary>
private readonly int[] _rowTransform = {-1, 1, 0, 0, -1, 1, -1, 1};
/// <summary>
/// The universe.
/// </summary>
private readonly UniverseHolder _universe;
/// <summary>
/// Construct the merge physics.
/// </summary>
/// <param name="theUniverse">The universe.</param>
public MergePhysics(UniverseHolder theUniverse)
{
_data = new double[2*_colorTable.Length];
_dataOrder = new int[_colorTable.Length];
_universe = theUniverse;
}
/// <inheritdoc />
public void CopyData(double[] sourceData)
{
Array.Copy(sourceData, 0, _data, 0, _data.Length);
SortData();
}
/// <inheritdoc />
public double[] Data
{
get { return _data; }
}
/// <inheritdoc />
public void Load(String filename)
{
using (FileStream fileStream = File.OpenRead(filename))
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, 128))
{
String line;
while ((line = streamReader.ReadLine()) != null)
{
line = line.Substring(1);
line = line.Substring(0, line.Length - 1);
string[] tok = line.Split(',');
int idx = 0;
foreach (string str in tok)
{
_data[idx++] = double.Parse(str, CultureInfo.InvariantCulture);
SortData();
}
}
}
}
/// <inheritdoc />
public void ProcessPixel(UniverseHolder outputUniverse, int row,
int col)
{
double total = 0;
int cnt = 0;
for (int dir = 0; dir < _rowTransform.Length; dir++)
{
int otherRow = row + _rowTransform[dir];
int otherCol = col + _colTransform[dir];
if (_universe.IsValid(otherRow, otherCol))
{
UniverseCell otherCell = _universe.Get(otherRow,
otherCol);
total += otherCell.Avg;
cnt++;
}
}
total /= cnt;
for (int i = 0; i < _colorTable.Length; i++)
{
int idx = _dataOrder[i];
if (total < _data[idx*2])
{
for (int j = 0; j < outputUniverse.CellSize; j++)
{
double d = _colorTable[idx][j]
- _universe.Get(row, col).Data[j];
double pct = _data[1 + idx*2];
pct = (pct + 1.0)/2.0;
d *= pct;
outputUniverse.Add(row, col, j, d);
}
break;
}
}
}
/// <inheritdoc />
public void Randomize()
{
IGenerateRandom rnd = new MersenneTwisterGenerateRandom();
for (int i = 0; i < _data.Length; i++)
{
_data[i] = rnd.NextDouble()*2.0 - 1.0;
}
SortData();
}
/// <inheritdoc />
public void Save(string filename)
{
using (StreamWriter dest = File.CreateText(filename))
{
bool first = true;
dest.Write("[");
foreach (double d in _data)
{
if (!first)
{
dest.Write(",");
}
dest.Write(d.ToString(CultureInfo.InvariantCulture));
first = false;
}
dest.WriteLine("]");
}
}
/// <summary>
/// Determine if "value" is in the array.
/// </summary>
/// <param name="list">The list.</param>
/// <param name="len">The length.</param>
/// <param name="value">The value.</param>
/// <returns>True, if value is in the list.</returns>
private bool ListContains(int[] list, int len,
int value)
{
for (int i = 0; i < len; i++)
{
if (list[i] == value)
{
return true;
}
}
return false;
}
/// <summary>
/// Sort the physical data for faster lookup.
/// </summary>
private void SortData()
{
// create the order table
for (int x = 0; x < _colorTable.Length; x++)
{
int lowestIndex = -1;
for (int y = 0; y < _colorTable.Length; y++)
{
double value = _data[y*2];
// Only consider positions that are not already in the list.
if (!ListContains(_dataOrder, x, y))
{
// See if this is the lowest index found for this pass.
if (lowestIndex == -1)
{
lowestIndex = y;
}
else
{
if (value < _data[lowestIndex*2])
{
lowestIndex = y;
}
}
}
}
_dataOrder[x] = lowestIndex;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
// The Windows implementation of PipeStream sets the stream's handle during
// creation, and as such should always have a handle, but the Unix implementation
// sometimes sets the handle not during creation but later during connection.
// As such, validation during member access needs to verify a valid handle on
// Windows, but can't assume a valid handle on Unix.
internal const bool CheckOperationsRequiresSetHandle = false;
/// <summary>Characters that can't be used in a pipe's name.</summary>
private static readonly char[] s_invalidFileNameChars = Path.GetInvalidFileNameChars();
/// <summary>Prefix to prepend to all pipe names.</summary>
private static readonly string s_pipePrefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_");
internal static string GetPipePath(string serverName, string pipeName)
{
if (serverName != "." && serverName != Interop.Sys.GetHostName())
{
// Cross-machine pipes are not supported.
throw new PlatformNotSupportedException(SR.PlatformNotSupported_RemotePipes);
}
if (string.Equals(pipeName, AnonymousPipeName, StringComparison.OrdinalIgnoreCase))
{
// Match Windows constraint
throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
}
if (pipeName.IndexOfAny(s_invalidFileNameChars) >= 0)
{
// Since pipes are stored as files in the file system, we don't support
// pipe names that are actually paths or that otherwise have invalid
// filename characters in them.
throw new PlatformNotSupportedException(SR.PlatformNotSupproted_InvalidNameChars);
}
// Return the pipe path. The pipe is created directly under %TMPDIR%. We previously
// didn't put it into a subdirectory because it only existed on disk for the duration
// between when the server started listening in WaitForConnection and when the client
// connected, after which the pipe was deleted. We now create the pipe when the
// server stream is created, which leaves it on disk longer, but we can't change the
// naming scheme used as that breaks the ability for code running on an older
// runtime to connect to code running on the newer runtime. That means we're stuck
// with a tmp file for the lifetime of the server stream.
return s_pipePrefix + pipeName;
}
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
if (safePipeHandle.NamedPipeSocket == null)
{
Interop.Sys.FileStatus status;
int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status));
if (result == 0)
{
if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO &&
(status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFSOCK)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
}
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// nop
}
internal virtual void DisposeCore(bool disposing)
{
// nop
}
private unsafe int ReadCore(Span<byte> buffer)
{
DebugAssertHandleValid(_handle);
// For named pipes, receive on the socket.
Socket socket = _handle.NamedPipeSocket;
if (socket != null)
{
// For a blocking socket, we could simply use the same Read syscall as is done
// for reading an anonymous pipe. However, for a non-blocking socket, Read could
// end up returning EWOULDBLOCK rather than blocking waiting for data. Such a case
// is already handled by Socket.Receive, so we use it here.
try
{
return socket.Receive(buffer, SocketFlags.None);
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
// For anonymous pipes, read from the file descriptor.
fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer))
{
int result = CheckPipeCall(Interop.Sys.Read(_handle, bufPtr, buffer.Length));
Debug.Assert(result <= buffer.Length);
return result;
}
}
private unsafe void WriteCore(ReadOnlySpan<byte> buffer)
{
DebugAssertHandleValid(_handle);
// For named pipes, send to the socket.
Socket socket = _handle.NamedPipeSocket;
if (socket != null)
{
// For a blocking socket, we could simply use the same Write syscall as is done
// for writing to anonymous pipe. However, for a non-blocking socket, Write could
// end up returning EWOULDBLOCK rather than blocking waiting for space available.
// Such a case is already handled by Socket.Send, so we use it here.
try
{
while (buffer.Length > 0)
{
int bytesWritten = socket.Send(buffer, SocketFlags.None);
buffer = buffer.Slice(bytesWritten);
}
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
// For anonymous pipes, write the file descriptor.
fixed (byte* bufPtr = &MemoryMarshal.GetReference(buffer))
{
while (buffer.Length > 0)
{
int bytesWritten = CheckPipeCall(Interop.Sys.Write(_handle, bufPtr, buffer.Length));
buffer = buffer.Slice(bytesWritten);
}
}
}
private async Task<int> ReadAsyncCore(Memory<byte> destination, CancellationToken cancellationToken)
{
Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
Socket socket = InternalHandle.NamedPipeSocket;
try
{
// TODO #22608:
// Remove all of this cancellation workaround once Socket.ReceiveAsync
// that accepts a CancellationToken is available.
// If a cancelable token is used and there's no data, issue a zero-length read so that
// we're asynchronously notified when data is available, and concurrently monitor the
// supplied cancellation token. If cancellation is requested, we will end up "leaking"
// the zero-length read until data becomes available, at which point it'll be satisfied.
// But it's very rare to reuse a stream after an operation has been canceled, so even if
// we do incur such a situation, it's likely to be very short lived.
if (cancellationToken.CanBeCanceled)
{
cancellationToken.ThrowIfCancellationRequested();
if (socket.Available == 0)
{
Task<int> t = socket.ReceiveAsync(Array.Empty<byte>(), SocketFlags.None);
if (!t.IsCompletedSuccessfully)
{
var cancelTcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), cancelTcs))
{
if (t == await Task.WhenAny(t, cancelTcs.Task).ConfigureAwait(false))
{
t.GetAwaiter().GetResult(); // propagate any failure
}
cancellationToken.ThrowIfCancellationRequested();
// At this point there was data available. In the rare case where multiple concurrent
// ReadAsyncs are issued against the PipeStream, worst case is the reads that lose
// the race condition for the data will end up in a non-cancelable state as part of
// the actual async receive operation.
}
}
}
}
// Issue the asynchronous read.
return await (destination.TryGetArray(out ArraySegment<byte> buffer) ?
socket.ReceiveAsync(buffer, SocketFlags.None) :
socket.ReceiveAsync(destination.ToArray(), SocketFlags.None)).ConfigureAwait(false);
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
private async Task WriteAsyncCore(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
{
Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
try
{
// TODO #22608: Remove this terribly inefficient special-case once Socket.SendAsync
// accepts a Memory<T> in the near future.
byte[] buffer;
int offset, count;
if (MemoryMarshal.TryGetArray(source, out ArraySegment<byte> segment))
{
buffer = segment.Array;
offset = segment.Offset;
count = segment.Count;
}
else
{
buffer = source.ToArray();
offset = 0;
count = buffer.Length;
}
while (count > 0)
{
// cancellationToken is (mostly) ignored. We could institute a polling loop like we do for reads if
// cancellationToken.CanBeCanceled, but that adds costs regardless of whether the operation will be canceled, and
// most writes will complete immediately as they simply store data into the socket's buffer. The only time we end
// up using it in a meaningful way is if a write completes partially, we'll check it on each individual write operation.
cancellationToken.ThrowIfCancellationRequested();
int bytesWritten = await _handle.NamedPipeSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false);
Debug.Assert(bytesWritten <= count);
count -= bytesWritten;
offset += bytesWritten;
}
}
catch (SocketException e)
{
throw GetIOExceptionForSocketException(e);
}
}
private IOException GetIOExceptionForSocketException(SocketException e)
{
if (e.SocketErrorCode == SocketError.Shutdown) // EPIPE
{
State = PipeState.Broken;
}
return new IOException(e.Message, e);
}
// Blocks until the other end of the pipe has read in all written buffer.
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
// For named pipes on sockets, we could potentially partially implement this
// via ioctl and TIOCOUTQ, which provides the number of unsent bytes. However,
// that would require polling, and it wouldn't actually mean that the other
// end has read all of the data, just that the data has left this end's buffer.
throw new PlatformNotSupportedException(); // not fully implementable on unix
}
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public virtual PipeTransmissionMode TransmissionMode
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public virtual int InBufferSize
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
return GetPipeBufferSize();
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public virtual int OutBufferSize
{
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
return GetPipeBufferSize();
}
}
public virtual PipeTransmissionMode ReadMode
{
get
{
CheckPipePropertyOperations();
return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode);
}
// nop, since it's already the only valid value
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>
/// We want to ensure that only one asynchronous operation is actually in flight
/// at a time. The base Stream class ensures this by serializing execution via a
/// semaphore. Since we don't delegate to the base stream for Read/WriteAsync due
/// to having specialized support for cancellation, we do the same serialization here.
/// </summary>
private SemaphoreSlim _asyncActiveSemaphore;
private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
private static void CreateDirectory(string directoryPath)
{
int result = Interop.Sys.MkDir(directoryPath, (int)Interop.Sys.Permissions.Mask);
// If successful created, we're done.
if (result >= 0)
return;
// If the directory already exists, consider it a success.
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EEXIST)
return;
// Otherwise, fail.
throw Interop.GetExceptionForIoErrno(errorInfo, directoryPath, isDirectory: true);
}
/// <summary>Creates an anonymous pipe.</summary>
/// <param name="inheritability">The inheritability to try to use. This may not always be honored, depending on platform.</param>
/// <param name="reader">The resulting reader end of the pipe.</param>
/// <param name="writer">The resulting writer end of the pipe.</param>
internal static unsafe void CreateAnonymousPipe(
HandleInheritability inheritability, out SafePipeHandle reader, out SafePipeHandle writer)
{
// Allocate the safe handle objects prior to calling pipe/pipe2, in order to help slightly in low-mem situations
reader = new SafePipeHandle();
writer = new SafePipeHandle();
// Create the OS pipe
int* fds = stackalloc int[2];
CreateAnonymousPipe(inheritability, fds);
// Store the file descriptors into our safe handles
reader.SetHandle(fds[Interop.Sys.ReadEndOfPipe]);
writer.SetHandle(fds[Interop.Sys.WriteEndOfPipe]);
}
internal int CheckPipeCall(int result)
{
if (result == -1)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
if (errorInfo.Error == Interop.Error.EPIPE)
State = PipeState.Broken;
throw Interop.GetExceptionForIoErrno(errorInfo);
}
return result;
}
private int GetPipeBufferSize()
{
if (!Interop.Sys.Fcntl.CanGetSetPipeSz)
{
throw new PlatformNotSupportedException(); // OS does not support getting pipe size
}
// If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction).
// If we don't, just return the buffer size that was passed to the constructor.
return _handle != null ?
CheckPipeCall(Interop.Sys.Fcntl.GetPipeSz(_handle)) :
_outBufferSize;
}
internal static unsafe void CreateAnonymousPipe(HandleInheritability inheritability, int* fdsptr)
{
var flags = (inheritability & HandleInheritability.Inheritable) == 0 ?
Interop.Sys.PipeFlags.O_CLOEXEC : 0;
Interop.CheckIo(Interop.Sys.Pipe(fdsptr, flags));
}
internal static void ConfigureSocket(
Socket s, SafePipeHandle pipeHandle,
PipeDirection direction, int inBufferSize, int outBufferSize, HandleInheritability inheritability)
{
if (inBufferSize > 0)
{
s.ReceiveBufferSize = inBufferSize;
}
if (outBufferSize > 0)
{
s.SendBufferSize = outBufferSize;
}
if (inheritability != HandleInheritability.Inheritable)
{
Interop.Sys.Fcntl.SetCloseOnExec(pipeHandle); // ignore failures, best-effort attempt
}
switch (direction)
{
case PipeDirection.In:
s.Shutdown(SocketShutdown.Send);
break;
case PipeDirection.Out:
s.Shutdown(SocketShutdown.Receive);
break;
}
}
}
}
| |
using System;
using Server;
using Server.Network;
using System.Collections;
using System.Collections.Generic;
namespace Server.Items
{
public class WarningItem : Item
{
private string m_WarningString;
private int m_WarningNumber;
private int m_Range;
private TimeSpan m_ResetDelay;
[CommandProperty( AccessLevel.GameMaster )]
public string WarningString
{
get{ return m_WarningString; }
set{ m_WarningString = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public int WarningNumber
{
get{ return m_WarningNumber; }
set{ m_WarningNumber = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public int Range
{
get{ return m_Range; }
set{ if ( value > 18 ) value = 18; m_Range = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public TimeSpan ResetDelay
{
get{ return m_ResetDelay; }
set{ m_ResetDelay = value; }
}
[Constructable]
public WarningItem( int itemID, int range, int warning ) : base( itemID )
{
if ( range > 18 )
range = 18;
Movable = false;
m_WarningNumber = warning;
m_Range = range;
}
[Constructable]
public WarningItem( int itemID, int range, string warning ) : base( itemID )
{
if ( range > 18 )
range = 18;
Movable = false;
m_WarningString = warning;
m_Range = range;
}
public WarningItem( Serial serial ) : base( serial )
{
}
private bool m_Broadcasting;
private DateTime m_LastBroadcast;
public virtual void SendMessage( Mobile triggerer, bool onlyToTriggerer, string messageString, int messageNumber )
{
if ( onlyToTriggerer )
{
if ( messageString != null )
triggerer.SendMessage( messageString );
else
triggerer.SendLocalizedMessage( messageNumber );
}
else
{
if ( messageString != null )
PublicOverheadMessage( MessageType.Regular, 0x3B2, false, messageString );
else
PublicOverheadMessage( MessageType.Regular, 0x3B2, messageNumber );
}
}
public virtual bool OnlyToTriggerer{ get{ return false; } }
public virtual int NeighborRange { get { return 5; } }
public virtual void Broadcast( Mobile triggerer )
{
if ( m_Broadcasting || (DateTime.Now < (m_LastBroadcast + m_ResetDelay)) )
return;
m_LastBroadcast = DateTime.Now;
m_Broadcasting = true;
SendMessage( triggerer, this.OnlyToTriggerer, m_WarningString, m_WarningNumber );
if ( NeighborRange >= 0 )
{
List<WarningItem> list = new List<WarningItem>();
foreach ( Item item in GetItemsInRange( NeighborRange ) )
{
if ( item != this && item is WarningItem )
list.Add( (WarningItem)item );
}
for ( int i = 0; i < list.Count; i++ )
list[i].Broadcast( triggerer );
}
Timer.DelayCall( TimeSpan.Zero, new TimerCallback( InternalCallback ) );
}
private void InternalCallback()
{
m_Broadcasting = false;
}
public override bool HandlesOnMovement{ get{ return true; } }
public override void OnMovement( Mobile m, Point3D oldLocation )
{
if ( m.Player && Utility.InRange( m.Location, Location, m_Range ) && !Utility.InRange( oldLocation, Location, m_Range ) )
Broadcast( m );
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
writer.Write( (string) m_WarningString );
writer.Write( (int) m_WarningNumber );
writer.Write( (int) m_Range );
writer.Write( (TimeSpan) m_ResetDelay );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_WarningString = reader.ReadString();
m_WarningNumber = reader.ReadInt();
m_Range = reader.ReadInt();
m_ResetDelay = reader.ReadTimeSpan();
break;
}
}
}
}
public class HintItem : WarningItem
{
private string m_HintString;
private int m_HintNumber;
[CommandProperty( AccessLevel.GameMaster )]
public string HintString
{
get{ return m_HintString; }
set{ m_HintString = value; }
}
[CommandProperty( AccessLevel.GameMaster )]
public int HintNumber
{
get{ return m_HintNumber; }
set{ m_HintNumber = value; }
}
public override bool OnlyToTriggerer{ get{ return true; } }
[Constructable]
public HintItem( int itemID, int range, int warning, int hint ) : base( itemID, range, warning )
{
m_HintNumber = hint;
}
[Constructable]
public HintItem( int itemID, int range, string warning, string hint ) : base( itemID, range, warning )
{
m_HintString = hint;
}
public HintItem( Serial serial ) : base( serial )
{
}
public override void OnDoubleClick( Mobile from )
{
SendMessage( from, true, m_HintString, m_HintNumber );
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 );
writer.Write( (string) m_HintString );
writer.Write( (int) m_HintNumber );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_HintString = reader.ReadString();
m_HintNumber = reader.ReadInt();
break;
}
}
}
}
}
| |
using System;
using System.Collections;
namespace OTFontFile
{
/// <summary>
/// Summary description for PostNames.
/// </summary>
public class PostNames
{
public PostNames()
{
InitNames();
}
public string GetAdobeGlyphName(char c)
{
return (string)m_hashNames[((uint)c).ToString("X4")];
}
void InitNames()
{
m_hashNames = new Hashtable();
// attempting to use uints as the key always made the hashtable return null
// this didn't work, but using strings as the key works:
// m_hashNames.Add(0x0020, "space");
m_hashNames.Add("0020", "space");
m_hashNames.Add("0021", "exclam");
m_hashNames.Add("0022", "quotedbl");
m_hashNames.Add("0023", "numbersign");
m_hashNames.Add("0024", "dollar");
m_hashNames.Add("0025", "percent");
m_hashNames.Add("0026", "ampersand");
m_hashNames.Add("0027", "quotesingle");
m_hashNames.Add("0028", "parenleft");
m_hashNames.Add("0029", "parenright");
m_hashNames.Add("002A", "asterisk");
m_hashNames.Add("002B", "plus");
m_hashNames.Add("002C", "comma");
m_hashNames.Add("002D", "hyphen");
m_hashNames.Add("002E", "period");
m_hashNames.Add("002F", "slash");
m_hashNames.Add("0030", "zero");
m_hashNames.Add("0031", "one");
m_hashNames.Add("0032", "two");
m_hashNames.Add("0033", "three");
m_hashNames.Add("0034", "four");
m_hashNames.Add("0035", "five");
m_hashNames.Add("0036", "six");
m_hashNames.Add("0037", "seven");
m_hashNames.Add("0038", "eight");
m_hashNames.Add("0039", "nine");
m_hashNames.Add("003A", "colon");
m_hashNames.Add("003B", "semicolon");
m_hashNames.Add("003C", "less");
m_hashNames.Add("003D", "equal");
m_hashNames.Add("003E", "greater");
m_hashNames.Add("003F", "question");
m_hashNames.Add("0040", "at");
m_hashNames.Add("0041", "A");
m_hashNames.Add("0042", "B");
m_hashNames.Add("0043", "C");
m_hashNames.Add("0044", "D");
m_hashNames.Add("0045", "E");
m_hashNames.Add("0046", "F");
m_hashNames.Add("0047", "G");
m_hashNames.Add("0048", "H");
m_hashNames.Add("0049", "I");
m_hashNames.Add("004A", "J");
m_hashNames.Add("004B", "K");
m_hashNames.Add("004C", "L");
m_hashNames.Add("004D", "M");
m_hashNames.Add("004E", "N");
m_hashNames.Add("004F", "O");
m_hashNames.Add("0050", "P");
m_hashNames.Add("0051", "Q");
m_hashNames.Add("0052", "R");
m_hashNames.Add("0053", "S");
m_hashNames.Add("0054", "T");
m_hashNames.Add("0055", "U");
m_hashNames.Add("0056", "V");
m_hashNames.Add("0057", "W");
m_hashNames.Add("0058", "X");
m_hashNames.Add("0059", "Y");
m_hashNames.Add("005A", "Z");
m_hashNames.Add("005B", "bracketleft");
m_hashNames.Add("005C", "backslash");
m_hashNames.Add("005D", "bracketright");
m_hashNames.Add("005E", "asciicircum");
m_hashNames.Add("005F", "underscore");
m_hashNames.Add("0060", "grave");
m_hashNames.Add("0061", "a");
m_hashNames.Add("0062", "b");
m_hashNames.Add("0063", "c");
m_hashNames.Add("0064", "d");
m_hashNames.Add("0065", "e");
m_hashNames.Add("0066", "f");
m_hashNames.Add("0067", "g");
m_hashNames.Add("0068", "h");
m_hashNames.Add("0069", "i");
m_hashNames.Add("006A", "j");
m_hashNames.Add("006B", "k");
m_hashNames.Add("006C", "l");
m_hashNames.Add("006D", "m");
m_hashNames.Add("006E", "n");
m_hashNames.Add("006F", "o");
m_hashNames.Add("0070", "p");
m_hashNames.Add("0071", "q");
m_hashNames.Add("0072", "r");
m_hashNames.Add("0073", "s");
m_hashNames.Add("0074", "t");
m_hashNames.Add("0075", "u");
m_hashNames.Add("0076", "v");
m_hashNames.Add("0077", "w");
m_hashNames.Add("0078", "x");
m_hashNames.Add("0079", "y");
m_hashNames.Add("007A", "z");
m_hashNames.Add("007B", "braceleft");
m_hashNames.Add("007C", "bar");
m_hashNames.Add("007D", "braceright");
m_hashNames.Add("007E", "asciitilde");
m_hashNames.Add("00A0", "space");
m_hashNames.Add("00A1", "exclamdown");
m_hashNames.Add("00A2", "cent");
m_hashNames.Add("00A3", "sterling");
m_hashNames.Add("00A4", "currency");
m_hashNames.Add("00A5", "yen");
m_hashNames.Add("00A6", "brokenbar");
m_hashNames.Add("00A7", "section");
m_hashNames.Add("00A8", "dieresis");
m_hashNames.Add("00A9", "copyright");
m_hashNames.Add("00AA", "ordfeminine");
m_hashNames.Add("00AB", "guillemotleft");
m_hashNames.Add("00AC", "logicalnot");
m_hashNames.Add("00AD", "hyphen");
m_hashNames.Add("00AE", "registered");
m_hashNames.Add("00AF", "macron");
m_hashNames.Add("00B0", "degree");
m_hashNames.Add("00B1", "plusminus");
m_hashNames.Add("00B2", "twosuperior");
m_hashNames.Add("00B3", "threesuperior");
m_hashNames.Add("00B4", "acute");
m_hashNames.Add("00B5", "mu");
m_hashNames.Add("00B6", "paragraph");
m_hashNames.Add("00B7", "periodcentered");
m_hashNames.Add("00B8", "cedilla");
m_hashNames.Add("00B9", "onesuperior");
m_hashNames.Add("00BA", "ordmasculine");
m_hashNames.Add("00BB", "guillemotright");
m_hashNames.Add("00BC", "onequarter");
m_hashNames.Add("00BD", "onehalf");
m_hashNames.Add("00BE", "threequarters");
m_hashNames.Add("00BF", "questiondown");
m_hashNames.Add("00C0", "Agrave");
m_hashNames.Add("00C1", "Aacute");
m_hashNames.Add("00C2", "Acircumflex");
m_hashNames.Add("00C3", "Atilde");
m_hashNames.Add("00C4", "Adieresis");
m_hashNames.Add("00C5", "Aring");
m_hashNames.Add("00C6", "AE");
m_hashNames.Add("00C7", "Ccedilla");
m_hashNames.Add("00C8", "Egrave");
m_hashNames.Add("00C9", "Eacute");
m_hashNames.Add("00CA", "Ecircumflex");
m_hashNames.Add("00CB", "Edieresis");
m_hashNames.Add("00CC", "Igrave");
m_hashNames.Add("00CD", "Iacute");
m_hashNames.Add("00CE", "Icircumflex");
m_hashNames.Add("00CF", "Idieresis");
m_hashNames.Add("00D0", "Eth");
m_hashNames.Add("00D1", "Ntilde");
m_hashNames.Add("00D2", "Ograve");
m_hashNames.Add("00D3", "Oacute");
m_hashNames.Add("00D4", "Ocircumflex");
m_hashNames.Add("00D5", "Otilde");
m_hashNames.Add("00D6", "Odieresis");
m_hashNames.Add("00D7", "multiply");
m_hashNames.Add("00D8", "Oslash");
m_hashNames.Add("00D9", "Ugrave");
m_hashNames.Add("00DA", "Uacute");
m_hashNames.Add("00DB", "Ucircumflex");
m_hashNames.Add("00DC", "Udieresis");
m_hashNames.Add("00DD", "Yacute");
m_hashNames.Add("00DE", "Thorn");
m_hashNames.Add("00DF", "germandbls");
m_hashNames.Add("00E0", "agrave");
m_hashNames.Add("00E1", "aacute");
m_hashNames.Add("00E2", "acircumflex");
m_hashNames.Add("00E3", "atilde");
m_hashNames.Add("00E4", "adieresis");
m_hashNames.Add("00E5", "aring");
m_hashNames.Add("00E6", "ae");
m_hashNames.Add("00E7", "ccedilla");
m_hashNames.Add("00E8", "egrave");
m_hashNames.Add("00E9", "eacute");
m_hashNames.Add("00EA", "ecircumflex");
m_hashNames.Add("00EB", "edieresis");
m_hashNames.Add("00EC", "igrave");
m_hashNames.Add("00ED", "iacute");
m_hashNames.Add("00EE", "icircumflex");
m_hashNames.Add("00EF", "idieresis");
m_hashNames.Add("00F0", "eth");
m_hashNames.Add("00F1", "ntilde");
m_hashNames.Add("00F2", "ograve");
m_hashNames.Add("00F3", "oacute");
m_hashNames.Add("00F4", "ocircumflex");
m_hashNames.Add("00F5", "otilde");
m_hashNames.Add("00F6", "odieresis");
m_hashNames.Add("00F7", "divide");
m_hashNames.Add("00F8", "oslash");
m_hashNames.Add("00F9", "ugrave");
m_hashNames.Add("00FA", "uacute");
m_hashNames.Add("00FB", "ucircumflex");
m_hashNames.Add("00FC", "udieresis");
m_hashNames.Add("00FD", "yacute");
m_hashNames.Add("00FE", "thorn");
m_hashNames.Add("00FF", "ydieresis");
m_hashNames.Add("0100", "Amacron");
m_hashNames.Add("0101", "amacron");
m_hashNames.Add("0102", "Abreve");
m_hashNames.Add("0103", "abreve");
m_hashNames.Add("0104", "Aogonek");
m_hashNames.Add("0105", "aogonek");
m_hashNames.Add("0106", "Cacute");
m_hashNames.Add("0107", "cacute");
m_hashNames.Add("0108", "Ccircumflex");
m_hashNames.Add("0109", "ccircumflex");
m_hashNames.Add("010A", "Cdotaccent");
m_hashNames.Add("010B", "cdotaccent");
m_hashNames.Add("010C", "Ccaron");
m_hashNames.Add("010D", "ccaron");
m_hashNames.Add("010E", "Dcaron");
m_hashNames.Add("010F", "dcaron");
m_hashNames.Add("0110", "Dcroat");
m_hashNames.Add("0111", "dcroat");
m_hashNames.Add("0112", "Emacron");
m_hashNames.Add("0113", "emacron");
m_hashNames.Add("0114", "Ebreve");
m_hashNames.Add("0115", "ebreve");
m_hashNames.Add("0116", "Edotaccent");
m_hashNames.Add("0117", "edotaccent");
m_hashNames.Add("0118", "Eogonek");
m_hashNames.Add("0119", "eogonek");
m_hashNames.Add("011A", "Ecaron");
m_hashNames.Add("011B", "ecaron");
m_hashNames.Add("011C", "Gcircumflex");
m_hashNames.Add("011D", "gcircumflex");
m_hashNames.Add("011E", "Gbreve");
m_hashNames.Add("011F", "gbreve");
m_hashNames.Add("0120", "Gdotaccent");
m_hashNames.Add("0121", "gdotaccent");
m_hashNames.Add("0122", "Gcommaaccent");
m_hashNames.Add("0123", "gcommaaccent");
m_hashNames.Add("0124", "Hcircumflex");
m_hashNames.Add("0125", "hcircumflex");
m_hashNames.Add("0126", "Hbar");
m_hashNames.Add("0127", "hbar");
m_hashNames.Add("0128", "Itilde");
m_hashNames.Add("0129", "itilde");
m_hashNames.Add("012A", "Imacron");
m_hashNames.Add("012B", "imacron");
m_hashNames.Add("012C", "Ibreve");
m_hashNames.Add("012D", "ibreve");
m_hashNames.Add("012E", "Iogonek");
m_hashNames.Add("012F", "iogonek");
m_hashNames.Add("0130", "Idotaccent");
m_hashNames.Add("0131", "dotlessi");
m_hashNames.Add("0132", "IJ");
m_hashNames.Add("0133", "ij");
m_hashNames.Add("0134", "Jcircumflex");
m_hashNames.Add("0135", "jcircumflex");
m_hashNames.Add("0136", "Kcommaaccent");
m_hashNames.Add("0137", "kcommaaccent");
m_hashNames.Add("0138", "kgreenlandic");
m_hashNames.Add("0139", "Lacute");
m_hashNames.Add("013A", "lacute");
m_hashNames.Add("013B", "Lcommaaccent");
m_hashNames.Add("013C", "lcommaaccent");
m_hashNames.Add("013D", "Lcaron");
m_hashNames.Add("013E", "lcaron");
m_hashNames.Add("013F", "Ldot");
m_hashNames.Add("0140", "ldot");
m_hashNames.Add("0141", "Lslash");
m_hashNames.Add("0142", "lslash");
m_hashNames.Add("0143", "Nacute");
m_hashNames.Add("0144", "nacute");
m_hashNames.Add("0145", "Ncommaaccent");
m_hashNames.Add("0146", "ncommaaccent");
m_hashNames.Add("0147", "Ncaron");
m_hashNames.Add("0148", "ncaron");
m_hashNames.Add("0149", "napostrophe");
m_hashNames.Add("014A", "Eng");
m_hashNames.Add("014B", "eng");
m_hashNames.Add("014C", "Omacron");
m_hashNames.Add("014D", "omacron");
m_hashNames.Add("014E", "Obreve");
m_hashNames.Add("014F", "obreve");
m_hashNames.Add("0150", "Ohungarumlaut");
m_hashNames.Add("0151", "ohungarumlaut");
m_hashNames.Add("0152", "OE");
m_hashNames.Add("0153", "oe");
m_hashNames.Add("0154", "Racute");
m_hashNames.Add("0155", "racute");
m_hashNames.Add("0156", "Rcommaaccent");
m_hashNames.Add("0157", "rcommaaccent");
m_hashNames.Add("0158", "Rcaron");
m_hashNames.Add("0159", "rcaron");
m_hashNames.Add("015A", "Sacute");
m_hashNames.Add("015B", "sacute");
m_hashNames.Add("015C", "Scircumflex");
m_hashNames.Add("015D", "scircumflex");
m_hashNames.Add("015E", "Scedilla");
m_hashNames.Add("015F", "scedilla");
m_hashNames.Add("0160", "Scaron");
m_hashNames.Add("0161", "scaron");
m_hashNames.Add("0162", "Tcommaaccent");
m_hashNames.Add("0163", "tcommaaccent");
m_hashNames.Add("0164", "Tcaron");
m_hashNames.Add("0165", "tcaron");
m_hashNames.Add("0166", "Tbar");
m_hashNames.Add("0167", "tbar");
m_hashNames.Add("0168", "Utilde");
m_hashNames.Add("0169", "utilde");
m_hashNames.Add("016A", "Umacron");
m_hashNames.Add("016B", "umacron");
m_hashNames.Add("016C", "Ubreve");
m_hashNames.Add("016D", "ubreve");
m_hashNames.Add("016E", "Uring");
m_hashNames.Add("016F", "uring");
m_hashNames.Add("0170", "Uhungarumlaut");
m_hashNames.Add("0171", "uhungarumlaut");
m_hashNames.Add("0172", "Uogonek");
m_hashNames.Add("0173", "uogonek");
m_hashNames.Add("0174", "Wcircumflex");
m_hashNames.Add("0175", "wcircumflex");
m_hashNames.Add("0176", "Ycircumflex");
m_hashNames.Add("0177", "ycircumflex");
m_hashNames.Add("0178", "Ydieresis");
m_hashNames.Add("0179", "Zacute");
m_hashNames.Add("017A", "zacute");
m_hashNames.Add("017B", "Zdotaccent");
m_hashNames.Add("017C", "zdotaccent");
m_hashNames.Add("017D", "Zcaron");
m_hashNames.Add("017E", "zcaron");
m_hashNames.Add("017F", "longs");
m_hashNames.Add("0192", "florin");
m_hashNames.Add("01A0", "Ohorn");
m_hashNames.Add("01A1", "ohorn");
m_hashNames.Add("01AF", "Uhorn");
m_hashNames.Add("01B0", "uhorn");
m_hashNames.Add("01E6", "Gcaron");
m_hashNames.Add("01E7", "gcaron");
m_hashNames.Add("01FA", "Aringacute");
m_hashNames.Add("01FB", "aringacute");
m_hashNames.Add("01FC", "AEacute");
m_hashNames.Add("01FD", "aeacute");
m_hashNames.Add("01FE", "Oslashacute");
m_hashNames.Add("01FF", "oslashacute");
m_hashNames.Add("0218", "Scommaaccent");
m_hashNames.Add("0219", "scommaaccent");
m_hashNames.Add("021A", "Tcommaaccent");
m_hashNames.Add("021B", "tcommaaccent");
m_hashNames.Add("02BC", "afii57929");
m_hashNames.Add("02BD", "afii64937");
m_hashNames.Add("02C6", "circumflex");
m_hashNames.Add("02C7", "caron");
m_hashNames.Add("02C9", "macron");
m_hashNames.Add("02D8", "breve");
m_hashNames.Add("02D9", "dotaccent");
m_hashNames.Add("02DA", "ring");
m_hashNames.Add("02DB", "ogonek");
m_hashNames.Add("02DC", "tilde");
m_hashNames.Add("02DD", "hungarumlaut");
m_hashNames.Add("0300", "gravecomb");
m_hashNames.Add("0301", "acutecomb");
m_hashNames.Add("0303", "tildecomb");
m_hashNames.Add("0309", "hookabovecomb");
m_hashNames.Add("0323", "dotbelowcomb");
m_hashNames.Add("0384", "tonos");
m_hashNames.Add("0385", "dieresistonos");
m_hashNames.Add("0386", "Alphatonos");
m_hashNames.Add("0387", "anoteleia");
m_hashNames.Add("0388", "Epsilontonos");
m_hashNames.Add("0389", "Etatonos");
m_hashNames.Add("038A", "Iotatonos");
m_hashNames.Add("038C", "Omicrontonos");
m_hashNames.Add("038E", "Upsilontonos");
m_hashNames.Add("038F", "Omegatonos");
m_hashNames.Add("0390", "iotadieresistonos");
m_hashNames.Add("0391", "Alpha");
m_hashNames.Add("0392", "Beta");
m_hashNames.Add("0393", "Gamma");
m_hashNames.Add("0394", "Delta");
m_hashNames.Add("0395", "Epsilon");
m_hashNames.Add("0396", "Zeta");
m_hashNames.Add("0397", "Eta");
m_hashNames.Add("0398", "Theta");
m_hashNames.Add("0399", "Iota");
m_hashNames.Add("039A", "Kappa");
m_hashNames.Add("039B", "Lambda");
m_hashNames.Add("039C", "Mu");
m_hashNames.Add("039D", "Nu");
m_hashNames.Add("039E", "Xi");
m_hashNames.Add("039F", "Omicron");
m_hashNames.Add("03A0", "Pi");
m_hashNames.Add("03A1", "Rho");
m_hashNames.Add("03A3", "Sigma");
m_hashNames.Add("03A4", "Tau");
m_hashNames.Add("03A5", "Upsilon");
m_hashNames.Add("03A6", "Phi");
m_hashNames.Add("03A7", "Chi");
m_hashNames.Add("03A8", "Psi");
m_hashNames.Add("03A9", "Omega");
m_hashNames.Add("03AA", "Iotadieresis");
m_hashNames.Add("03AB", "Upsilondieresis");
m_hashNames.Add("03AC", "alphatonos");
m_hashNames.Add("03AD", "epsilontonos");
m_hashNames.Add("03AE", "etatonos");
m_hashNames.Add("03AF", "iotatonos");
m_hashNames.Add("03B0", "upsilondieresistonos");
m_hashNames.Add("03B1", "alpha");
m_hashNames.Add("03B2", "beta");
m_hashNames.Add("03B3", "gamma");
m_hashNames.Add("03B4", "delta");
m_hashNames.Add("03B5", "epsilon");
m_hashNames.Add("03B6", "zeta");
m_hashNames.Add("03B7", "eta");
m_hashNames.Add("03B8", "theta");
m_hashNames.Add("03B9", "iota");
m_hashNames.Add("03BA", "kappa");
m_hashNames.Add("03BB", "lambda");
m_hashNames.Add("03BC", "mu");
m_hashNames.Add("03BD", "nu");
m_hashNames.Add("03BE", "xi");
m_hashNames.Add("03BF", "omicron");
m_hashNames.Add("03C0", "pi");
m_hashNames.Add("03C1", "rho");
m_hashNames.Add("03C2", "sigma1");
m_hashNames.Add("03C3", "sigma");
m_hashNames.Add("03C4", "tau");
m_hashNames.Add("03C5", "upsilon");
m_hashNames.Add("03C6", "phi");
m_hashNames.Add("03C7", "chi");
m_hashNames.Add("03C8", "psi");
m_hashNames.Add("03C9", "omega");
m_hashNames.Add("03CA", "iotadieresis");
m_hashNames.Add("03CB", "upsilondieresis");
m_hashNames.Add("03CC", "omicrontonos");
m_hashNames.Add("03CD", "upsilontonos");
m_hashNames.Add("03CE", "omegatonos");
m_hashNames.Add("03D1", "theta1");
m_hashNames.Add("03D2", "Upsilon1");
m_hashNames.Add("03D5", "phi1");
m_hashNames.Add("03D6", "omega1");
m_hashNames.Add("0401", "afii10023");
m_hashNames.Add("0402", "afii10051");
m_hashNames.Add("0403", "afii10052");
m_hashNames.Add("0404", "afii10053");
m_hashNames.Add("0405", "afii10054");
m_hashNames.Add("0406", "afii10055");
m_hashNames.Add("0407", "afii10056");
m_hashNames.Add("0408", "afii10057");
m_hashNames.Add("0409", "afii10058");
m_hashNames.Add("040A", "afii10059");
m_hashNames.Add("040B", "afii10060");
m_hashNames.Add("040C", "afii10061");
m_hashNames.Add("040E", "afii10062");
m_hashNames.Add("040F", "afii10145");
m_hashNames.Add("0410", "afii10017");
m_hashNames.Add("0411", "afii10018");
m_hashNames.Add("0412", "afii10019");
m_hashNames.Add("0413", "afii10020");
m_hashNames.Add("0414", "afii10021");
m_hashNames.Add("0415", "afii10022");
m_hashNames.Add("0416", "afii10024");
m_hashNames.Add("0417", "afii10025");
m_hashNames.Add("0418", "afii10026");
m_hashNames.Add("0419", "afii10027");
m_hashNames.Add("041A", "afii10028");
m_hashNames.Add("041B", "afii10029");
m_hashNames.Add("041C", "afii10030");
m_hashNames.Add("041D", "afii10031");
m_hashNames.Add("041E", "afii10032");
m_hashNames.Add("041F", "afii10033");
m_hashNames.Add("0420", "afii10034");
m_hashNames.Add("0421", "afii10035");
m_hashNames.Add("0422", "afii10036");
m_hashNames.Add("0423", "afii10037");
m_hashNames.Add("0424", "afii10038");
m_hashNames.Add("0425", "afii10039");
m_hashNames.Add("0426", "afii10040");
m_hashNames.Add("0427", "afii10041");
m_hashNames.Add("0428", "afii10042");
m_hashNames.Add("0429", "afii10043");
m_hashNames.Add("042A", "afii10044");
m_hashNames.Add("042B", "afii10045");
m_hashNames.Add("042C", "afii10046");
m_hashNames.Add("042D", "afii10047");
m_hashNames.Add("042E", "afii10048");
m_hashNames.Add("042F", "afii10049");
m_hashNames.Add("0430", "afii10065");
m_hashNames.Add("0431", "afii10066");
m_hashNames.Add("0432", "afii10067");
m_hashNames.Add("0433", "afii10068");
m_hashNames.Add("0434", "afii10069");
m_hashNames.Add("0435", "afii10070");
m_hashNames.Add("0436", "afii10072");
m_hashNames.Add("0437", "afii10073");
m_hashNames.Add("0438", "afii10074");
m_hashNames.Add("0439", "afii10075");
m_hashNames.Add("043A", "afii10076");
m_hashNames.Add("043B", "afii10077");
m_hashNames.Add("043C", "afii10078");
m_hashNames.Add("043D", "afii10079");
m_hashNames.Add("043E", "afii10080");
m_hashNames.Add("043F", "afii10081");
m_hashNames.Add("0440", "afii10082");
m_hashNames.Add("0441", "afii10083");
m_hashNames.Add("0442", "afii10084");
m_hashNames.Add("0443", "afii10085");
m_hashNames.Add("0444", "afii10086");
m_hashNames.Add("0445", "afii10087");
m_hashNames.Add("0446", "afii10088");
m_hashNames.Add("0447", "afii10089");
m_hashNames.Add("0448", "afii10090");
m_hashNames.Add("0449", "afii10091");
m_hashNames.Add("044A", "afii10092");
m_hashNames.Add("044B", "afii10093");
m_hashNames.Add("044C", "afii10094");
m_hashNames.Add("044D", "afii10095");
m_hashNames.Add("044E", "afii10096");
m_hashNames.Add("044F", "afii10097");
m_hashNames.Add("0451", "afii10071");
m_hashNames.Add("0452", "afii10099");
m_hashNames.Add("0453", "afii10100");
m_hashNames.Add("0454", "afii10101");
m_hashNames.Add("0455", "afii10102");
m_hashNames.Add("0456", "afii10103");
m_hashNames.Add("0457", "afii10104");
m_hashNames.Add("0458", "afii10105");
m_hashNames.Add("0459", "afii10106");
m_hashNames.Add("045A", "afii10107");
m_hashNames.Add("045B", "afii10108");
m_hashNames.Add("045C", "afii10109");
m_hashNames.Add("045E", "afii10110");
m_hashNames.Add("045F", "afii10193");
m_hashNames.Add("0462", "afii10146");
m_hashNames.Add("0463", "afii10194");
m_hashNames.Add("0472", "afii10147");
m_hashNames.Add("0473", "afii10195");
m_hashNames.Add("0474", "afii10148");
m_hashNames.Add("0475", "afii10196");
m_hashNames.Add("0490", "afii10050");
m_hashNames.Add("0491", "afii10098");
m_hashNames.Add("04D9", "afii10846");
m_hashNames.Add("05B0", "afii57799");
m_hashNames.Add("05B1", "afii57801");
m_hashNames.Add("05B2", "afii57800");
m_hashNames.Add("05B3", "afii57802");
m_hashNames.Add("05B4", "afii57793");
m_hashNames.Add("05B5", "afii57794");
m_hashNames.Add("05B6", "afii57795");
m_hashNames.Add("05B7", "afii57798");
m_hashNames.Add("05B8", "afii57797");
m_hashNames.Add("05B9", "afii57806");
m_hashNames.Add("05BB", "afii57796");
m_hashNames.Add("05BC", "afii57807");
m_hashNames.Add("05BD", "afii57839");
m_hashNames.Add("05BE", "afii57645");
m_hashNames.Add("05BF", "afii57841");
m_hashNames.Add("05C0", "afii57842");
m_hashNames.Add("05C1", "afii57804");
m_hashNames.Add("05C2", "afii57803");
m_hashNames.Add("05C3", "afii57658");
m_hashNames.Add("05D0", "afii57664");
m_hashNames.Add("05D1", "afii57665");
m_hashNames.Add("05D2", "afii57666");
m_hashNames.Add("05D3", "afii57667");
m_hashNames.Add("05D4", "afii57668");
m_hashNames.Add("05D5", "afii57669");
m_hashNames.Add("05D6", "afii57670");
m_hashNames.Add("05D7", "afii57671");
m_hashNames.Add("05D8", "afii57672");
m_hashNames.Add("05D9", "afii57673");
m_hashNames.Add("05DA", "afii57674");
m_hashNames.Add("05DB", "afii57675");
m_hashNames.Add("05DC", "afii57676");
m_hashNames.Add("05DD", "afii57677");
m_hashNames.Add("05DE", "afii57678");
m_hashNames.Add("05DF", "afii57679");
m_hashNames.Add("05E0", "afii57680");
m_hashNames.Add("05E1", "afii57681");
m_hashNames.Add("05E2", "afii57682");
m_hashNames.Add("05E3", "afii57683");
m_hashNames.Add("05E4", "afii57684");
m_hashNames.Add("05E5", "afii57685");
m_hashNames.Add("05E6", "afii57686");
m_hashNames.Add("05E7", "afii57687");
m_hashNames.Add("05E8", "afii57688");
m_hashNames.Add("05E9", "afii57689");
m_hashNames.Add("05EA", "afii57690");
m_hashNames.Add("05F0", "afii57716");
m_hashNames.Add("05F1", "afii57717");
m_hashNames.Add("05F2", "afii57718");
m_hashNames.Add("060C", "afii57388");
m_hashNames.Add("061B", "afii57403");
m_hashNames.Add("061F", "afii57407");
m_hashNames.Add("0621", "afii57409");
m_hashNames.Add("0622", "afii57410");
m_hashNames.Add("0623", "afii57411");
m_hashNames.Add("0624", "afii57412");
m_hashNames.Add("0625", "afii57413");
m_hashNames.Add("0626", "afii57414");
m_hashNames.Add("0627", "afii57415");
m_hashNames.Add("0628", "afii57416");
m_hashNames.Add("0629", "afii57417");
m_hashNames.Add("062A", "afii57418");
m_hashNames.Add("062B", "afii57419");
m_hashNames.Add("062C", "afii57420");
m_hashNames.Add("062D", "afii57421");
m_hashNames.Add("062E", "afii57422");
m_hashNames.Add("062F", "afii57423");
m_hashNames.Add("0630", "afii57424");
m_hashNames.Add("0631", "afii57425");
m_hashNames.Add("0632", "afii57426");
m_hashNames.Add("0633", "afii57427");
m_hashNames.Add("0634", "afii57428");
m_hashNames.Add("0635", "afii57429");
m_hashNames.Add("0636", "afii57430");
m_hashNames.Add("0637", "afii57431");
m_hashNames.Add("0638", "afii57432");
m_hashNames.Add("0639", "afii57433");
m_hashNames.Add("063A", "afii57434");
m_hashNames.Add("0640", "afii57440");
m_hashNames.Add("0641", "afii57441");
m_hashNames.Add("0642", "afii57442");
m_hashNames.Add("0643", "afii57443");
m_hashNames.Add("0644", "afii57444");
m_hashNames.Add("0645", "afii57445");
m_hashNames.Add("0646", "afii57446");
m_hashNames.Add("0647", "afii57470");
m_hashNames.Add("0648", "afii57448");
m_hashNames.Add("0649", "afii57449");
m_hashNames.Add("064A", "afii57450");
m_hashNames.Add("064B", "afii57451");
m_hashNames.Add("064C", "afii57452");
m_hashNames.Add("064D", "afii57453");
m_hashNames.Add("064E", "afii57454");
m_hashNames.Add("064F", "afii57455");
m_hashNames.Add("0650", "afii57456");
m_hashNames.Add("0651", "afii57457");
m_hashNames.Add("0652", "afii57458");
m_hashNames.Add("0660", "afii57392");
m_hashNames.Add("0661", "afii57393");
m_hashNames.Add("0662", "afii57394");
m_hashNames.Add("0663", "afii57395");
m_hashNames.Add("0664", "afii57396");
m_hashNames.Add("0665", "afii57397");
m_hashNames.Add("0666", "afii57398");
m_hashNames.Add("0667", "afii57399");
m_hashNames.Add("0668", "afii57400");
m_hashNames.Add("0669", "afii57401");
m_hashNames.Add("066A", "afii57381");
m_hashNames.Add("066D", "afii63167");
m_hashNames.Add("0679", "afii57511");
m_hashNames.Add("067E", "afii57506");
m_hashNames.Add("0686", "afii57507");
m_hashNames.Add("0688", "afii57512");
m_hashNames.Add("0691", "afii57513");
m_hashNames.Add("0698", "afii57508");
m_hashNames.Add("06A4", "afii57505");
m_hashNames.Add("06AF", "afii57509");
m_hashNames.Add("06BA", "afii57514");
m_hashNames.Add("06D2", "afii57519");
m_hashNames.Add("06D5", "afii57534");
m_hashNames.Add("1E80", "Wgrave");
m_hashNames.Add("1E81", "wgrave");
m_hashNames.Add("1E82", "Wacute");
m_hashNames.Add("1E83", "wacute");
m_hashNames.Add("1E84", "Wdieresis");
m_hashNames.Add("1E85", "wdieresis");
m_hashNames.Add("1EF2", "Ygrave");
m_hashNames.Add("1EF3", "ygrave");
m_hashNames.Add("200C", "afii61664");
m_hashNames.Add("200D", "afii301");
m_hashNames.Add("200E", "afii299");
m_hashNames.Add("200F", "afii300");
m_hashNames.Add("2012", "figuredash");
m_hashNames.Add("2013", "endash");
m_hashNames.Add("2014", "emdash");
m_hashNames.Add("2015", "afii00208");
m_hashNames.Add("2017", "underscoredbl");
m_hashNames.Add("2018", "quoteleft");
m_hashNames.Add("2019", "quoteright");
m_hashNames.Add("201A", "quotesinglbase");
m_hashNames.Add("201B", "quotereversed");
m_hashNames.Add("201C", "quotedblleft");
m_hashNames.Add("201D", "quotedblright");
m_hashNames.Add("201E", "quotedblbase");
m_hashNames.Add("2020", "dagger");
m_hashNames.Add("2021", "daggerdbl");
m_hashNames.Add("2022", "bullet");
m_hashNames.Add("2024", "onedotenleader");
m_hashNames.Add("2025", "twodotenleader");
m_hashNames.Add("2026", "ellipsis");
m_hashNames.Add("202C", "afii61573");
m_hashNames.Add("202D", "afii61574");
m_hashNames.Add("202E", "afii61575");
m_hashNames.Add("2030", "perthousand");
m_hashNames.Add("2032", "minute");
m_hashNames.Add("2033", "second");
m_hashNames.Add("2039", "guilsinglleft");
m_hashNames.Add("203A", "guilsinglright");
m_hashNames.Add("203C", "exclamdbl");
m_hashNames.Add("2044", "fraction");
m_hashNames.Add("2070", "zerosuperior");
m_hashNames.Add("2074", "foursuperior");
m_hashNames.Add("2075", "fivesuperior");
m_hashNames.Add("2076", "sixsuperior");
m_hashNames.Add("2077", "sevensuperior");
m_hashNames.Add("2078", "eightsuperior");
m_hashNames.Add("2079", "ninesuperior");
m_hashNames.Add("207D", "parenleftsuperior");
m_hashNames.Add("207E", "parenrightsuperior");
m_hashNames.Add("207F", "nsuperior");
m_hashNames.Add("2080", "zeroinferior");
m_hashNames.Add("2081", "oneinferior");
m_hashNames.Add("2082", "twoinferior");
m_hashNames.Add("2083", "threeinferior");
m_hashNames.Add("2084", "fourinferior");
m_hashNames.Add("2085", "fiveinferior");
m_hashNames.Add("2086", "sixinferior");
m_hashNames.Add("2087", "seveninferior");
m_hashNames.Add("2088", "eightinferior");
m_hashNames.Add("2089", "nineinferior");
m_hashNames.Add("208D", "parenleftinferior");
m_hashNames.Add("208E", "parenrightinferior");
m_hashNames.Add("20A1", "colonmonetary");
m_hashNames.Add("20A3", "franc");
m_hashNames.Add("20A4", "lira");
m_hashNames.Add("20A7", "peseta");
m_hashNames.Add("20AA", "afii57636");
m_hashNames.Add("20AB", "dong");
m_hashNames.Add("20AC", "Euro");
m_hashNames.Add("2105", "afii61248");
m_hashNames.Add("2111", "Ifraktur");
m_hashNames.Add("2113", "afii61289");
m_hashNames.Add("2116", "afii61352");
m_hashNames.Add("2118", "weierstrass");
m_hashNames.Add("211C", "Rfraktur");
m_hashNames.Add("211E", "prescription");
m_hashNames.Add("2122", "trademark");
m_hashNames.Add("2126", "Omega");
m_hashNames.Add("212E", "estimated");
m_hashNames.Add("2135", "aleph");
m_hashNames.Add("2153", "onethird");
m_hashNames.Add("2154", "twothirds");
m_hashNames.Add("215B", "oneeighth");
m_hashNames.Add("215C", "threeeighths");
m_hashNames.Add("215D", "fiveeighths");
m_hashNames.Add("215E", "seveneighths");
m_hashNames.Add("2190", "arrowleft");
m_hashNames.Add("2191", "arrowup");
m_hashNames.Add("2192", "arrowright");
m_hashNames.Add("2193", "arrowdown");
m_hashNames.Add("2194", "arrowboth");
m_hashNames.Add("2195", "arrowupdn");
m_hashNames.Add("21A8", "arrowupdnbse");
m_hashNames.Add("21B5", "carriagereturn");
m_hashNames.Add("21D0", "arrowdblleft");
m_hashNames.Add("21D1", "arrowdblup");
m_hashNames.Add("21D2", "arrowdblright");
m_hashNames.Add("21D3", "arrowdbldown");
m_hashNames.Add("21D4", "arrowdblboth");
m_hashNames.Add("2200", "universal");
m_hashNames.Add("2202", "partialdiff");
m_hashNames.Add("2203", "existential");
m_hashNames.Add("2205", "emptyset");
m_hashNames.Add("2206", "Delta");
m_hashNames.Add("2207", "gradient");
m_hashNames.Add("2208", "element");
m_hashNames.Add("2209", "notelement");
m_hashNames.Add("220B", "suchthat");
m_hashNames.Add("220F", "product");
m_hashNames.Add("2211", "summation");
m_hashNames.Add("2212", "minus");
m_hashNames.Add("2215", "fraction");
m_hashNames.Add("2217", "asteriskmath");
m_hashNames.Add("2219", "periodcentered");
m_hashNames.Add("221A", "radical");
m_hashNames.Add("221D", "proportional");
m_hashNames.Add("221E", "infinity");
m_hashNames.Add("221F", "orthogonal");
m_hashNames.Add("2220", "angle");
m_hashNames.Add("2227", "logicaland");
m_hashNames.Add("2228", "logicalor");
m_hashNames.Add("2229", "intersection");
m_hashNames.Add("222A", "union");
m_hashNames.Add("222B", "integral");
m_hashNames.Add("2234", "therefore");
m_hashNames.Add("223C", "similar");
m_hashNames.Add("2245", "congruent");
m_hashNames.Add("2248", "approxequal");
m_hashNames.Add("2260", "notequal");
m_hashNames.Add("2261", "equivalence");
m_hashNames.Add("2264", "lessequal");
m_hashNames.Add("2265", "greaterequal");
m_hashNames.Add("2282", "propersubset");
m_hashNames.Add("2283", "propersuperset");
m_hashNames.Add("2284", "notsubset");
m_hashNames.Add("2286", "reflexsubset");
m_hashNames.Add("2287", "reflexsuperset");
m_hashNames.Add("2295", "circleplus");
m_hashNames.Add("2297", "circlemultiply");
m_hashNames.Add("22A5", "perpendicular");
m_hashNames.Add("22C5", "dotmath");
m_hashNames.Add("2302", "house");
m_hashNames.Add("2310", "revlogicalnot");
m_hashNames.Add("2320", "integraltp");
m_hashNames.Add("2321", "integralbt");
m_hashNames.Add("2329", "angleleft");
m_hashNames.Add("232A", "angleright");
m_hashNames.Add("2500", "SF100000");
m_hashNames.Add("2502", "SF110000");
m_hashNames.Add("250C", "SF010000");
m_hashNames.Add("2510", "SF030000");
m_hashNames.Add("2514", "SF020000");
m_hashNames.Add("2518", "SF040000");
m_hashNames.Add("251C", "SF080000");
m_hashNames.Add("2524", "SF090000");
m_hashNames.Add("252C", "SF060000");
m_hashNames.Add("2534", "SF070000");
m_hashNames.Add("253C", "SF050000");
m_hashNames.Add("2550", "SF430000");
m_hashNames.Add("2551", "SF240000");
m_hashNames.Add("2552", "SF510000");
m_hashNames.Add("2553", "SF520000");
m_hashNames.Add("2554", "SF390000");
m_hashNames.Add("2555", "SF220000");
m_hashNames.Add("2556", "SF210000");
m_hashNames.Add("2557", "SF250000");
m_hashNames.Add("2558", "SF500000");
m_hashNames.Add("2559", "SF490000");
m_hashNames.Add("255A", "SF380000");
m_hashNames.Add("255B", "SF280000");
m_hashNames.Add("255C", "SF270000");
m_hashNames.Add("255D", "SF260000");
m_hashNames.Add("255E", "SF360000");
m_hashNames.Add("255F", "SF370000");
m_hashNames.Add("2560", "SF420000");
m_hashNames.Add("2561", "SF190000");
m_hashNames.Add("2562", "SF200000");
m_hashNames.Add("2563", "SF230000");
m_hashNames.Add("2564", "SF470000");
m_hashNames.Add("2565", "SF480000");
m_hashNames.Add("2566", "SF410000");
m_hashNames.Add("2567", "SF450000");
m_hashNames.Add("2568", "SF460000");
m_hashNames.Add("2569", "SF400000");
m_hashNames.Add("256A", "SF540000");
m_hashNames.Add("256B", "SF530000");
m_hashNames.Add("256C", "SF440000");
m_hashNames.Add("2580", "upblock");
m_hashNames.Add("2584", "dnblock");
m_hashNames.Add("2588", "block");
m_hashNames.Add("258C", "lfblock");
m_hashNames.Add("2590", "rtblock");
m_hashNames.Add("2591", "ltshade");
m_hashNames.Add("2592", "shade");
m_hashNames.Add("2593", "dkshade");
m_hashNames.Add("25A0", "filledbox");
m_hashNames.Add("25A1", "H22073");
m_hashNames.Add("25AA", "H18543");
m_hashNames.Add("25AB", "H18551");
m_hashNames.Add("25AC", "filledrect");
m_hashNames.Add("25B2", "triagup");
m_hashNames.Add("25BA", "triagrt");
m_hashNames.Add("25BC", "triagdn");
m_hashNames.Add("25C4", "triaglf");
m_hashNames.Add("25CA", "lozenge");
m_hashNames.Add("25CB", "circle");
m_hashNames.Add("25CF", "H18533");
m_hashNames.Add("25D8", "invbullet");
m_hashNames.Add("25D9", "invcircle");
m_hashNames.Add("25E6", "openbullet");
m_hashNames.Add("263A", "smileface");
m_hashNames.Add("263B", "invsmileface");
m_hashNames.Add("263C", "sun");
m_hashNames.Add("2640", "female");
m_hashNames.Add("2642", "male");
m_hashNames.Add("2660", "spade");
m_hashNames.Add("2663", "club");
m_hashNames.Add("2665", "heart");
m_hashNames.Add("2666", "diamond");
m_hashNames.Add("266A", "musicalnote");
m_hashNames.Add("266B", "musicalnotedbl");
m_hashNames.Add("F6BE", "dotlessj");
m_hashNames.Add("F6BF", "LL");
m_hashNames.Add("F6C0", "ll");
m_hashNames.Add("F6C1", "Scedilla");
m_hashNames.Add("F6C2", "scedilla");
m_hashNames.Add("F6C3", "commaaccent");
m_hashNames.Add("F6C4", "afii10063");
m_hashNames.Add("F6C5", "afii10064");
m_hashNames.Add("F6C6", "afii10192");
m_hashNames.Add("F6C7", "afii10831");
m_hashNames.Add("F6C8", "afii10832");
m_hashNames.Add("F6C9", "Acute");
m_hashNames.Add("F6CA", "Caron");
m_hashNames.Add("F6CB", "Dieresis");
m_hashNames.Add("F6CC", "DieresisAcute");
m_hashNames.Add("F6CD", "DieresisGrave");
m_hashNames.Add("F6CE", "Grave");
m_hashNames.Add("F6CF", "Hungarumlaut");
m_hashNames.Add("F6D0", "Macron");
m_hashNames.Add("F6D1", "cyrBreve");
m_hashNames.Add("F6D2", "cyrFlex");
m_hashNames.Add("F6D3", "dblGrave");
m_hashNames.Add("F6D4", "cyrbreve");
m_hashNames.Add("F6D5", "cyrflex");
m_hashNames.Add("F6D6", "dblgrave");
m_hashNames.Add("F6D7", "dieresisacute");
m_hashNames.Add("F6D8", "dieresisgrave");
m_hashNames.Add("F6D9", "copyrightserif");
m_hashNames.Add("F6DA", "registerserif");
m_hashNames.Add("F6DB", "trademarkserif");
m_hashNames.Add("F6DC", "onefitted");
m_hashNames.Add("F6DD", "rupiah");
m_hashNames.Add("F6DE", "threequartersemdash");
m_hashNames.Add("F6DF", "centinferior");
m_hashNames.Add("F6E0", "centsuperior");
m_hashNames.Add("F6E1", "commainferior");
m_hashNames.Add("F6E2", "commasuperior");
m_hashNames.Add("F6E3", "dollarinferior");
m_hashNames.Add("F6E4", "dollarsuperior");
m_hashNames.Add("F6E5", "hypheninferior");
m_hashNames.Add("F6E6", "hyphensuperior");
m_hashNames.Add("F6E7", "periodinferior");
m_hashNames.Add("F6E8", "periodsuperior");
m_hashNames.Add("F6E9", "asuperior");
m_hashNames.Add("F6EA", "bsuperior");
m_hashNames.Add("F6EB", "dsuperior");
m_hashNames.Add("F6EC", "esuperior");
m_hashNames.Add("F6ED", "isuperior");
m_hashNames.Add("F6EE", "lsuperior");
m_hashNames.Add("F6EF", "msuperior");
m_hashNames.Add("F6F0", "osuperior");
m_hashNames.Add("F6F1", "rsuperior");
m_hashNames.Add("F6F2", "ssuperior");
m_hashNames.Add("F6F3", "tsuperior");
m_hashNames.Add("F6F4", "Brevesmall");
m_hashNames.Add("F6F5", "Caronsmall");
m_hashNames.Add("F6F6", "Circumflexsmall");
m_hashNames.Add("F6F7", "Dotaccentsmall");
m_hashNames.Add("F6F8", "Hungarumlautsmall");
m_hashNames.Add("F6F9", "Lslashsmall");
m_hashNames.Add("F6FA", "OEsmall");
m_hashNames.Add("F6FB", "Ogoneksmall");
m_hashNames.Add("F6FC", "Ringsmall");
m_hashNames.Add("F6FD", "Scaronsmall");
m_hashNames.Add("F6FE", "Tildesmall");
m_hashNames.Add("F6FF", "Zcaronsmall");
m_hashNames.Add("F721", "exclamsmall");
m_hashNames.Add("F724", "dollaroldstyle");
m_hashNames.Add("F726", "ampersandsmall");
m_hashNames.Add("F730", "zerooldstyle");
m_hashNames.Add("F731", "oneoldstyle");
m_hashNames.Add("F732", "twooldstyle");
m_hashNames.Add("F733", "threeoldstyle");
m_hashNames.Add("F734", "fouroldstyle");
m_hashNames.Add("F735", "fiveoldstyle");
m_hashNames.Add("F736", "sixoldstyle");
m_hashNames.Add("F737", "sevenoldstyle");
m_hashNames.Add("F738", "eightoldstyle");
m_hashNames.Add("F739", "nineoldstyle");
m_hashNames.Add("F73F", "questionsmall");
m_hashNames.Add("F760", "Gravesmall");
m_hashNames.Add("F761", "Asmall");
m_hashNames.Add("F762", "Bsmall");
m_hashNames.Add("F763", "Csmall");
m_hashNames.Add("F764", "Dsmall");
m_hashNames.Add("F765", "Esmall");
m_hashNames.Add("F766", "Fsmall");
m_hashNames.Add("F767", "Gsmall");
m_hashNames.Add("F768", "Hsmall");
m_hashNames.Add("F769", "Ismall");
m_hashNames.Add("F76A", "Jsmall");
m_hashNames.Add("F76B", "Ksmall");
m_hashNames.Add("F76C", "Lsmall");
m_hashNames.Add("F76D", "Msmall");
m_hashNames.Add("F76E", "Nsmall");
m_hashNames.Add("F76F", "Osmall");
m_hashNames.Add("F770", "Psmall");
m_hashNames.Add("F771", "Qsmall");
m_hashNames.Add("F772", "Rsmall");
m_hashNames.Add("F773", "Ssmall");
m_hashNames.Add("F774", "Tsmall");
m_hashNames.Add("F775", "Usmall");
m_hashNames.Add("F776", "Vsmall");
m_hashNames.Add("F777", "Wsmall");
m_hashNames.Add("F778", "Xsmall");
m_hashNames.Add("F779", "Ysmall");
m_hashNames.Add("F77A", "Zsmall");
m_hashNames.Add("F7A1", "exclamdownsmall");
m_hashNames.Add("F7A2", "centoldstyle");
m_hashNames.Add("F7A8", "Dieresissmall");
m_hashNames.Add("F7AF", "Macronsmall");
m_hashNames.Add("F7B4", "Acutesmall");
m_hashNames.Add("F7B8", "Cedillasmall");
m_hashNames.Add("F7BF", "questiondownsmall");
m_hashNames.Add("F7E0", "Agravesmall");
m_hashNames.Add("F7E1", "Aacutesmall");
m_hashNames.Add("F7E2", "Acircumflexsmall");
m_hashNames.Add("F7E3", "Atildesmall");
m_hashNames.Add("F7E4", "Adieresissmall");
m_hashNames.Add("F7E5", "Aringsmall");
m_hashNames.Add("F7E6", "AEsmall");
m_hashNames.Add("F7E7", "Ccedillasmall");
m_hashNames.Add("F7E8", "Egravesmall");
m_hashNames.Add("F7E9", "Eacutesmall");
m_hashNames.Add("F7EA", "Ecircumflexsmall");
m_hashNames.Add("F7EB", "Edieresissmall");
m_hashNames.Add("F7EC", "Igravesmall");
m_hashNames.Add("F7ED", "Iacutesmall");
m_hashNames.Add("F7EE", "Icircumflexsmall");
m_hashNames.Add("F7EF", "Idieresissmall");
m_hashNames.Add("F7F0", "Ethsmall");
m_hashNames.Add("F7F1", "Ntildesmall");
m_hashNames.Add("F7F2", "Ogravesmall");
m_hashNames.Add("F7F3", "Oacutesmall");
m_hashNames.Add("F7F4", "Ocircumflexsmall");
m_hashNames.Add("F7F5", "Otildesmall");
m_hashNames.Add("F7F6", "Odieresissmall");
m_hashNames.Add("F7F8", "Oslashsmall");
m_hashNames.Add("F7F9", "Ugravesmall");
m_hashNames.Add("F7FA", "Uacutesmall");
m_hashNames.Add("F7FB", "Ucircumflexsmall");
m_hashNames.Add("F7FC", "Udieresissmall");
m_hashNames.Add("F7FD", "Yacutesmall");
m_hashNames.Add("F7FE", "Thornsmall");
m_hashNames.Add("F7FF", "Ydieresissmall");
m_hashNames.Add("F8E5", "radicalex");
m_hashNames.Add("F8E6", "arrowvertex");
m_hashNames.Add("F8E7", "arrowhorizex");
m_hashNames.Add("F8E8", "registersans");
m_hashNames.Add("F8E9", "copyrightsans");
m_hashNames.Add("F8EA", "trademarksans");
m_hashNames.Add("F8EB", "parenlefttp");
m_hashNames.Add("F8EC", "parenleftex");
m_hashNames.Add("F8ED", "parenleftbt");
m_hashNames.Add("F8EE", "bracketlefttp");
m_hashNames.Add("F8EF", "bracketleftex");
m_hashNames.Add("F8F0", "bracketleftbt");
m_hashNames.Add("F8F1", "bracelefttp");
m_hashNames.Add("F8F2", "braceleftmid");
m_hashNames.Add("F8F3", "braceleftbt");
m_hashNames.Add("F8F4", "braceex");
m_hashNames.Add("F8F5", "integralex");
m_hashNames.Add("F8F6", "parenrighttp");
m_hashNames.Add("F8F7", "parenrightex");
m_hashNames.Add("F8F8", "parenrightbt");
m_hashNames.Add("F8F9", "bracketrighttp");
m_hashNames.Add("F8FA", "bracketrightex");
m_hashNames.Add("F8FB", "bracketrightbt");
m_hashNames.Add("F8FC", "bracerighttp");
m_hashNames.Add("F8FD", "bracerightmid");
m_hashNames.Add("F8FE", "bracerightbt");
m_hashNames.Add("FB00", "ff");
m_hashNames.Add("FB01", "fi");
m_hashNames.Add("FB02", "fl");
m_hashNames.Add("FB03", "ffi");
m_hashNames.Add("FB04", "ffl");
m_hashNames.Add("FB1F", "afii57705");
m_hashNames.Add("FB2A", "afii57694");
m_hashNames.Add("FB2B", "afii57695");
m_hashNames.Add("FB35", "afii57723");
m_hashNames.Add("FB4B", "afii57700");
}
Hashtable m_hashNames;
}
}
| |
using UnityEngine;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace NG.AssertDebug
{
public enum DebugWarningLevel
{ all, warning, error, none }
public enum FailureReaction
{ pause, kill, none }
/// <summary>
/// Options:
/// <para />all, assertOnly, and debugOnly will always write to file after each message.
/// <para />allFailureOnly, assertFailureOnly, and debugErrorOnly will only write to
/// <para />file on failure and stores messages in a list before writing.
/// <para />Log file is tab seperated, so don't use tabs in your log messages!
/// </summary>
public enum LogToFileCondition
{ all, assertOnly, debugOnly, allFailureOnly, assertFailureOnly, debugErrorOnly, none }
public enum DebugConsoleDisplay
{ never, editorOnly, buildOnly, both}
[XmlRoot("AssertDebugConfig")]
public class AssertDebugConfig
{
private static AssertDebugConfig m_instance;
public static AssertDebugConfig instance
{
get
{
if (m_instance == null)
{
m_instance = new AssertDebugConfig();
LoadSettings();
}
return m_instance;
}
private set { m_instance = value; }
}
// Disables all logging
public bool masterDisable = false;
// Set what debug messages to log
public DebugWarningLevel debugLogWarningLevel = DebugWarningLevel.all;
// Disable assertion messages
public bool assertDisable = false;
// Run in debug build only
public bool runInDebugBuildOnly = true;
// What to do when we encounter a failure
public FailureReaction assertFailureReaction = FailureReaction.pause;
public FailureReaction debugErrorReaction = FailureReaction.pause;
public bool shouldAssertDoFailure = true;
public bool shouldLogErrorDoFailure = true;
// When to log to file - see enum definition for details
public LogToFileCondition logToFileCondition = LogToFileCondition.all;
public string logFileName = "debug";
public string logFileExt = ".txt";
public string debugFileHeader = "Time\tError Type\tMessage\tStack Trace";
// Set to automatically take screenshot on failure
public bool takeScreenShot = false;
public string screenShotFileName = "error_screen";
// Set the key that brings up the in-game debug console
public KeyCode debugConsoleKey = KeyCode.BackQuote;
// Set whether to show NGDebugConsole on error in editor, builds, or both.
public DebugConsoleDisplay debugConsoleDisplay = DebugConsoleDisplay.both;
public bool ShowGuiLogConsoleOnError()
{
#if !UNITY_EDITOR
if (debugConsoleDisplay == DebugConsoleDisplay.editorOnly ||
debugConsoleDisplay == DebugConsoleDisplay.both)
return true;
#else
if (debugConsoleDisplay == DebugConsoleDisplay.buildOnly ||
debugConsoleDisplay == DebugConsoleDisplay.both)
return true;
#endif
return false;
}
/// <summary>
/// Returns the log file path.
/// When running from the editor this will be the "Unity project folder"/logs.
/// When running a standalone build this will be MyDocuments/CompanyName/ApplicationName/logs
/// </summary>
/// <returns></returns>
public string GetLogFilePath()
{
string path = Application.dataPath;
#if !UNITY_EDITOR
path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + "/" + Application.companyName + "/" + Application.productName + "/logs";
#else
DirectoryInfo parentDir = Directory.GetParent(Application.dataPath);
path = parentDir.FullName + "/logs";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
#endif
return path;
}
public string GetDebugFileName()
{
return GetLogFilePath() + "/" + logFileName + "_" + AssertDateStamp.FileDate() + logFileExt;
}
public string GetScreenShotFileName()
{
int extNum = 0;
while (File.Exists(ScreenShotFileName(extNum)))
extNum++;
return ScreenShotFileName(extNum);
}
private string ScreenShotFileName(int extNum)
{
return GetLogFilePath() + "/" + screenShotFileName + "_" + AssertDateStamp.FileDate() + extNum.ToString() + ".png";
}
public const string personalSettingsXmlFile = "personal_debug_settings.xml";
[XmlIgnore]
public bool personalSettingsLoaded = false;
public static string Save()
{
string pathFile = instance.GetLogFilePath() + "/" + personalSettingsXmlFile;
Save(pathFile);
return pathFile;
}
private static void Save(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return;
var serializer = new XmlSerializer(typeof(AssertDebugConfig));
using (var stream = new FileStream(fileName, FileMode.Create))
serializer.Serialize(stream, instance);
}
//Don't reference instance here, use m_instance otherwise we'll possibly create an inf loop
public static void LoadSettings()
{
if (!m_instance.personalSettingsLoaded)
{
string pathFile = instance.GetLogFilePath() + "/" + personalSettingsXmlFile;
if (File.Exists(pathFile))
{
var serializer = new XmlSerializer(typeof(AssertDebugConfig));
using (var stream = new FileStream(pathFile, FileMode.Open))
{
m_instance = serializer.Deserialize(stream) as AssertDebugConfig;
m_instance.personalSettingsLoaded = true;
}
}
}
}
public static void ReloadSettings()
{
m_instance.personalSettingsLoaded = false;
LoadSettings();
}
public static bool RestoreDefaults()
{
string pathFile = instance.GetLogFilePath() + "/" + personalSettingsXmlFile;
if (File.Exists(pathFile))
{
File.Delete(pathFile);
m_instance = null;
return true;
}
return false;
}
}
public class AssertDateStamp
{
public static string FileDate()
{
System.DateTime time = System.DateTime.Now;
string format = "yyyyMMdd-HH";
return time.ToString(format);
}
public static string LogEntryTime()
{
System.DateTime time = System.DateTime.Now;
string format = "HH:mm:ss.fff";
return time.ToString(format);
}
}
}
| |
namespace NServiceBus.Persistence.AzureTable
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Microsoft.Azure.Cosmos.Table;
using System.Collections.Concurrent;
using System.Linq.Expressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
static class DictionaryTableEntityExtensionsNew
{
public static TEntity ToSagaDataNew<TEntity>(DictionaryTableEntity entity)
{
return (TEntity)ToSagaData(typeof(TEntity), entity);
}
private static object ToSagaData(Type sagaDataType, DictionaryTableEntity entity)
{
var toCreate = Activator.CreateInstance(sagaDataType);
foreach (var accessor in GetPropertyAccessors(sagaDataType))
{
if (!entity.ContainsKey(accessor.Name))
{
continue;
}
var value = entity[accessor.Name];
var type = accessor.PropertyType;
if (type == typeof(byte[]))
{
accessor.Setter(toCreate, value.BinaryValue);
}
else if (TrySetNullable(value, toCreate, accessor))
{
}
else if (type == typeof(string))
{
accessor.Setter(toCreate, value.StringValue);
}
else
{
if (value.PropertyType == EdmType.String)
{
// possibly serialized JSON.NET value
try
{
using (var stringReader = new StringReader(value.StringValue))
{
var deserialized = jsonSerializer.Deserialize(stringReader, type);
accessor.Setter(toCreate, deserialized);
}
}
catch (Exception)
{
throw new NotSupportedException($"The property type '{type.Name}' is not supported in Azure Table Storage and it cannot be deserialized with JSON.NET.");
}
}
else
{
throw new NotSupportedException($"The property type '{type.Name}' is not supported in Azure Table Storage");
}
}
}
return toCreate;
}
public static DictionaryTableEntity ToDictionaryTableEntity(object sagaData, DictionaryTableEntity toPersist)
{
foreach (var accessor in GetPropertyAccessors(sagaData.GetType()))
{
var name = accessor.Name;
var type = accessor.PropertyType;
var value = accessor.Getter(sagaData);
if (type == typeof(byte[]))
{
toPersist[name] = new EntityProperty((byte[])value);
}
else if (TryGetNullable(type, value, out bool? @bool))
{
toPersist[name] = new EntityProperty(@bool);
}
else if (TryGetNullable(type, value, out DateTime? dateTime))
{
if (!dateTime.HasValue || dateTime.Value < StorageTableMinDateTime)
{
throw new Exception($"Saga data of type '{sagaData.GetType().FullName}' with DateTime property '{name}' has an invalid value '{dateTime}'. Value cannot be null and must be equal to or greater than '{StorageTableMinDateTime}'.");
}
toPersist[name] = new EntityProperty(dateTime);
}
else if (TryGetNullable(type, value, out Guid? guid))
{
toPersist[name] = new EntityProperty(guid);
}
else if (TryGetNullable(type, value, out int? @int))
{
toPersist[name] = new EntityProperty(@int);
}
else if (TryGetNullable(type, value, out long? @long))
{
toPersist[name] = new EntityProperty(@long);
}
else if (TryGetNullable(type, value, out double? @double))
{
toPersist[name] = new EntityProperty(@double);
}
else if (type == typeof(string))
{
toPersist[name] = new EntityProperty((string)value);
}
else
{
using (var sw = new StringWriter())
{
try
{
jsonSerializerWithNonAbstractDefaultContractResolver.Serialize(sw, value, type);
}
catch (Exception)
{
throw new NotSupportedException($"The property type '{type.Name}' is not supported in Azure Table Storage and it cannot be serialized with JSON.NET.");
}
toPersist[name] = new EntityProperty(sw.ToString());
}
}
}
return toPersist;
}
private static IReadOnlyCollection<PropertyAccessor> GetPropertyAccessors(Type sagaDataType)
{
var accessors = propertyAccessorCache.GetOrAdd(sagaDataType, dataType =>
{
var setters = new List<PropertyAccessor>();
var entityProperties = dataType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var propertyInfo in entityProperties)
{
setters.Add(new PropertyAccessor(propertyInfo));
}
return setters;
});
return accessors;
}
static bool TryGetNullable<TPrimitive>(Type type, object value, out TPrimitive? nullable)
where TPrimitive : struct
{
if (type == typeof(TPrimitive))
{
nullable = (TPrimitive)value;
return true;
}
if (type == typeof(TPrimitive?))
{
nullable = (TPrimitive?)value;
return true;
}
nullable = null;
return false;
}
static bool TrySetNullable(EntityProperty value, object toCreate, PropertyAccessor setter)
{
return
TrySetNullable<bool>(value, toCreate, setter) ||
TrySetNullable<DateTime>(value, toCreate, setter) ||
TrySetNullable<Guid>(value, toCreate, setter) ||
TrySetNullable<int>(value, toCreate, setter) ||
TrySetNullable<double>(value, toCreate, setter) ||
TrySetNullable<long>(value, toCreate, setter);
}
static bool TrySetNullable<TPrimitive>(EntityProperty property, object entity, PropertyAccessor setter)
where TPrimitive : struct
{
if (setter.PropertyType == typeof(TPrimitive))
{
var value = (TPrimitive?)property.PropertyAsObject;
var nonNullableValue = value ?? default;
setter.Setter(entity, nonNullableValue);
return true;
}
if (setter.PropertyType == typeof(TPrimitive?))
{
var value = (TPrimitive?)property.PropertyAsObject;
setter.Setter(entity, value);
return true;
}
return false;
}
public static TableQuery<DictionaryTableEntity> BuildWherePropertyQuery(Type type, string property, object value)
{
TableQuery<DictionaryTableEntity> query;
var propertyInfo = type.GetProperty(property);
if (propertyInfo == null)
{
return null;
}
if (propertyInfo.PropertyType == typeof(byte[]))
{
query = new TableQuery<DictionaryTableEntity>().Where(TableQuery.GenerateFilterConditionForBinary(property, QueryComparisons.Equal, (byte[])value));
}
else if (propertyInfo.PropertyType == typeof(bool))
{
query = new TableQuery<DictionaryTableEntity>().Where(TableQuery.GenerateFilterConditionForBool(property, QueryComparisons.Equal, (bool)value));
}
else if (propertyInfo.PropertyType == typeof(DateTime))
{
query = new TableQuery<DictionaryTableEntity>().Where(TableQuery.GenerateFilterConditionForDate(property, QueryComparisons.Equal, (DateTime)value));
}
else if (propertyInfo.PropertyType == typeof(Guid))
{
query = new TableQuery<DictionaryTableEntity>().Where(TableQuery.GenerateFilterConditionForGuid(property, QueryComparisons.Equal, (Guid)value));
}
else if (propertyInfo.PropertyType == typeof(int))
{
query = new TableQuery<DictionaryTableEntity>().Where(TableQuery.GenerateFilterConditionForInt(property, QueryComparisons.Equal, (int)value));
}
else if (propertyInfo.PropertyType == typeof(long))
{
query = new TableQuery<DictionaryTableEntity>().Where(TableQuery.GenerateFilterConditionForLong(property, QueryComparisons.Equal, (long)value));
}
else if (propertyInfo.PropertyType == typeof(double))
{
query = new TableQuery<DictionaryTableEntity>().Where(TableQuery.GenerateFilterConditionForDouble(property, QueryComparisons.Equal, (double)value));
}
else if (propertyInfo.PropertyType == typeof(string))
{
query = new TableQuery<DictionaryTableEntity>().Where(TableQuery.GenerateFilterCondition(property, QueryComparisons.Equal, (string)value));
}
else
{
throw new NotSupportedException($"The property type '{propertyInfo.PropertyType.Name}' is not supported in Azure Table Storage");
}
return query;
}
static readonly ConcurrentDictionary<Type, IReadOnlyCollection<PropertyAccessor>> propertyAccessorCache = new ConcurrentDictionary<Type, IReadOnlyCollection<PropertyAccessor>>();
static readonly JsonSerializer jsonSerializer = JsonSerializer.Create();
static readonly JsonSerializer jsonSerializerWithNonAbstractDefaultContractResolver = new JsonSerializer
{
ContractResolver = new NonAbstractDefaultContractResolver(),
};
private static readonly DateTime StorageTableMinDateTime = new DateTime(1601, 1, 1);
sealed class PropertyAccessor
{
public PropertyAccessor(PropertyInfo propertyInfo)
{
Setter = GenerateSetter(propertyInfo);
Getter = GenerateGetter(propertyInfo);
Name = propertyInfo.Name;
PropertyType = propertyInfo.PropertyType;
}
private static Func<object, object> GenerateGetter(PropertyInfo propertyInfo)
{
var instance = Expression.Parameter(typeof(object), "instance");
var instanceCast = !propertyInfo.DeclaringType.IsValueType
? Expression.TypeAs(instance, propertyInfo.DeclaringType)
: Expression.Convert(instance, propertyInfo.DeclaringType);
var getter = Expression
.Lambda<Func<object, object>>(
Expression.TypeAs(Expression.Call(instanceCast, propertyInfo.GetGetMethod()), typeof(object)), instance)
.Compile();
return getter;
}
private static Action<object, object> GenerateSetter(PropertyInfo propertyInfo)
{
var instance = Expression.Parameter(typeof(object), "instance");
var value = Expression.Parameter(typeof(object), "value");
// value as T is slightly faster than (T)value, so if it's not a value type, use that
var instanceCast = !propertyInfo.DeclaringType.IsValueType
? Expression.TypeAs(instance, propertyInfo.DeclaringType)
: Expression.Convert(instance, propertyInfo.DeclaringType);
var valueCast = !propertyInfo.PropertyType.IsValueType
? Expression.TypeAs(value, propertyInfo.PropertyType)
: Expression.Convert(value, propertyInfo.PropertyType);
var setter = Expression
.Lambda<Action<object, object>>(Expression.Call(instanceCast, propertyInfo.GetSetMethod(), valueCast), instance,
value).Compile();
return setter;
}
public Action<object, object> Setter { get; }
public Func<object, object> Getter { get; }
public string Name { get; }
public Type PropertyType { get; }
}
class NonAbstractDefaultContractResolver : DefaultContractResolver
{
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
if (objectType.IsAbstract || objectType.IsInterface)
{
throw new ArgumentException("Cannot serialize an abstract class/interface", nameof(objectType));
}
return base.CreateObjectContract(objectType);
}
}
}
}
| |
using ExtendedXmlSerializer.Core.Sources;
using LightInject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ExtendedXmlSerializer.ExtensionModel
{
class Services : IServices
{
readonly IServiceContainer _container;
readonly IServiceRegistry _registry;
public Services(IServiceContainer container) : this(container, container) {}
public Services(IServiceContainer container, IServiceRegistry registry)
{
_container = container;
_registry = registry;
}
public IEnumerable<TypeInfo> AvailableServices
=> _registry.AvailableServices.Select(x => x.ServiceType.GetTypeInfo());
public IServiceRepository Register(Type serviceType, Type implementingType)
=> new Services(_container, _registry.Register(serviceType, implementingType));
public IServiceRepository Register(Type serviceType, Type implementingType, string serviceName)
=> new Services(_container, _registry.Register(serviceType, implementingType, serviceName));
public IServiceRepository Register<TService, TImplementation>() where TImplementation : TService
=> new Services(_container, _registry.Register<TService, TImplementation>(new PerContainerLifetime()));
public IServiceRepository Register<TService, TImplementation>(string serviceName)
where TImplementation : TService
=> new Services(_container, _registry.Register<TService, TImplementation>(serviceName));
public IServiceRepository Register<TService>()
=> new Services(_container, _registry.Register<TService>(new PerContainerLifetime()));
public IServiceRepository RegisterInstance<TService>(TService instance)
=> new Services(_container, _registry.RegisterInstance(instance));
public IServiceRepository RegisterInstance<TService>(TService instance, string serviceName)
=> new Services(_container, _registry.RegisterInstance(instance, serviceName));
public IServiceRepository RegisterInstance(Type serviceType, object instance)
=> new Services(_container, _registry.RegisterInstance(serviceType, instance));
public IServiceRepository RegisterInstance(Type serviceType, object instance, string serviceName)
=> new Services(_container, _registry.RegisterInstance(serviceType, instance, serviceName));
public IServiceRepository Register(Type serviceType)
=> new Services(_container, _registry.Register(serviceType));
public IServiceRepository Register<TService>(Func<IServiceProvider, TService> factory)
=> new Services(_container,
_registry.Register(new Registration<TService>(factory).Get, new PerContainerLifetime()));
sealed class Providers : ReferenceCache<IServiceFactory, IServiceProvider>
{
public static Providers Default { get; } = new Providers();
Providers() : base(x => new Provider(x)) {}
class Provider : IServiceProvider
{
readonly IServiceFactory _factory;
public Provider(IServiceFactory factory)
{
_factory = factory;
}
public object GetService(Type serviceType) => _factory.Create(serviceType);
public object GetInstance(Type serviceType) => _factory.GetInstance(serviceType);
public object GetInstance(Type serviceType, object[] arguments)
=> _factory.GetInstance(serviceType, arguments);
public object GetInstance(Type serviceType, string serviceName, object[] arguments)
=> _factory.GetInstance(serviceType, serviceName, arguments);
public object GetInstance(Type serviceType, string serviceName)
=> _factory.GetInstance(serviceType, serviceName);
public object TryGetInstance(Type serviceType) => _factory.TryGetInstance(serviceType);
public object TryGetInstance(Type serviceType, string serviceName)
=> _factory.TryGetInstance(serviceType, serviceName);
public IEnumerable<object> GetAllInstances(Type serviceType) => _factory.GetAllInstances(serviceType);
public object Create(Type serviceType) => _factory.Create(serviceType);
}
}
public IServiceRepository Register<T, TService>(Func<IServiceProvider, T, TService> factory)
=> new Services(_container, _registry.Register<T, TService>(new Registration<T, TService>(factory).Get));
public IServiceRepository Register<T, TService>(Func<IServiceProvider, T, TService> factory, string serviceName)
=> new Services(_container,
_registry.Register<T, TService>(new Registration<T, TService>(factory).Get, serviceName));
public IServiceRepository Register<T1, T2, TService>(Func<IServiceProvider, T1, T2, TService> factory)
=> new Services(_container,
_registry.Register<T1, T2, TService>(new Registration<T1, T2, TService>(factory).Get));
public IServiceRepository Register<T1, T2, TService>(Func<IServiceProvider, T1, T2, TService> factory,
string serviceName)
=>
new Services(_container,
_registry.Register<T1, T2, TService>(new Registration<T1, T2, TService>(factory).Get,
serviceName));
public IServiceRepository Register<T1, T2, T3, TService>(Func<IServiceProvider, T1, T2, T3, TService> factory)
=>
new Services(_container,
_registry.Register<T1, T2, T3, TService>(new Registration<T1, T2, T3, TService>(factory)
.Get));
public IServiceRepository Register<T1, T2, T3, TService>(Func<IServiceProvider, T1, T2, T3, TService> factory,
string serviceName)
=>
new Services(_container,
_registry
.Register<T1, T2, T3, TService>(new Registration<T1, T2, T3, TService>(factory).Get,
serviceName));
public IServiceRepository Register<T1, T2, T3, T4, TService>(
Func<IServiceProvider, T1, T2, T3, T4, TService> factory)
=>
new Services(_container,
_registry
.Register<T1, T2, T3, T4, TService>(new Registration<T1, T2, T3, T4, TService>(factory)
.Get));
public IServiceRepository Register<T1, T2, T3, T4, TService>(
Func<IServiceProvider, T1, T2, T3, T4, TService> factory,
string serviceName)
=> new Services(_container,
_registry
.Register<T1, T2, T3, T4, TService
>(new Registration<T1, T2, T3, T4, TService>(factory).Get,
serviceName));
public IServiceRepository Register<TService>(Func<IServiceProvider, TService> factory, string serviceName)
=> new Services(_container, _registry.Register(new Registration<TService>(factory).Get, serviceName));
public IServiceRepository RegisterFallback(Func<Type, bool> predicate, Func<Type, object> factory)
=>
new Services(_container,
_registry.RegisterFallback((type, s) => predicate(type),
request => factory(request.ServiceType)));
public IServiceRepository RegisterConstructorDependency<TDependency>(
Func<IServiceProvider, ParameterInfo, TDependency> factory)
=> new Services(_container,
_registry.RegisterConstructorDependency(new Dependency<TDependency>(factory).Get));
public IServiceRepository RegisterConstructorDependency<TDependency>(
Func<IServiceProvider, ParameterInfo, object[], TDependency> factory)
=> new Services(_container,
_registry.RegisterConstructorDependency(new Arguments<TDependency>(factory).Get));
public IServiceRepository Decorate(Type serviceType, Type decoratorType)
=> new Services(_container, _registry.Decorate(serviceType, decoratorType));
public IServiceRepository Decorate<TService, TDecorator>() where TDecorator : TService
=> new Services(_container, _registry.Decorate<TService, TDecorator>());
public IServiceRepository Decorate<TService>(Func<IServiceProvider, TService, TService> factory)
=> new Services(_container, _registry.Decorate<TService>(new Decoration<TService>(factory).Get));
public object Create(Type serviceType) => _container.Create(serviceType);
public object GetService(Type serviceType) => _container.GetInstance(serviceType);
public object GetInstance(Type serviceType) => _container.GetInstance(serviceType);
public object GetInstance(Type serviceType, object[] arguments)
=> _container.GetInstance(serviceType, arguments);
public object GetInstance(Type serviceType, string serviceName, object[] arguments)
=> _container.GetInstance(serviceType, serviceName, arguments);
public object GetInstance(Type serviceType, string serviceName)
=> _container.GetInstance(serviceType, serviceName);
public object TryGetInstance(Type serviceType) => _container.TryGetInstance(serviceType);
public object TryGetInstance(Type serviceType, string serviceName)
=> _container.TryGetInstance(serviceType, serviceName);
public IEnumerable<object> GetAllInstances(Type serviceType) => _container.GetAllInstances(serviceType);
public void Dispose() => _container.Dispose();
class Arguments<T>
{
readonly Func<IServiceProvider, ParameterInfo, object[], T> _factory;
public Arguments(Func<IServiceProvider, ParameterInfo, object[], T> factory)
{
_factory = factory;
}
public T Get(IServiceFactory factory, ParameterInfo parameter, object[] arguments)
=> _factory(Providers.Default.Get(factory), parameter, arguments);
}
class Decoration<T>
{
readonly Func<IServiceProvider, T, T> _factory;
public Decoration(Func<IServiceProvider, T, T> factory)
{
_factory = factory;
}
public T Get(IServiceFactory factory, T parameter) => _factory(Providers.Default.Get(factory), parameter);
}
class Dependency<T>
{
readonly Func<IServiceProvider, ParameterInfo, T> _factory;
public Dependency(Func<IServiceProvider, ParameterInfo, T> factory)
{
_factory = factory;
}
public T Get(IServiceFactory factory, ParameterInfo parameter)
=> _factory(Providers.Default.Get(factory), parameter);
}
class Registration<T>
{
readonly Func<IServiceProvider, T> _factory;
public Registration(Func<IServiceProvider, T> factory)
{
_factory = factory;
}
public T Get(IServiceFactory factory) => _factory(Providers.Default.Get(factory));
}
class Registration<T, TService>
{
readonly Func<IServiceProvider, T, TService> _factory;
public Registration(Func<IServiceProvider, T, TService> factory)
{
_factory = factory;
}
public TService Get(IServiceFactory factory, T parameter)
=> _factory(Providers.Default.Get(factory), parameter);
}
class Registration<T1, T2, TService>
{
readonly Func<IServiceProvider, T1, T2, TService> _factory;
public Registration(Func<IServiceProvider, T1, T2, TService> factory)
{
_factory = factory;
}
public TService Get(IServiceFactory factory, T1 first, T2 second)
=> _factory(Providers.Default.Get(factory), first, second);
}
class Registration<T1, T2, T3, TService>
{
readonly Func<IServiceProvider, T1, T2, T3, TService> _factory;
public Registration(Func<IServiceProvider, T1, T2, T3, TService> factory)
{
_factory = factory;
}
// ReSharper disable once TooManyArguments
public TService Get(IServiceFactory factory, T1 first, T2 second, T3 third)
=> _factory(Providers.Default.Get(factory), first, second, third);
}
class Registration<T1, T2, T3, T4, TService>
{
readonly Func<IServiceProvider, T1, T2, T3, T4, TService> _factory;
public Registration(Func<IServiceProvider, T1, T2, T3, T4, TService> factory)
{
_factory = factory;
}
// ReSharper disable once TooManyArguments
public TService Get(IServiceFactory factory, T1 first, T2 second, T3 third, T4 forth)
=> _factory(Providers.Default.Get(factory), first, second, third, forth);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Principal;
using System.Diagnostics.Contracts;
namespace System.Security.AccessControl
{
public enum AccessControlType
{
Allow = 0,
Deny = 1,
}
public abstract class AuthorizationRule
{
#region Private Members
private readonly IdentityReference _identity;
private readonly int _accessMask;
private readonly bool _isInherited;
private readonly InheritanceFlags _inheritanceFlags;
private readonly PropagationFlags _propagationFlags;
#endregion
#region Constructors
internal protected AuthorizationRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags )
{
if ( identity == null )
{
throw new ArgumentNullException( nameof(identity));
}
if ( accessMask == 0 )
{
throw new ArgumentException(
SR.Argument_ArgumentZero,
nameof(accessMask));
}
if ( inheritanceFlags < InheritanceFlags.None || inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit) )
{
throw new ArgumentOutOfRangeException(
nameof(inheritanceFlags),
SR.Format( SR.Argument_InvalidEnumValue, inheritanceFlags, "InheritanceFlags" ));
}
if ( propagationFlags < PropagationFlags.None || propagationFlags > (PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly) )
{
throw new ArgumentOutOfRangeException(
nameof(propagationFlags),
SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "PropagationFlags"));
}
Contract.EndContractBlock();
if (identity.IsValidTargetType(typeof(SecurityIdentifier)) == false)
{
throw new ArgumentException(
SR.Arg_MustBeIdentityReferenceType,
nameof(identity));
}
_identity = identity;
_accessMask = accessMask;
_isInherited = isInherited;
_inheritanceFlags = inheritanceFlags;
if ( inheritanceFlags != 0 )
{
_propagationFlags = propagationFlags;
}
else
{
_propagationFlags = 0;
}
}
#endregion
#region Properties
public IdentityReference IdentityReference
{
get { return _identity; }
}
internal protected int AccessMask
{
get { return _accessMask; }
}
public bool IsInherited
{
get { return _isInherited; }
}
public InheritanceFlags InheritanceFlags
{
get { return _inheritanceFlags; }
}
public PropagationFlags PropagationFlags
{
get { return _propagationFlags; }
}
#endregion
}
public abstract class AccessRule : AuthorizationRule
{
#region Private Methods
private readonly AccessControlType _type;
#endregion
#region Constructors
protected AccessRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags )
{
if ( type != AccessControlType.Allow &&
type != AccessControlType.Deny )
{
throw new ArgumentOutOfRangeException(
nameof(type),
SR.ArgumentOutOfRange_Enum );
}
if ( inheritanceFlags < InheritanceFlags.None || inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit) )
{
throw new ArgumentOutOfRangeException(
nameof(inheritanceFlags),
SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "InheritanceFlags"));
}
if ( propagationFlags < PropagationFlags.None || propagationFlags > (PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly) )
{
throw new ArgumentOutOfRangeException(
nameof(propagationFlags),
SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "PropagationFlags"));
}
Contract.EndContractBlock();
_type = type;
}
#endregion
#region Properties
public AccessControlType AccessControlType
{
get { return _type; }
}
#endregion
}
public abstract class ObjectAccessRule: AccessRule
{
#region Private Members
private readonly Guid _objectType;
private readonly Guid _inheritedObjectType;
private readonly ObjectAceFlags _objectFlags = ObjectAceFlags.None;
#endregion
#region Constructors
protected ObjectAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AccessControlType type )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type )
{
if (( !objectType.Equals( Guid.Empty )) && (( accessMask & ObjectAce.AccessMaskWithObjectType ) != 0 ))
{
_objectType = objectType;
_objectFlags |= ObjectAceFlags.ObjectAceTypePresent;
}
else
{
_objectType = Guid.Empty;
}
if (( !inheritedObjectType.Equals( Guid.Empty )) && ((inheritanceFlags & InheritanceFlags.ContainerInherit ) != 0 ))
{
_inheritedObjectType = inheritedObjectType;
_objectFlags |= ObjectAceFlags.InheritedObjectAceTypePresent;
}
else
{
_inheritedObjectType = Guid.Empty;
}
}
#endregion
#region Properties
public Guid ObjectType
{
get { return _objectType; }
}
public Guid InheritedObjectType
{
get { return _inheritedObjectType; }
}
public ObjectAceFlags ObjectFlags
{
get { return _objectFlags; }
}
#endregion
}
public abstract class AuditRule : AuthorizationRule
{
#region Private Members
private readonly AuditFlags _flags;
#endregion
#region Constructors
protected AuditRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags auditFlags )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags )
{
if ( auditFlags == AuditFlags.None )
{
throw new ArgumentException(
SR.Arg_EnumAtLeastOneFlag ,
nameof(auditFlags));
}
else if (( auditFlags & ~( AuditFlags.Success | AuditFlags.Failure )) != 0 )
{
throw new ArgumentOutOfRangeException(
nameof(auditFlags),
SR.ArgumentOutOfRange_Enum );
}
_flags = auditFlags;
}
#endregion
#region Public Properties
public AuditFlags AuditFlags
{
get { return _flags; }
}
#endregion
}
public abstract class ObjectAuditRule: AuditRule
{
#region Private Members
private readonly Guid _objectType;
private readonly Guid _inheritedObjectType;
private readonly ObjectAceFlags _objectFlags = ObjectAceFlags.None;
#endregion
#region Constructors
protected ObjectAuditRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AuditFlags auditFlags )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, auditFlags )
{
if (( !objectType.Equals( Guid.Empty )) && (( accessMask & ObjectAce.AccessMaskWithObjectType ) != 0 ))
{
_objectType = objectType;
_objectFlags |= ObjectAceFlags.ObjectAceTypePresent;
}
else
{
_objectType = Guid.Empty;
}
if (( !inheritedObjectType.Equals( Guid.Empty )) && ((inheritanceFlags & InheritanceFlags.ContainerInherit ) != 0 ))
{
_inheritedObjectType = inheritedObjectType;
_objectFlags |= ObjectAceFlags.InheritedObjectAceTypePresent;
}
else
{
_inheritedObjectType = Guid.Empty;
}
}
#endregion
#region Public Properties
public Guid ObjectType
{
get { return _objectType; }
}
public Guid InheritedObjectType
{
get { return _inheritedObjectType; }
}
public ObjectAceFlags ObjectFlags
{
get { return _objectFlags; }
}
#endregion
}
public sealed class AuthorizationRuleCollection : ICollection, IEnumerable // TODO: Is this right? Was previously ReadOnlyCollectionBase
{
#region ReadOnlyCollectionBase APIs
// Goo to translate this from ReadOnlyCollectionBase to ICollection
Object _syncRoot;
List<AuthorizationRule> list;
List<AuthorizationRule> InnerList
{
get
{
if (list == null)
list = new List<AuthorizationRule>();
return list;
}
}
public int Count
{
get { return InnerList.Count; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
void ICollection.CopyTo(Array array, int index)
{
InnerList.CopyTo((AuthorizationRule[])array, index);
}
IEnumerator IEnumerable.GetEnumerator()
{
return InnerList.GetEnumerator();
}
#endregion
#region Constructors
public AuthorizationRuleCollection()
: base()
{
}
#endregion
#region Public methods
public void AddRule(AuthorizationRule rule)
{
InnerList.Add( rule );
}
#endregion
#region ICollection Members
public void CopyTo( AuthorizationRule[] rules, int index )
{
(( ICollection )this ).CopyTo( rules, index );
}
#endregion
#region Public properties
public AuthorizationRule this[int index]
{
get { return InnerList[index] as AuthorizationRule; }
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsHttp
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// HttpSuccess operations.
/// </summary>
public partial interface IHttpSuccess
{
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Head200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get 200 success
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
Task<HttpOperationResponse<bool?>> Get200WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put boolean value true returning 200 success
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Put200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patch true Boolean value in request returning 200
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Patch200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post bollean value true in request that returns a 200
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Post200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete simple boolean value true returns 200
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Delete200WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put true Boolean value in request returns 201
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Put201WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post true Boolean value in request returns 201 (Created)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Post201WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Put202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patch true Boolean value in request returns 202
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Patch202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post true Boolean value in request returns 202 (Accepted)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Post202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete true Boolean value in request returns 202 (accepted)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Delete202WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Head204WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Put204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Patch true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Patch204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Post true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Post204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete true Boolean value in request returns 204 (no content)
/// </summary>
/// <param name='booleanValue'>
/// Simple boolean value true
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Delete204WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Return 404 status code
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
Task<HttpOperationResponse> Head404WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace UMA.Controls
{
// The TreeModel is a utility class working on a list of serializable TreeElements where the order and the depth of each TreeElement define
// the tree structure. Note that the TreeModel itself is not serializable (in Unity we are currently limited to serializing lists/arrays) but the
// input list is.
// The tree representation (parent and children references) are then build internally using TreeElementUtility.ListToTree (using depth
// values of the elements).
// The first element of the input list is required to have depth == -1 (the hiddenroot) and the rest to have
// depth >= 0 (otherwise an exception will be thrown)
public class TreeModel<T> where T : TreeElement
{
IList<T> m_Data;
T m_Root;
int m_MaxID;
public T root { get { return m_Root; } set { m_Root = value; } }
public event Action modelChanged;
public int numberOfDataElements
{
get { return m_Data.Count; }
}
public TreeModel (IList<T> data)
{
SetData (data);
}
public T Find (int id)
{
return m_Data.FirstOrDefault (element => element.id == id);
}
public void SetData (IList<T> data)
{
Init (data);
}
void Init (IList<T> data)
{
if (data == null)
throw new ArgumentNullException("data", "Input data is null. Ensure input is a non-null list.");
m_Data = data;
if (m_Data.Count > 0)
m_Root = TreeElementUtility.ListToTree(data);
m_MaxID = m_Data.Max(e => e.id);
}
public int GenerateUniqueID ()
{
return ++m_MaxID;
}
public IList<int> GetAncestors (int id)
{
var parents = new List<int>();
TreeElement T = Find(id);
if (T != null)
{
while (T.parent != null)
{
parents.Add(T.parent.id);
T = T.parent;
}
}
return parents;
}
public IList<int> GetDescendantsThatHaveChildren (int id)
{
T searchFromThis = Find(id);
if (searchFromThis != null)
{
return GetParentsBelowStackBased(searchFromThis);
}
return new List<int>();
}
IList<int> GetParentsBelowStackBased(TreeElement searchFromThis)
{
Stack<TreeElement> stack = new Stack<TreeElement>();
stack.Push(searchFromThis);
var parentsBelow = new List<int>();
while (stack.Count > 0)
{
TreeElement current = stack.Pop();
if (current.hasChildren)
{
parentsBelow.Add(current.id);
foreach (var T in current.children)
{
stack.Push(T);
}
}
}
return parentsBelow;
}
public void RemoveElements (IList<int> elementIDs)
{
IList<T> elements = m_Data.Where (element => elementIDs.Contains (element.id)).ToArray ();
RemoveElements (elements);
}
public void RemoveElements (IList<T> elements)
{
foreach (var element in elements)
if (element == m_Root)
throw new ArgumentException("It is not allowed to remove the root element");
var commonAncestors = TreeElementUtility.FindCommonAncestorsWithinList (elements);
foreach (var element in commonAncestors)
{
element.parent.children.Remove (element);
element.parent = null;
}
TreeElementUtility.TreeToList(m_Root, m_Data);
Changed();
}
public void AddElements (IList<T> elements, TreeElement parent, int insertPosition)
{
if (elements == null)
throw new ArgumentNullException("elements", "elements is null");
if (elements.Count == 0)
throw new ArgumentNullException("elements", "elements Count is 0: nothing to add");
if (parent == null)
throw new ArgumentNullException("parent", "parent is null");
if (parent.children == null)
parent.children = new List<TreeElement>();
parent.children.InsertRange(insertPosition, elements.Cast<TreeElement> ());
foreach (var element in elements)
{
element.parent = parent;
element.depth = parent.depth + 1;
TreeElementUtility.UpdateDepthValues(element);
}
TreeElementUtility.TreeToList(m_Root, m_Data);
Changed();
}
public void AddRoot (T root)
{
if (root == null)
throw new ArgumentNullException("root", "root is null");
if (m_Data == null)
throw new InvalidOperationException("Internal Error: data list is null");
if (m_Data.Count != 0)
throw new InvalidOperationException("AddRoot is only allowed on empty data list");
root.id = GenerateUniqueID ();
root.depth = -1;
m_Data.Add (root);
}
public void AddElement (T element, TreeElement parent, int insertPosition)
{
if (element == null)
throw new ArgumentNullException("element", "element is null");
if (parent == null)
throw new ArgumentNullException("parent", "parent is null");
if (parent.children == null)
parent.children = new List<TreeElement> ();
parent.children.Insert (insertPosition, element);
element.parent = parent;
TreeElementUtility.UpdateDepthValues(parent);
TreeElementUtility.TreeToList(m_Root, m_Data);
Changed ();
}
public void MoveElements(TreeElement parentElement, int insertionIndex, List<TreeElement> elements)
{
if (insertionIndex < 0)
throw new ArgumentException("Invalid input: insertionIndex is -1, client needs to decide what index elements should be reparented at");
// Invalid reparenting input
if (parentElement == null)
return;
// We are moving items so we adjust the insertion index to accomodate that any items above the insertion index is removed before inserting
if (insertionIndex > 0)
insertionIndex -= parentElement.children.GetRange(0, insertionIndex).Count(elements.Contains);
// Remove draggedItems from their parents
foreach (var draggedItem in elements)
{
draggedItem.parent.children.Remove(draggedItem); // remove from old parent
draggedItem.parent = parentElement; // set new parent
}
if (parentElement.children == null)
parentElement.children = new List<TreeElement>();
// Insert dragged items under new parent
parentElement.children.InsertRange(insertionIndex, elements);
TreeElementUtility.UpdateDepthValues (root);
TreeElementUtility.TreeToList (m_Root, m_Data);
Changed ();
}
void Changed ()
{
if (modelChanged != null)
modelChanged ();
}
}
}
| |
//
// Executors.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// 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.Threading;
using System.Collections.Generic;
using SThread = System.Threading.Thread;
namespace Sharpen
{
internal class Executors
{
static ThreadFactory defaultThreadFactory = new ThreadFactory ();
public static ExecutorService NewFixedThreadPool (int threads)
{
return new FixedThreadPoolExecutorService ();
}
public static ThreadFactory DefaultThreadFactory ()
{
return defaultThreadFactory;
}
}
internal class FixedThreadPoolExecutorService: ExecutorService
{
List<WaitHandle> tasks = new List<WaitHandle> ();
bool shuttingDown;
#region ExecutorService implementation
public bool AwaitTermination (long n, Sharpen.TimeUnit unit)
{
WaitHandle[] handles;
lock (tasks) {
if (tasks.Count == 0)
return true;
handles = tasks.ToArray ();
}
return WaitHandle.WaitAll (handles, (int) unit.Convert (n, TimeUnit.Milliseconds));
}
public void ShutdownNow ()
{
Shutdown ();
}
public void Shutdown ()
{
lock (tasks) {
shuttingDown = true;
}
}
public Future<T> Submit<T> (Sharpen.Callable<T> c)
{
TaskFuture<T> future = new TaskFuture<T> (this);
lock (tasks) {
if (shuttingDown)
throw new RejectedExecutionException ();
tasks.Add (future.DoneEvent);
ThreadPool.QueueUserWorkItem (delegate {
future.Run (c);
});
}
return future;
}
internal void RemoveTask (WaitHandle handle)
{
lock (tasks) {
tasks.Remove (handle);
}
}
#endregion
#region Executor implementation
public void Execute (Sharpen.Runnable runnable)
{
throw new System.NotImplementedException ();
}
#endregion
}
internal interface FutureBase
{
}
class TaskFuture<T>: Future<T>, FutureBase
{
SThread t;
T result;
ManualResetEvent doneEvent = new ManualResetEvent (false);
Exception error;
bool canceled;
bool started;
bool done;
FixedThreadPoolExecutorService service;
public TaskFuture (FixedThreadPoolExecutorService service)
{
this.service = service;
}
public WaitHandle DoneEvent {
get { return doneEvent; }
}
public void Run (Callable<T> c)
{
try {
lock (this) {
if (canceled)
return;
t = SThread.CurrentThread;
started = true;
}
result = c.Call ();
} catch (ThreadAbortException ex) {
SThread.ResetAbort ();
error = ex;
} catch (Exception ex) {
error = ex;
} finally {
lock (this) {
done = true;
service.RemoveTask (doneEvent);
}
doneEvent.Set ();
}
}
public bool Cancel (bool mayInterruptIfRunning)
{
lock (this) {
if (done || canceled)
return false;
canceled = true;
doneEvent.Set ();
if (started) {
if (mayInterruptIfRunning) {
try {
t.Abort ();
} catch {}
}
else
return false;
}
return true;
}
}
public T Get ()
{
doneEvent.WaitOne ();
if (canceled)
throw new CancellationException ();
if (error != null)
throw new ExecutionException (error);
else
return result;
}
}
internal class CancellationException: Exception
{
}
internal class RejectedExecutionException: Exception
{
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2014 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 12.20Release
// Tag = $Name$
////////////////////////////////////////////////////////////////////////////////
#endregion
using System.Collections.Generic;
using System.IO;
using FitFilePreviewer.Decode.Fit.Types;
using FitFilePreviewer.Decode.Utility;
namespace FitFilePreviewer.Decode.Fit
{
/// <summary>
/// Architecture defaults to Little Endian (unless decoded from an binary defn as Big Endian)
/// This could be exposed in the future to programatically create BE streams.
/// </summary>
public class MesgDefinition
{
#region Fields
private byte architecture;
private byte localMesgNum;
private List<FieldDefinition> fieldDefs = new List<FieldDefinition>();
#endregion
#region Properties
public ushort GlobalMesgNum { get; set; }
public byte LocalMesgNum
{
get
{
return localMesgNum;
}
set
{
if (value > Fit.LocalMesgNumMask)
{
throw new FitException("MesgDefinition:LocalMesgNum - Invalid Local message number " + value + ". Local message number must be < " + Fit.LocalMesgNumMask);
}
else
{
localMesgNum = value;
}
}
}
public byte NumFields { get; set; }
public bool IsBigEndian
{
get
{
if (architecture == Fit.BigEndian)
{
return true;
}
else
{
return false;
}
}
}
#endregion
#region Constructors
internal MesgDefinition()
{
LocalMesgNum = 0;
GlobalMesgNum = (ushort)MesgNum.Invalid;
architecture = Fit.LittleEndian;
}
public MesgDefinition(Stream fitSource)
{
Read(fitSource);
}
public MesgDefinition(Mesg mesg)
{
LocalMesgNum = mesg.LocalNum;
GlobalMesgNum = mesg.Num;
architecture = Fit.LittleEndian;
NumFields = (byte)mesg.fields.Count;
foreach (Field field in mesg.fields)
{
fieldDefs.Add(new FieldDefinition(field));
}
}
public MesgDefinition(MesgDefinition mesgDef)
{
LocalMesgNum = mesgDef.LocalMesgNum;
GlobalMesgNum = mesgDef.GlobalMesgNum;
architecture = mesgDef.IsBigEndian ? Fit.BigEndian : Fit.LittleEndian;
NumFields = mesgDef.NumFields;
foreach (FieldDefinition fieldDef in mesgDef.fieldDefs)
{
fieldDefs.Add(new FieldDefinition(fieldDef));
}
}
#endregion
#region Methods
public void Read(Stream fitSource)
{
fitSource.Position = 0;
EndianBinaryReader br = new EndianBinaryReader(fitSource, false);
LocalMesgNum = (byte)(br.ReadByte() & Fit.LocalMesgNumMask);
byte reserved = br.ReadByte();
architecture = br.ReadByte();
br.IsBigEndian = this.IsBigEndian;
GlobalMesgNum = br.ReadUInt16();
NumFields = br.ReadByte();
for (int i=0; i<NumFields; i++)
{
FieldDefinition newField = new FieldDefinition();
newField.Num = br.ReadByte();
newField.Size = br.ReadByte();
newField.Type = br.ReadByte();
fieldDefs.Add(newField);
}
}
public void Write (Stream fitDest)
{
BinaryWriter bw = new BinaryWriter(fitDest);
bw.Write((byte)(LocalMesgNum + Fit.MesgDefinitionMask));
bw.Write((byte)Fit.MesgDefinitionReserved);
bw.Write((byte)Fit.LittleEndian);
bw.Write(GlobalMesgNum);
bw.Write(NumFields);
if (NumFields != fieldDefs.Count)
{
throw new FitException("MesgDefinition:Write - Field Count Internal Error");
}
for (int i = 0; i < fieldDefs.Count; i++)
{
bw.Write(fieldDefs[i].Num);
bw.Write(fieldDefs[i].Size);
bw.Write(fieldDefs[i].Type);
}
}
public int GetMesgSize()
{
int mesgSize = 1; // header
foreach (FieldDefinition field in fieldDefs)
{
mesgSize += field.Size;
}
return mesgSize;
}
public void AddField(FieldDefinition field)
{
fieldDefs.Add(field);
}
public void ClearFields()
{
fieldDefs.Clear();
}
public int GetNumFields()
{
return fieldDefs.Count;
}
public List<FieldDefinition> GetFields()
{
// This is a reference to the real list
return fieldDefs;
}
public FieldDefinition GetField(byte num)
{
foreach (FieldDefinition fieldDef in fieldDefs)
{
if (fieldDef.Num == num)
{
return fieldDef;
}
}
return null;
}
public bool Supports(Mesg mesg)
{
return Supports(new MesgDefinition(mesg));
}
public bool Supports(MesgDefinition mesgDef)
{
if (mesgDef == null)
{
return false;
}
if (GlobalMesgNum != mesgDef.GlobalMesgNum)
{
return false;
}
if (LocalMesgNum != mesgDef.LocalMesgNum)
{
return false;
}
foreach (FieldDefinition fieldDef in mesgDef.GetFields())
{
FieldDefinition supportedFieldDef = GetField(fieldDef.Num);
if (supportedFieldDef == null)
{
return false;
}
if (fieldDef.Size > supportedFieldDef.Size)
{
return false;
}
}
return true;
}
#endregion
}
} // namespace
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Threading;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class Handshake_Property : PortsTest
{
//The default number of bytes to read/write to verify the speed of the port
//and that the bytes were transfered successfully
private static readonly int s_DEFAULT_BYTE_SIZE = TCSupport.MinimumBlockingByteCount;
//The number of bytes to send when send XOn or XOff, the actual XOn/XOff char will be inserted somewhere
//in the array of bytes
private static readonly int s_DEFAULT_BYTE_SIZE_XON_XOFF = TCSupport.MinimumBlockingByteCount * 2;
//The default time to wait after writing some bytes
private const int DEFAULT_WAIT_AFTER_READ_OR_WRITE = 500;
private enum ThrowAt { Set, Open };
#region Test Cases
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_Default()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
Debug.WriteLine("Verifying default Handshake");
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyHandshake(com1);
com1.DiscardInBuffer();
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_None_BeforeOpen()
{
Debug.WriteLine("Verifying None Handshake before open");
VerifyHandshakeBeforeOpen((int)Handshake.None);
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_XOnXOff_BeforeOpen()
{
Debug.WriteLine("Verifying XOnXOff Handshake before open");
VerifyHandshakeBeforeOpen((int)Handshake.XOnXOff);
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSend_BeforeOpen()
{
Debug.WriteLine("Verifying RequestToSend Handshake before open");
VerifyHandshakeBeforeOpen((int)Handshake.RequestToSend);
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSendXOnXOff_BeforeOpen()
{
Debug.WriteLine("Verifying RequestToSendXOnXOff Handshake before open");
VerifyHandshakeBeforeOpen((int)Handshake.RequestToSendXOnXOff);
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_None_AfterOpen()
{
Debug.WriteLine("Verifying None Handshake after open");
VerifyHandshakeAfterOpen((int)Handshake.None);
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem))]
public void Handshake_XOnXOff_AfterOpen()
{
Debug.WriteLine("Verifying XOnXOff Handshake after open");
VerifyHandshakeAfterOpen((int)Handshake.XOnXOff);
}
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSend_AfterOpen()
{
Debug.WriteLine("Verifying RequestToSend Handshake after open");
VerifyHandshakeAfterOpen((int)Handshake.RequestToSend);
}
[KnownFailure]
[ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))]
public void Handshake_RequestToSendXOnXOff_AfterOpen()
{
Debug.WriteLine("Verifying RequestToSendXOnXOff Handshake after open");
VerifyHandshakeAfterOpen((int)Handshake.RequestToSendXOnXOff);
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Handshake_Int32MinValue()
{
Debug.WriteLine("Verifying Int32.MinValue Handshake");
VerifyException(int.MinValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Handshake_Neg1()
{
Debug.WriteLine("Verifying -1 Handshake");
VerifyException(-1, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Handshake_4()
{
Debug.WriteLine("Verifying 4 Handshake");
VerifyException(4, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Handshake_Int32MaxValue()
{
Debug.WriteLine("Verifying Int32.MaxValue Handshake");
VerifyException(int.MaxValue, ThrowAt.Set, typeof(ArgumentOutOfRangeException));
}
#endregion
#region Verification for Test Cases
private void VerifyException(int handshake, ThrowAt throwAt, Type expectedException)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
VerifyExceptionAtOpen(com, handshake, throwAt, expectedException);
if (com.IsOpen)
com.Close();
VerifyExceptionAfterOpen(com, handshake, expectedException);
}
}
private void VerifyExceptionAtOpen(SerialPort com, int handshake, ThrowAt throwAt, Type expectedException)
{
int origHandshake = (int)com.Handshake;
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
if (ThrowAt.Open == throwAt)
serPortProp.SetProperty("Handshake", (Handshake)handshake);
try
{
com.Handshake = (Handshake)handshake;
if (ThrowAt.Open == throwAt)
com.Open();
if (null != expectedException)
{
Fail("ERROR!!! Expected Open() to throw {0} and nothing was thrown", expectedException);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("ERROR!!! Expected Open() NOT to throw an exception and {0} was thrown", e.GetType());
}
else if (e.GetType() != expectedException)
{
Fail("ERROR!!! Expected Open() throw {0} and {1} was thrown", expectedException, e.GetType());
}
}
serPortProp.VerifyPropertiesAndPrint(com);
com.Handshake = (Handshake)origHandshake;
}
private void VerifyExceptionAfterOpen(SerialPort com, int handshake, Type expectedException)
{
SerialPortProperties serPortProp = new SerialPortProperties();
com.Open();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
try
{
com.Handshake = (Handshake)handshake;
if (null != expectedException)
{
Fail("ERROR!!! Expected setting the Handshake after Open() to throw {0} and nothing was thrown", expectedException);
}
}
catch (Exception e)
{
if (null == expectedException)
{
Fail("ERROR!!! Expected setting the Handshake after Open() NOT to throw an exception and {0} was thrown", e.GetType());
}
else if (e.GetType() != expectedException)
{
Fail("ERROR!!! Expected setting the Handshake after Open() throw {0} and {1} was thrown", expectedException, e.GetType());
}
}
serPortProp.VerifyPropertiesAndPrint(com);
}
private void VerifyHandshakeBeforeOpen(int handshake)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Handshake = (Handshake)handshake;
com1.Open();
serPortProp.SetProperty("Handshake", (Handshake)handshake);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyHandshake(com1);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
private void VerifyHandshakeAfterOpen(int handshake)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
SerialPortProperties serPortProp = new SerialPortProperties();
serPortProp.SetAllPropertiesToOpenDefaults();
serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName);
com1.Open();
com1.Handshake = (Handshake)handshake;
serPortProp.SetProperty("Handshake", (Handshake)handshake);
serPortProp.VerifyPropertiesAndPrint(com1);
VerifyHandshake(com1);
serPortProp.VerifyPropertiesAndPrint(com1);
}
}
private void VerifyHandshake(SerialPort com1)
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
int origWriteTimeout = com1.WriteTimeout;
int origReadTimeout = com1.ReadTimeout;
com2.Open();
com1.WriteTimeout = 250;
com1.ReadTimeout = 250;
VerifyRTSHandshake(com1, com2);
VerifyXOnXOffHandshake(com1, com2);
VerifyRTSXOnXOffHandshake(com1, com2);
VerirfyRTSBufferFull(com1, com2);
VerirfyXOnXOffBufferFull(com1, com2);
com1.WriteTimeout = origWriteTimeout;
com1.ReadTimeout = origReadTimeout;
}
}
private void VerifyRTSHandshake(SerialPort com1, SerialPort com2)
{
bool origRtsEnable = com2.RtsEnable;
try
{
com2.RtsEnable = true;
try
{
com1.Write(new byte[s_DEFAULT_BYTE_SIZE], 0, s_DEFAULT_BYTE_SIZE);
}
catch (TimeoutException)
{
Fail("Err_103948aooh!!! TimeoutException thrown when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake);
}
com2.RtsEnable = false;
try
{
com1.Write(new byte[s_DEFAULT_BYTE_SIZE], 0, s_DEFAULT_BYTE_SIZE);
if (Handshake.RequestToSend == com1.Handshake || Handshake.RequestToSendXOnXOff == com1.Handshake)
{
Fail("Err_15397lkjh!!! TimeoutException NOT thrown when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake);
}
}
catch (TimeoutException)
{
if (Handshake.RequestToSend != com1.Handshake && Handshake.RequestToSendXOnXOff != com1.Handshake)
{
Fail("Err_1341pawh!!! TimeoutException thrown when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake);
}
}
com2.RtsEnable = true;
try
{
com1.Write(new byte[s_DEFAULT_BYTE_SIZE], 0, s_DEFAULT_BYTE_SIZE);
}
catch (TimeoutException)
{
Fail("Err_143987aqaih!!! TimeoutException thrown when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake);
}
}
finally
{
com2.RtsEnable = origRtsEnable;
com2.DiscardInBuffer();
}
}
private void VerifyRTSXOnXOffHandshake(SerialPort com1, SerialPort com2)
{
bool origRtsEnable = com2.RtsEnable;
Random rndGen = new Random();
byte[] xmitXOnBytes = new byte[s_DEFAULT_BYTE_SIZE_XON_XOFF];
byte[] xmitXOffBytes = new byte[s_DEFAULT_BYTE_SIZE_XON_XOFF];
try
{
for (int i = 0; i < xmitXOnBytes.Length; i++)
{
byte rndByte;
do
{
rndByte = (byte)rndGen.Next(0, 256);
} while (rndByte == 17 || rndByte == 19);
xmitXOnBytes[i] = rndByte;
}
for (int i = 0; i < xmitXOffBytes.Length; i++)
{
byte rndByte;
do
{
rndByte = (byte)rndGen.Next(0, 256);
} while (rndByte == 17 || rndByte == 19);
xmitXOffBytes[i] = rndByte;
}
xmitXOnBytes[rndGen.Next(0, xmitXOnBytes.Length)] = (byte)17;
xmitXOffBytes[rndGen.Next(0, xmitXOffBytes.Length)] = (byte)19;
com2.RtsEnable = false;
com2.Write(xmitXOffBytes, 0, xmitXOffBytes.Length);
com2.Write(xmitXOnBytes, 0, xmitXOnBytes.Length);
while (true)
{
try
{
com1.ReadByte();
}
catch (TimeoutException)
{
break;
}
}
try
{
com1.Write(new byte[s_DEFAULT_BYTE_SIZE], 0, s_DEFAULT_BYTE_SIZE);
if (Handshake.RequestToSend == com1.Handshake || Handshake.RequestToSendXOnXOff == com1.Handshake)
{
Fail("Err_1253aasyo!!! TimeoutException NOT thrown after XOff and XOn char sent when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake);
}
}
catch (TimeoutException)
{
if (Handshake.RequestToSend != com1.Handshake && Handshake.RequestToSendXOnXOff != com1.Handshake)
{
Fail("Err_51390awi!!! TimeoutException thrown after XOff and XOn char sent when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake);
}
}
com2.Write(xmitXOffBytes, 0, xmitXOffBytes.Length);
com2.RtsEnable = false;
com2.RtsEnable = true;
while (true)
{
try
{
com1.ReadByte();
}
catch (TimeoutException)
{
break;
}
}
try
{
com1.Write(new byte[s_DEFAULT_BYTE_SIZE], 0, s_DEFAULT_BYTE_SIZE);
if (Handshake.XOnXOff == com1.Handshake || Handshake.RequestToSendXOnXOff == com1.Handshake)
{
Fail("Err_2457awez!!! TimeoutException NOT thrown after RTSEnable set to false then true when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake);
}
}
catch (TimeoutException)
{
if (Handshake.XOnXOff != com1.Handshake && Handshake.RequestToSendXOnXOff != com1.Handshake)
{
Fail("Err_3240aw4er!!! TimeoutException thrown RTSEnable set to false then true when CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake);
}
}
com2.Write(xmitXOnBytes, 0, xmitXOnBytes.Length);
while (true)
{
try
{
com1.ReadByte();
}
catch (TimeoutException)
{
break;
}
}
}
finally
{
com2.RtsEnable = origRtsEnable;
com2.DiscardInBuffer();
}
}
private void VerifyXOnXOffHandshake(SerialPort com1, SerialPort com2)
{
bool origRtsEnable = com2.RtsEnable;
Random rndGen = new Random();
byte[] xmitXOnBytes = new byte[s_DEFAULT_BYTE_SIZE_XON_XOFF];
byte[] xmitXOffBytes = new byte[s_DEFAULT_BYTE_SIZE_XON_XOFF];
try
{
com2.RtsEnable = true;
for (int i = 0; i < xmitXOnBytes.Length; i++)
{
byte rndByte;
do
{
rndByte = (byte)rndGen.Next(0, 256);
} while (rndByte == 17 || rndByte == 19);
xmitXOnBytes[i] = rndByte;
}
for (int i = 0; i < xmitXOffBytes.Length; i++)
{
byte rndByte;
do
{
rndByte = (byte)rndGen.Next(0, 256);
} while (rndByte == 17 || rndByte == 19);
xmitXOffBytes[i] = rndByte;
}
Assert.InRange(xmitXOnBytes.Length, 1, int.MaxValue);
int XOnIndex = rndGen.Next(0, xmitXOnBytes.Length);
int XOffIndex = rndGen.Next(0, xmitXOffBytes.Length);
xmitXOnBytes[XOnIndex] = (byte)17;
xmitXOffBytes[XOffIndex] = (byte)19;
Debug.WriteLine("XOnIndex={0} XOffIndex={1}", XOnIndex, XOffIndex);
com2.Write(xmitXOnBytes, 0, xmitXOnBytes.Length);
com2.Write(xmitXOnBytes, 0, xmitXOnBytes.Length);
while (true)
{
try
{
com1.ReadByte();
}
catch (TimeoutException)
{
break;
}
}
try
{
com1.Write(new byte[s_DEFAULT_BYTE_SIZE], 0, s_DEFAULT_BYTE_SIZE);
}
catch (TimeoutException)
{
Fail("Err_2357pquaz!!! TimeoutException thrown after XOn char sent and CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake);
}
com2.Write(xmitXOffBytes, 0, xmitXOffBytes.Length);
while (true)
{
try
{
com1.ReadByte();
}
catch (TimeoutException)
{
break;
}
}
try
{
com1.Write(new byte[s_DEFAULT_BYTE_SIZE], 0, s_DEFAULT_BYTE_SIZE);
if (Handshake.XOnXOff == com1.Handshake || Handshake.RequestToSendXOnXOff == com1.Handshake)
{
Fail("Err_1349znpq!!! TimeoutException NOT thrown after XOff char sent and CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake);
}
}
catch (TimeoutException)
{
if (Handshake.XOnXOff != com1.Handshake && Handshake.RequestToSendXOnXOff != com1.Handshake)
{
Fail("Err_2507pqzhn!!! TimeoutException thrown after XOff char sent and CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake);
}
}
com2.Write(xmitXOnBytes, 0, xmitXOnBytes.Length);
while (true)
{
try
{
com1.ReadByte();
}
catch (TimeoutException)
{
break;
}
}
try
{
com1.Write(new byte[s_DEFAULT_BYTE_SIZE], 0, s_DEFAULT_BYTE_SIZE);
}
catch (TimeoutException)
{
Fail("Err_2570aqpa!!! TimeoutException thrown after XOn char sent and CtsHolding={0} with Handshake={1}", com1.CtsHolding, com1.Handshake);
}
}
finally
{
com2.RtsEnable = origRtsEnable;
com2.DiscardInBuffer();
}
}
private void VerirfyRTSBufferFull(SerialPort com1, SerialPort com2)
{
int com1BaudRate = com1.BaudRate;
int com2BaudRate = com2.BaudRate;
int com1ReadBufferSize = com1.ReadBufferSize;
int bufferSize = com1.ReadBufferSize;
int upperLimit = (3 * bufferSize) / 4;
int lowerLimit = bufferSize / 4;
byte[] bytes = new byte[upperLimit];
try
{
//Set the BaudRate to something faster so that it does not take so long to fill up the buffer
com1.BaudRate = 115200;
com2.BaudRate = 115200;
//Write 1 less byte then when the RTS pin would be cleared
com2.Write(bytes, 0, upperLimit - 1);
Thread.Sleep(DEFAULT_WAIT_AFTER_READ_OR_WRITE);
if (IsRequestToSend(com1))
{
if (!com2.CtsHolding)
{
Fail("Err_548458ahiede Expected RTS to be set");
}
}
else
{
if (com2.CtsHolding)
{
Fail("Err_028538aieoz Expected RTS to be cleared");
}
}
//Write the byte and verify the RTS pin is cleared appropriately
com2.Write(bytes, 0, 1);
Thread.Sleep(DEFAULT_WAIT_AFTER_READ_OR_WRITE);
if (IsRequestToSend(com1))
{
if (com2.CtsHolding)
{
Fail("Err_508845aueid Expected RTS to be cleared");
}
}
else
{
if (com2.CtsHolding)
{
Fail("Err_48848ajeoid Expected RTS to be set");
}
}
//Read 1 less byte then when the RTS pin would be set
com1.Read(bytes, 0, (upperLimit - lowerLimit) - 1);
Thread.Sleep(DEFAULT_WAIT_AFTER_READ_OR_WRITE);
if (IsRequestToSend(com1))
{
if (com2.CtsHolding)
{
Fail("Err_952085aizpea Expected RTS to be cleared");
}
}
else
{
if (com2.CtsHolding)
{
Fail("Err_725527ahjiuzp Expected RTS to be set");
}
}
//Read the byte and verify the RTS pin is set appropriately
com1.Read(bytes, 0, 1);
Thread.Sleep(DEFAULT_WAIT_AFTER_READ_OR_WRITE);
if (IsRequestToSend(com1))
{
if (!com2.CtsHolding)
{
Fail("Err_652820aopea Expected RTS to be set");
}
}
else
{
if (com2.CtsHolding)
{
Fail("Err_35585ajuei Expected RTS to be cleared");
}
}
}
finally
{
//Rollback any changed that were made to the SerialPort
com1.BaudRate = com1BaudRate;
com2.BaudRate = com2BaudRate;
com1.DiscardInBuffer();//This can cuase the XOn character to be sent to com2.
Thread.Sleep(DEFAULT_WAIT_AFTER_READ_OR_WRITE);
com2.DiscardInBuffer();
}
}
private void VerirfyXOnXOffBufferFull(SerialPort com1, SerialPort com2)
{
int com1BaudRate = com1.BaudRate;
int com2BaudRate = com2.BaudRate;
int com1ReadBufferSize = com1.ReadBufferSize;
bool com2RtsEnable = com2.RtsEnable;
int bufferSize = com1.ReadBufferSize;
int upperLimit = bufferSize - 1024;
int lowerLimit = 1024;
byte[] bytes = new byte[upperLimit];
int byteRead;
try
{
//Set the BaudRate to something faster so that it does not take so long to fill up the buffer
com1.BaudRate = 115200;
com2.BaudRate = 115200;
if (com1.Handshake == Handshake.RequestToSendXOnXOff)
{
com2.RtsEnable = true;
com1.Write("foo");
Thread.Sleep(DEFAULT_WAIT_AFTER_READ_OR_WRITE);
com2.DiscardInBuffer();
}
//Write 1 less byte then when the XOff character would be sent
com2.Write(bytes, 0, upperLimit - 1);
Thread.Sleep(DEFAULT_WAIT_AFTER_READ_OR_WRITE);
if (IsXOnXOff(com1))
{
if (com2.BytesToRead != 0)
{
Fail("Err_81919aniee Did not expect anything to be sent");
}
}
else
{
if (com2.BytesToRead != 0)
{
Fail("Err_5258aieodpo Did not expect anything to be sent com2.BytesToRead={0}", com2.BytesToRead);
}
}
//Write the byte and verify the XOff character was sent as appropriately
com2.Write(bytes, 0, 1);
Thread.Sleep(DEFAULT_WAIT_AFTER_READ_OR_WRITE);
if (IsXOnXOff(com1))
{
if (com2.BytesToRead != 1)
{
Fail("Err_12558aoed Expected XOff to be sent and nothing was sent");
}
else if (XOnOff.XOFF != (byteRead = com2.ReadByte()))
{
Fail("Err_0188598aoepad Expected XOff to be sent actually sent={0}", byteRead);
}
}
else
{
if (com2.BytesToRead != 0)
{
Fail("Err_2258ajoe Did not expect anything to be sent");
}
}
//Read 1 less byte then when the XOn char would be sent
com1.Read(bytes, 0, (upperLimit - lowerLimit) - 1);
Thread.Sleep(DEFAULT_WAIT_AFTER_READ_OR_WRITE);
if (IsXOnXOff(com1))
{
if (com2.BytesToRead != 0)
{
Fail("Err_22808aiuepa Did not expect anything to be sent");
}
}
else
{
if (com2.BytesToRead != 0)
{
Fail("Err_12508aieap Did not expect anything to be sent");
}
}
//Read the byte and verify the XOn char is sent as appropriately
com1.Read(bytes, 0, 1);
Thread.Sleep(DEFAULT_WAIT_AFTER_READ_OR_WRITE);
if (IsXOnXOff(com1))
{
if (com2.BytesToRead != 1)
{
Fail("Err_6887518adizpa Expected XOn to be sent and nothing was sent");
}
else if (XOnOff.XON != (byteRead = com2.ReadByte()))
{
Fail("Err_58145auead Expected XOn to be sent actually sent={0}", byteRead);
}
}
else
{
if (com2.BytesToRead != 0)
{
Fail("Err_256108aipeg Did not expect anything to be sent");
}
}
}
finally
{
//Rollback any changed that were made to the SerialPort
com1.BaudRate = com1BaudRate;
com2.BaudRate = com2BaudRate;
com1.DiscardInBuffer();
com2.DiscardInBuffer();
com2.RtsEnable = com2RtsEnable;
}
}
private bool IsRequestToSend(SerialPort com)
{
return com.Handshake == Handshake.RequestToSend || com.Handshake == Handshake.RequestToSendXOnXOff;
}
private bool IsXOnXOff(SerialPort com)
{
return com.Handshake == Handshake.XOnXOff || com.Handshake == Handshake.RequestToSendXOnXOff;
}
#endregion
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
namespace App.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc3")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("WebApplication.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Claims")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany("Claims")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany("Logins")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("WebApplication.Models.ApplicationUser")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureParameterGrouping
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestParameterGroupingTestService : ServiceClient<AutoRestParameterGroupingTestService>, IAutoRestParameterGroupingTestService, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IParameterGroupingOperations.
/// </summary>
public virtual IParameterGroupingOperations ParameterGrouping { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestParameterGroupingTestService(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestParameterGroupingTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestParameterGroupingTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestParameterGroupingTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestParameterGroupingTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestParameterGroupingTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestParameterGroupingTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestParameterGroupingTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.ParameterGrouping = new ParameterGroupingOperations(this);
this.BaseUri = new Uri("https://localhost");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
using System;
using System.Globalization;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Q42.HueApi.Interfaces;
using Q42.HueApi.Converters;
namespace Q42.HueApi
{
/// <summary>
/// Compose a light command to send to a light
/// </summary>
[DataContract]
public class LightCommand : ICommandBody
{
/// <summary>
/// Gets or sets the colors based on CIE 1931 Color coordinates.
/// </summary>
[DataMember (Name = "xy")]
public double[] ColorCoordinates { get; set; }
/// <summary>
/// Gets or sets the brightness 0-255.
/// </summary>
[DataMember (Name = "bri")]
public byte? Brightness { get; set; }
/// <summary>
/// Gets or sets the hue for Hue and <see cref="Saturation"/> mode.
/// </summary>
[DataMember (Name = "hue")]
public int? Hue { get; set; }
/// <summary>
/// Gets or sets the saturation for <see cref="Hue"/> and Saturation mode.
/// </summary>
[DataMember (Name = "sat")]
public int? Saturation { get; set; }
/// <summary>
/// Gets or sets the Color Temperature
/// </summary>
[DataMember (Name = "ct")]
public int? ColorTemperature { get; set; }
/// <summary>
/// Gets or sets whether the light is on.
/// </summary>
[DataMember (Name = "on")]
public bool? On { get; set; }
/// <summary>
/// Gets or sets the current effect for the light.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
[DataMember (Name = "effect")]
public Effect? Effect { get; set; }
/// <summary>
/// Gets or sets the current alert for the light.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
[DataMember (Name = "alert")]
public Alert? Alert { get; set; }
/// <summary>
/// Gets or sets the transition time for the light.
/// </summary>
[DataMember (Name = "transitiontime")]
[JsonConverter (typeof(TransitionTimeConverter))]
public TimeSpan? TransitionTime { get; set; }
/// <summary>
/// -254 to 254
/// As of 1.7. Increments or decrements the value of the brightness. bri_inc is ignored if the bri attribute is provided. Any ongoing bri transition is stopped. Setting a value of 0 also stops any ongoing transition. The bridge will return the bri value after the increment is performed.
/// </summary>
[DataMember(Name = "bri_inc")]
public int? BrightnessIncrement { get; set; }
/// <summary>
/// -254 to 254
/// As of 1.7. Increments or decrements the value of the sat. sat_inc is ignored if the sat attribute is provided. Any ongoing sat transition is stopped. Setting a value of 0 also stops any ongoing transition. The bridge will return the sat value after the increment is performed.
/// </summary>
[DataMember(Name = "sat_inc")]
public int? SaturationIncrement { get; set; }
/// <summary>
/// -65534 to 65534
/// As of 1.7. Increments or decrements the value of the hue. hue_inc is ignored if the hue attribute is provided. Any ongoing color transition is stopped. Setting a value of 0 also stops any ongoing transition. The bridge will return the hue value after the increment is performed.
/// </summary>
[DataMember(Name = "hue_inc")]
public int? HueIncrement { get; set; }
/// <summary>
/// -65534 to 65534
/// As of 1.7. Increments or decrements the value of the ct. ct_inc is ignored if the ct attribute is provided. Any ongoing color transition is stopped. Setting a value of 0 also stops any ongoing transition. The bridge will return the ct value after the increment is performed.
/// </summary>
[DataMember(Name = "ct_inc")]
public int? ColorTemperatureIncrement { get; set; }
/// <summary>
/// -0.5 to 0.5
/// As of 1.7. Increments or decrements the value of the xy. xy_inc is ignored if the xy attribute is provided. Any ongoing color transition is stopped. Will stop at it's gamut boundaries. Setting a value of 0 also stops any ongoing transition. The bridge will return the xy value after the increment is performed.
/// </summary>
[DataMember(Name = "xy_inc")]
public double[]? ColorCoordinatesIncrement { get; set; }
}
/// <summary>
/// Possible light alerts
/// </summary>
public enum Alert
{
/// <summary>
/// Stop alert
/// </summary>
[EnumMember (Value = "none")]
None,
/// <summary>
/// Alert once
/// </summary>
[EnumMember (Value = "select")]
Once,
/// <summary>
/// Alert multiple times
/// </summary>
[EnumMember (Value = "lselect")]
Multiple
}
/// <summary>
/// Possible light effects
/// </summary>
public enum Effect
{
/// <summary>
/// Stop current effect
/// </summary>
[EnumMember (Value = "none")]
None,
/// <summary>
/// Color loop
/// </summary>
[EnumMember (Value = "colorloop")]
ColorLoop
}
/// <summary>
/// Extension methods to compose a light command
/// </summary>
public static class lightCommandExtensions
{
/// <summary>
/// Helper to set the color based on the light's built in XY color schema
/// </summary>
/// <param name="lightCommand"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static LightCommand SetColor(this LightCommand lightCommand, double x, double y)
{
if (lightCommand == null)
throw new ArgumentNullException (nameof(lightCommand));
lightCommand.ColorCoordinates = new[] { x, y };
return lightCommand;
}
/// <summary>
/// Helper to set the color based on the light's built in CT color scheme
/// </summary>
/// <param name="lightCommand"></param>
/// <param name="ct"></param>
/// <returns></returns>
public static LightCommand SetColor(this LightCommand lightCommand, int ct)
{
if (lightCommand == null)
throw new ArgumentNullException (nameof(lightCommand));
lightCommand.ColorTemperature = ct;
return lightCommand;
}
/// <summary>
/// Helper to create turn on command
/// </summary>
/// <param name="lightCommand"></param>
/// <returns></returns>
public static LightCommand TurnOn(this LightCommand lightCommand)
{
if (lightCommand == null)
throw new ArgumentNullException (nameof(lightCommand));
lightCommand.On = true;
return lightCommand;
}
/// <summary>
/// Helper to create turn off command
/// </summary>
/// <param name="lightCommand"></param>
/// <returns></returns>
public static LightCommand TurnOff(this LightCommand lightCommand)
{
if (lightCommand == null)
throw new ArgumentNullException (nameof(lightCommand));
lightCommand.On = false;
return lightCommand;
}
}
}
| |
using System;
using Rhino.Commons;
using Rhino.Security.Interfaces;
using Rhino.Security.Model;
namespace Rhino.Security.Services
{
/// <summary>
/// Allow to define permissions using a fluent interface
/// </summary>
public class PermissionsBuilderService : IPermissionsBuilderService
{
private readonly IRepository<Permission> permissionRepository;
private readonly IAuthorizationRepository authorizationRepository;
/// <summary>
/// Initializes a new instance of the <see cref="PermissionsBuilderService"/> class.
/// </summary>
/// <param name="permissionRepository">The permission repository.</param>
/// <param name="authorizationRepository">The authorization editing service.</param>
public PermissionsBuilderService(IRepository<Permission> permissionRepository, IAuthorizationRepository authorizationRepository)
{
this.permissionRepository = permissionRepository;
this.authorizationRepository = authorizationRepository;
}
/// <summary>
/// Builds a permission
/// </summary>
public class FluentPermissionBuilder : IPermissionBuilder, IForPermissionBuilder, IOnPermissionBuilder,
ILevelPermissionBuilder
{
private readonly Permission permission = new Permission();
private readonly PermissionsBuilderService permissionBuilderService;
/// <summary>
/// Initializes a new instance of the <see cref="FluentPermissionBuilder"/> class.
/// </summary>
/// <param name="permissionBuilderService">The permission service.</param>
/// <param name="allow">if set to <c>true</c> create an allow permission.</param>
/// <param name="operation">The operation.</param>
public FluentPermissionBuilder(PermissionsBuilderService permissionBuilderService, bool allow, Operation operation)
{
this.permissionBuilderService = permissionBuilderService;
permission.Allow = allow;
permission.Operation = operation;
}
/// <summary>
/// Save the created permission
/// </summary>
public Permission Save()
{
permissionBuilderService.Save(permission);
return permission;
}
/// <summary>
/// Set the user that this permission is built for
/// </summary>
/// <param name="user">The user.</param>
/// <returns></returns>
public IOnPermissionBuilder For(IUser user)
{
permission.User = user;
return this;
}
/// <summary>
/// Set the users group that this permission is built for
/// </summary>
/// <param name="usersGroupName">Name of the users group.</param>
/// <returns></returns>
public IOnPermissionBuilder For(string usersGroupName)
{
UsersGroup usersGroup = permissionBuilderService
.authorizationRepository
.GetUsersGroupByName(usersGroupName);
Guard.Against<ArgumentException>(usersGroup == null, "There is not users group named: " + usersGroup);
return For(usersGroup);
}
/// <summary>
/// Set the users group that this permission is built for
/// </summary>
/// <param name="usersGroup">The users group.</param>
/// <returns></returns>
public IOnPermissionBuilder For(UsersGroup usersGroup)
{
permission.UsersGroup = usersGroup;
return this;
}
/// <summary>
/// Set the entity this permission is built for
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <param name="entity">The account.</param>
/// <returns></returns>
public ILevelPermissionBuilder On<TEntity>(TEntity entity) where TEntity : class
{
permission.SetEntityType(typeof (TEntity));
permission.EntitySecurityKey = Security.ExtractKey(entity);
return this;
}
/// <summary>
/// Set the entity group this permission is built for
/// </summary>
/// <param name="entitiesGroupName">Name of the entities group.</param>
/// <returns></returns>
public ILevelPermissionBuilder On(string entitiesGroupName)
{
EntitiesGroup entitiesGroup =
permissionBuilderService
.authorizationRepository
.GetEntitiesGroupByName(entitiesGroupName);
Guard.Against<ArgumentException>(entitiesGroup == null,
"There is no entities group named: " + entitiesGroupName);
return On(entitiesGroup);
}
/// <summary>
/// Set the entity group this permission is built for
/// </summary>
/// <param name="entitiesGroup">The entities group.</param>
/// <returns></returns>
public ILevelPermissionBuilder On(EntitiesGroup entitiesGroup)
{
permission.EntitiesGroup = entitiesGroup;
return this;
}
/// <summary>
/// Set this permission to be application to everything
/// </summary>
/// <returns></returns>
public ILevelPermissionBuilder OnEverything()
{
return this;
}
/// <summary>
/// Define the level of this permission
/// </summary>
/// <param name="level">The level.</param>
/// <returns></returns>
public IPermissionBuilder Level(int level)
{
permission.Level = level;
return this;
}
/// <summary>
/// Define the default level;
/// </summary>
/// <returns></returns>
public IPermissionBuilder DefaultLevel()
{
return Level(1);
}
}
/// <summary>
/// Saves the specified permission
/// </summary>
/// <param name="permission">The permission.</param>
public void Save(Permission permission)
{
permissionRepository.Save(permission);
}
/// <summary>
/// Allow permission for the specified operation.
/// </summary>
/// <param name="operationName">Name of the operation.</param>
/// <returns></returns>
public IForPermissionBuilder Allow(string operationName)
{
Operation operation = authorizationRepository.GetOperationByName(operationName);
Guard.Against<ArgumentException>(operation == null, "There is no operation named: " + operationName);
return Allow(operation);
}
/// <summary>
/// Deny permission for the specified operation
/// </summary>
/// <param name="operationName">Name of the operation.</param>
/// <returns></returns>
public IForPermissionBuilder Deny(string operationName)
{
Operation operation = authorizationRepository.GetOperationByName(operationName);
Guard.Against<ArgumentException>(operation == null, "There is no operation named: " + operationName);
return Deny(operation);
}
/// <summary>
/// Allow permission for the specified operation.
/// </summary>
/// <param name="operation">The operation.</param>
/// <returns></returns>
public IForPermissionBuilder Allow(Operation operation)
{
return new FluentPermissionBuilder(this, true, operation);
}
/// <summary>
/// Deny permission for the specified operation
/// </summary>
/// <param name="operation">The operation.</param>
/// <returns></returns>
public IForPermissionBuilder Deny(Operation operation)
{
return new FluentPermissionBuilder(this, false, operation);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using WebRole.Areas.HelpPage.Models;
namespace WebRole.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 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 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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpClientMiniStress
{
private static bool HttpStressEnabled => Environment.GetEnvironmentVariable("HTTP_STRESS") == "1";
[ConditionalTheory(nameof(HttpStressEnabled))]
[MemberData(nameof(GetStressOptions))]
public void SingleClient_ManyGets_Sync(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
using (var client = new HttpClient())
{
Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ =>
{
CreateServerAndGet(client, completionOption, responseText);
});
}
}
[ConditionalTheory(nameof(HttpStressEnabled))]
public async Task SingleClient_ManyGets_Async(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
using (var client = new HttpClient())
{
await ForCountAsync(numRequests, dop, i => CreateServerAndGetAsync(client, completionOption, responseText));
}
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[MemberData(nameof(GetStressOptions))]
public void ManyClients_ManyGets(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ =>
{
using (var client = new HttpClient())
{
CreateServerAndGet(client, completionOption, responseText);
}
});
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[MemberData(nameof(PostStressOptions))]
public async Task ManyClients_ManyPosts_Async(int numRequests, int dop, int numBytes)
{
string responseText = CreateResponse("");
await ForCountAsync(numRequests, dop, async i =>
{
using (HttpClient client = new HttpClient())
{
await CreateServerAndPostAsync(client, numBytes, responseText);
}
});
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[InlineData(1000000)]
public void CreateAndDestroyManyClients(int numClients)
{
for (int i = 0; i < numClients; i++)
{
new HttpClient().Dispose();
}
}
[ConditionalTheory(nameof(HttpStressEnabled))]
[InlineData(5000)]
public async Task MakeAndFaultManyRequests(int numRequests)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (var client = new HttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
var ep = (IPEndPoint)server.LocalEndPoint;
Task<string>[] tasks =
(from i in Enumerable.Range(0, numRequests)
select client.GetStringAsync($"http://{ep.Address}:{ep.Port}"))
.ToArray();
Assert.All(tasks, t => Assert.Equal(TaskStatus.WaitingForActivation, t.Status));
server.Dispose();
foreach (Task<string> task in tasks)
{
await Assert.ThrowsAnyAsync<HttpRequestException>(() => task);
}
}
}, new LoopbackServer.Options { ListenBacklog = numRequests });
}
public static IEnumerable<object[]> GetStressOptions()
{
foreach (int numRequests in new[] { 5000 }) // number of requests
foreach (int dop in new[] { 1, 32 }) // number of threads
foreach (var completionoption in new[] { HttpCompletionOption.ResponseContentRead, HttpCompletionOption.ResponseHeadersRead })
yield return new object[] { numRequests, dop, completionoption };
}
private static void CreateServerAndGet(HttpClient client, HttpCompletionOption completionOption, string responseText)
{
LoopbackServer.CreateServerAsync((server, url) =>
{
Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption);
LoopbackServer.AcceptSocketAsync(server, (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(reader.ReadLine())) ;
writer.Write(responseText);
writer.Flush();
s.Shutdown(SocketShutdown.Send);
return Task.CompletedTask;
}).GetAwaiter().GetResult();
getAsync.GetAwaiter().GetResult().Dispose();
return Task.CompletedTask;
}).GetAwaiter().GetResult();
}
private static async Task CreateServerAndGetAsync(HttpClient client, HttpCompletionOption completionOption, string responseText)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync().ConfigureAwait(false))) ;
await writer.WriteAsync(responseText).ConfigureAwait(false);
await writer.FlushAsync().ConfigureAwait(false);
s.Shutdown(SocketShutdown.Send);
});
(await getAsync.ConfigureAwait(false)).Dispose();
});
}
public static IEnumerable<object[]> PostStressOptions()
{
foreach (int numRequests in new[] { 5000 }) // number of requests
foreach (int dop in new[] { 1, 32 }) // number of threads
foreach (int numBytes in new[] { 0, 100 }) // number of bytes to post
yield return new object[] { numRequests, dop, numBytes };
}
private static async Task CreateServerAndPostAsync(HttpClient client, int numBytes, string responseText)
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
var content = new ByteArrayContent(new byte[numBytes]);
Task<HttpResponseMessage> postAsync = client.PostAsync(url, content);
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync().ConfigureAwait(false))) ;
for (int i = 0; i < numBytes; i++) Assert.NotEqual(-1, reader.Read());
await writer.WriteAsync(responseText).ConfigureAwait(false);
await writer.FlushAsync().ConfigureAwait(false);
s.Shutdown(SocketShutdown.Send);
});
(await postAsync.ConfigureAwait(false)).Dispose();
});
}
[ConditionalFact(nameof(HttpStressEnabled))]
public async Task UnreadResponseMessage_Collectible()
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (var client = new HttpClient())
{
Func<Task<WeakReference>> getAsync = async () => new WeakReference(await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead));
Task<WeakReference> wrt = getAsync();
await LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) =>
{
while (!string.IsNullOrEmpty(await reader.ReadLineAsync())) ;
await writer.WriteAsync(CreateResponse(new string('a', 32 * 1024)));
await writer.FlushAsync();
WeakReference wr = wrt.GetAwaiter().GetResult();
Assert.True(SpinWait.SpinUntil(() =>
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
return !wr.IsAlive;
}, 10 * 1000), "Response object should have been collected");
});
}
});
}
private static string CreateResponse(string asciiBody) =>
$"HTTP/1.1 200 OK\r\n" +
$"Date: {DateTimeOffset.UtcNow:R}\r\n" +
"Content-Type: text/plain\r\n" +
"Content-Length: {asciiBody.Length}\r\n" +
"\r\n" +
"{asciiBody}\r\n";
private static Task ForCountAsync(int count, int dop, Func<int, Task> bodyAsync)
{
var sched = new ThreadPerTaskScheduler();
int nextAvailableIndex = 0;
return Task.WhenAll(Enumerable.Range(0, dop).Select(_ => Task.Factory.StartNew(async delegate
{
int index;
while ((index = Interlocked.Increment(ref nextAvailableIndex) - 1) < count)
{
try { await bodyAsync(index); }
catch
{
Volatile.Write(ref nextAvailableIndex, count); // avoid any further iterations
throw;
}
}
}, CancellationToken.None, TaskCreationOptions.None, sched).Unwrap()));
}
private sealed class ThreadPerTaskScheduler : TaskScheduler
{
protected override void QueueTask(Task task) =>
Task.Factory.StartNew(() => TryExecuteTask(task), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => TryExecuteTask(task);
protected override IEnumerable<Task> GetScheduledTasks() => null;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Diagnostics
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
class ServiceModelPerformanceCounters
{
Dictionary<string, OperationPerformanceCountersBase> operationPerfCounters;
SortedList<string, string> actionToOperation;
EndpointPerformanceCountersBase endpointPerfCounters;
ServicePerformanceCountersBase servicePerfCounters;
DefaultPerformanceCounters defaultPerfCounters;
bool initialized;
string perfCounterId;
internal ServiceModelPerformanceCounters(
ServiceHostBase serviceHost,
ContractDescription contractDescription,
EndpointDispatcher endpointDispatcher)
{
this.perfCounterId = endpointDispatcher.PerfCounterId;
if (PerformanceCounters.Scope == PerformanceCounterScope.All)
{
this.operationPerfCounters = new Dictionary<string, OperationPerformanceCountersBase>(contractDescription.Operations.Count);
this.actionToOperation = new SortedList<string, string>(contractDescription.Operations.Count);
foreach (OperationDescription opDescription in contractDescription.Operations)
{
Fx.Assert(null != opDescription.Messages, "OperationDescription.Messages should not be null");
Fx.Assert(opDescription.Messages.Count > 0, "OperationDescription.Messages should not be empty");
Fx.Assert(null != opDescription.Messages[0], "OperationDescription.Messages[0] should not be null");
if (null != opDescription.Messages[0].Action && !this.actionToOperation.Keys.Contains(opDescription.Messages[0].Action))
{
this.actionToOperation.Add(opDescription.Messages[0].Action, opDescription.Name);
}
OperationPerformanceCountersBase c;
if (!this.operationPerfCounters.TryGetValue(opDescription.Name, out c))
{
OperationPerformanceCountersBase counters =
PerformanceCountersFactory.CreateOperationCounters(serviceHost.Description.Name, contractDescription.Name, opDescription.Name, endpointDispatcher.PerfCounterBaseId);
if (counters != null && counters.Initialized)
{
this.operationPerfCounters.Add(opDescription.Name, counters);
}
else
{
// cleanup the others and return.
this.initialized = false;
return;
}
}
}
// add endpoint scoped perf counters
EndpointPerformanceCountersBase endpointCounters = PerformanceCountersFactory.CreateEndpointCounters(serviceHost.Description.Name, contractDescription.Name, endpointDispatcher.PerfCounterBaseId);
if (endpointCounters != null && endpointCounters.Initialized)
{
this.endpointPerfCounters = endpointCounters;
}
}
if (PerformanceCounters.PerformanceCountersEnabled)
{
this.servicePerfCounters = serviceHost.Counters;
}
if (PerformanceCounters.MinimalPerformanceCountersEnabled)
{
this.defaultPerfCounters = serviceHost.DefaultCounters;
}
this.initialized = true;
}
internal OperationPerformanceCountersBase GetOperationPerformanceCountersFromMessage(Message message)
{
Fx.Assert(null != message, "message must not be null");
Fx.Assert(null != message.Headers, "message headers must not be null");
Fx.Assert(null != message.Headers.Action, "action must not be null");
string operation;
if (this.actionToOperation.TryGetValue(message.Headers.Action, out operation))
{
return this.GetOperationPerformanceCounters(operation);
}
else
{
return null;
}
}
internal OperationPerformanceCountersBase GetOperationPerformanceCounters(string operation)
{
Fx.Assert(PerformanceCounters.Scope == PerformanceCounterScope.All, "Only call GetOparationPerformanceCounters when performance counter scope is All");
OperationPerformanceCountersBase counters;
Dictionary<string, OperationPerformanceCountersBase> opPerfCounters = this.operationPerfCounters;
if (opPerfCounters != null && opPerfCounters.TryGetValue(operation, out counters))
{
return counters;
}
return null;
}
internal bool Initialized
{
get { return this.initialized; }
}
internal EndpointPerformanceCountersBase EndpointPerformanceCounters
{
get { return this.endpointPerfCounters; }
}
internal ServicePerformanceCountersBase ServicePerformanceCounters
{
get { return this.servicePerfCounters; }
}
internal DefaultPerformanceCounters DefaultPerformanceCounters
{
get { return this.defaultPerfCounters; }
}
internal string PerfCounterId
{
get { return this.perfCounterId; }
}
}
internal class ServiceModelPerformanceCountersEntry
{
ServicePerformanceCountersBase servicePerformanceCounters;
DefaultPerformanceCounters defaultPerformanceCounters;
List<ServiceModelPerformanceCounters> performanceCounters;
public ServiceModelPerformanceCountersEntry(ServicePerformanceCountersBase serviceCounters)
{
this.servicePerformanceCounters = serviceCounters;
this.performanceCounters = new List<ServiceModelPerformanceCounters>();
}
public ServiceModelPerformanceCountersEntry(DefaultPerformanceCounters defaultServiceCounters)
{
this.defaultPerformanceCounters = defaultServiceCounters;
this.performanceCounters = new List<ServiceModelPerformanceCounters>();
}
public void Add(ServiceModelPerformanceCounters counters)
{
this.performanceCounters.Add(counters);
}
public void Remove(string id)
{
for (int i = 0; i < this.performanceCounters.Count; ++i)
{
if (this.performanceCounters[i].PerfCounterId.Equals(id))
{
this.performanceCounters.RemoveAt(i);
break;
}
}
}
public void Clear()
{
this.performanceCounters.Clear();
}
public ServicePerformanceCountersBase ServicePerformanceCounters
{
get { return this.servicePerformanceCounters; }
set { this.servicePerformanceCounters = value; }
}
public DefaultPerformanceCounters DefaultPerformanceCounters
{
get { return this.defaultPerformanceCounters; }
set { this.defaultPerformanceCounters = value; }
}
public List<ServiceModelPerformanceCounters> CounterList
{
get { return this.performanceCounters; }
}
}
}
| |
// <file>
// <copyright see=""/>
// <license see=""/>
// <owner name="Youseful Software" email="support@youseful.com"/>
// <version value="$version"/>
// </file>
using System;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
//using Youseful.Installer.Nativemsi;
using Youseful.Exceptions.Win32;
/* A High Level Wrapper for msi.dll */
namespace Youseful.Installer.WI.Nativemsi.Exceptions
{
#region Exception Types
[Serializable]
public class MsiException : Exception, ISerializable
{
private string _ErrorMessage;
public MsiException (string errorMessage) : base(errorMessage)
{
}
public MsiException () : base()
{
}
public MsiException (string errorMessage, Exception innerException)
: base(errorMessage, innerException)
{
}
public string ErrorMessage { get { return _ErrorMessage;}}
public override string Message
{
get
{
string msg = base.Message;
if (_ErrorMessage != null)
msg += Environment.NewLine + "WI API: " + _ErrorMessage;
return msg;
}
}
protected MsiException(SerializationInfo info,
StreamingContext context) : base(info, context)
{
_ErrorMessage = info.GetString("ErrorMessage");
}
void ISerializable.GetObjectData(SerializationInfo info,
StreamingContext context)
{
info.AddValue("ErrorMessage",_ErrorMessage);
base.GetObjectData(info,context);
}
public MsiException(string message, string errormessage,
Exception innerException) : this(message, innerException)
{
this._ErrorMessage = errormessage;
}
}
[Serializable]
sealed public class MsiDBException : MsiException, ISerializable
{
private string _ErrorMessage;
public MsiDBException (string errorMessage) : base(errorMessage)
{
}
public MsiDBException () : base()
{
}
public MsiDBException (string errorMessage, Exception innerException)
: base(errorMessage, innerException)
{
}
public string ErrorMessage { get { return _ErrorMessage;}}
public override string Message
{
get
{
string msg = base.Message;
if (_ErrorMessage != null)
msg += Environment.NewLine + "WI DB API: " + _ErrorMessage;
return msg;
}
}
protected MsiDBException(SerializationInfo info,
StreamingContext context) : base(info, context)
{
_ErrorMessage = info.GetString("ErrorMessage");
}
void ISerializable.GetObjectData(SerializationInfo info,
StreamingContext context)
{
info.AddValue("ErrorMessage",_ErrorMessage);
base.GetObjectData(info,context);
}
public MsiDBException(string message, string errormessage,
Exception innerException) : this(message, innerException)
{
this._ErrorMessage = errormessage;
}
}
#endregion
#region Low Level Exception Classes
sealed public class MsiCheckAll
{
//private MsiCheck Check;
//private MsiDBCheck DBCheck;
/* public MsiCheckAll ()
{
//Check = new MsiCheck();
//DBCheck = new MsiDBCheck();
}
public void CheckEx (long ErrorCode)
{
//Check.CheckEx(ErrorCode);
//DBCheck.CheckEx(Convert.ToInt32(ErrorCode));
}*/
/// <summary>
/// Checks and calls appropiate exceptions
/// </summary>
public static void CheckAll (long ErrorCode)
{
MsiCheck.CheckEx(ErrorCode);
MsiDBCheck.CheckEx(Convert.ToInt32(ErrorCode));
Win32Check.CheckEx(ErrorCode);
}
}
#region MsiCheck
public class MsiCheck
{
// --------------------------------------------------------------------------
// Error codes for installer access functions - until merged to winerr.h
// --------------------------------------------------------------------------
///ifndef ERROR_INSTALL_FAILURE
public const long ERROR_INSTALL_USEREXIT = 1602L; // User cancel installation.
public const long ERROR_INSTALL_FAILURE = 1603L; // Fatal error during installation.
public const long ERROR_INSTALL_SUSPEND = 1604L; // Installation suspended, incomplete.
// LOCALIZE BEGIN:
public const long ERROR_UNKNOWN_PRODUCT = 1605L; // This action is only valid for products that are currently installed.
// LOCALIZE END
public const long ERROR_UNKNOWN_FEATURE = 1606L; // Feature ID not registered.
public const long ERROR_UNKNOWN_COMPONENT = 1607L; // Component ID not registered.
public const long ERROR_UNKNOWN_PROPERTY = 1608L; // Unknown property.
public const long ERROR_INVALID_HANDLE_STATE = 1609L; // Handle is in an invalid state.
// LOCALIZE BEGIN:
public const long ERROR_BAD_CONFIGURATION = 1610L; // The configuration data for this product is corrupt. Contact your support personnel.
// LOCALIZE END:
public const long ERROR_INDEX_ABSENT = 1611L; // Component qualifier not present.
// LOCALIZE BEGIN:
public const long ERROR_INSTALL_SOURCE_ABSENT = 1612L; // The installation source for this product is not available. Verify that the source exists and that you can access it.
// LOCALIZE END;;
public const long ERROR_PRODUCT_UNINSTALLED = 1614L; // Product is uninstalled.
public const long ERROR_BAD_QUERY_SYNTAX = 1615L; // SQL query syntax invalid or unsupported.
public const long ERROR_INVALID_FIELD = 1616L; // Record field does not exist.
//endif
// LOCALIZE BEGIN:
//ifndef ERROR_INSTALL_SERVICE_FAILURE
public const long ERROR_INSTALL_SERVICE_FAILURE = 1601L; // The Windows Installer service could not be accessed. Contact your support personnel to verify that the Windows Installer service is properly registered.
public const long ERROR_INSTALL_PACKAGE_VERSION = 1613L; // This installation package cannot be installed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.
public const long ERROR_INSTALL_ALREADY_RUNNING = 1618L; // Another installation is already in progress. Complete that installation before proceeding with this install.
public const long ERROR_INSTALL_PACKAGE_OPEN_FAILED = 1619L; // This installation package could not be opened. Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package.
public const long ERROR_INSTALL_PACKAGE_INVALID = 1620L; // This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package.
public const long ERROR_INSTALL_UI_FAILURE = 1621L; // There was an error starting the Windows Installer service user interface. Contact your support personnel.
public const long ERROR_INSTALL_LOG_FAILURE = 1622L; // Error opening installation log file. Verify that the specified log file location exists and is writable.
public const long ERROR_INSTALL_LANGUAGE_UNSUPPORTED = 1623L; // This language of this installation package is not supported by your system.
public const long ERROR_INSTALL_PACKAGE_REJECTED = 1625L; // The system administrator has set policies to prevent this installation.
// LOCALIZE END
public const long ERROR_FUNCTION_NOT_CALLED = 1626L; // Function could not be executed.
public const long ERROR_FUNCTION_FAILED = 1627L; // Function failed during execution.
public const long ERROR_INVALID_TABLE = 1628L; // Invalid or unknown table specified.
public const long ERROR_DATATYPE_MISMATCH = 1629L; // Data supplied is of wrong type.
public const long ERROR_UNSUPPORTED_TYPE = 1630L; // Data of this type is not supported.
// LOCALIZE BEGIN:;
public const long ERROR_CREATE_FAILED = 1631L; // The Windows Installer service failed to start. Contact your support personnel.
// LOCALIZE END:
//endif
// LOCALIZE BEGIN:
//ifndef ERROR_INSTALL_TEMP_UNWRITABLE
public const long ERROR_INSTALL_TEMP_UNWRITABLE = 1632L; // The Temp folder is on a drive that is full or is inaccessible. Free up space on the drive or verify that you have write permission on the Temp folder.
//endif
//ifndef ERROR_INSTALL_PLATFORM_UNSUPPORTED
public const long ERROR_INSTALL_PLATFORM_UNSUPPORTED = 1633L; // This installation package is not supported by this processor type. Contact your product vendor.
// endif
// LOCALIZE END
//ifndef ERROR_INSTALL_NOTUSED
public const long ERROR_INSTALL_NOTUSED = 1634L; // Component not used on this machine
//endif
// LOCALIZE BEGIN:
//ifndef ERROR_INSTALL_TRANSFORM_FAILURE
public const long ERROR_INSTALL_TRANSFORM_FAILURE = 1624L; // Error applying transforms. Verify that the specified transform paths are valid.
//endif
//ifndef ERROR_PATCH_PACKAGE_OPEN_FAILED
public const long ERROR_PATCH_PACKAGE_OPEN_FAILED = 1635L; // This patch package could not be opened. Verify that the patch package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer patch package.
public const long ERROR_PATCH_PACKAGE_INVALID = 1636L; // This patch package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer patch package.
public const long ERROR_PATCH_PACKAGE_UNSUPPORTED = 1637L; // This patch package cannot be processed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.
//endif
//ndef ERROR_PRODUCT_VERSION
public const long ERROR_PRODUCT_VERSION = 1638L;// Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs on the Control Panel.
//endif
//ifndef ERROR_INVALID_COMMAND_LINE
public const long ERROR_INVALID_COMMAND_LINE = 1639L; // Invalid command line argument. Consult the Windows Installer SDK for detailed command line help.
//endif
// The following three error codes are not returned from MSI version 1.0
//ifndef ERROR_INSTALL_REMOTE_DISALLOWED
public const long ERROR_INSTALL_REMOTE_DISALLOWED = 1640L; // Configuration of this product is not permitted from remote sessions. Contact your administrator.
//endif
// LOCALIZE END
//ifndef ERROR_SUCCESS_REBOOT_INITIATED
public const long ERROR_SUCCESS_REBOOT_INITIATED = 1641L; // The requested operation completed successfully. The system will be restarted so the changes can take effect.
//endif
// LOCALIZE BEGIN:
//ifndef ERROR_PATCH_TARGET_NOT_FOUND
public const long ERROR_PATCH_TARGET_NOT_FOUND = 1642L; // The upgrade patch cannot be installed by the Windows Installer service because the program to be upgraded may be missing, or the upgrade patch may update a different version of the program. Verify that the program to be upgraded exists on your computer and that you have the correct upgrade patch.
//endif
// LOCALIZE END
// The following two error codes are not returned from MSI version 1.0, 1.1. or 1.2
// LOCALIZE BEGIN:
//ifndef ERROR_PATCH_PACKAGE_REJECTED
public const long ERROR_PATCH_PACKAGE_REJECTED = 1643L; // The patch package is not permitted by system policy. It is not signed with an appropriate certificate.
//endif
//ifndef ERROR_INSTALL_TRANSFORM_REJECTED
public const long ERROR_INSTALL_TRANSFORM_REJECTED = 1644L; // One or more customizations are not permitted by system policy. They are not signed with an appropriate certificate.
//endif
// LOCALIZE END
public MsiCheck ()
{
}
public static void CheckEx (long ErrorCode)
{
switch(ErrorCode)
{
case ERROR_INSTALL_USEREXIT :
throw new MsiException("User cancel installation.");
case ERROR_INSTALL_FAILURE :
throw new MsiException("Fatal error during installation.");
case ERROR_INSTALL_SUSPEND :
throw new MsiException("Installation suspended, incomplete.");
case ERROR_UNKNOWN_PRODUCT :
throw new MsiException("This action is only valid for products that are currently installed.");
case ERROR_UNKNOWN_FEATURE :
throw new MsiException("Feature ID not registered.");
case ERROR_UNKNOWN_COMPONENT :
throw new MsiException("Component ID not registered.");
case ERROR_UNKNOWN_PROPERTY :
throw new MsiException("Unknown property.");
case ERROR_INVALID_HANDLE_STATE :
throw new MsiException("Handle is in an invalid state.");
case ERROR_BAD_CONFIGURATION :
throw new MsiException("The configuration data for this product is corrupt. Contact your support personnel.");
case ERROR_INDEX_ABSENT :
throw new MsiException("Component qualifier not present.");
case ERROR_INSTALL_SOURCE_ABSENT :
throw new MsiException("The installation source for this product is not available. Verify that the source exists and that you can access it.");
case ERROR_PRODUCT_UNINSTALLED :
throw new MsiException("Product is uninstalled.");
case ERROR_BAD_QUERY_SYNTAX :
throw new MsiException("SQL query syntax invalid or unsupported.");
case ERROR_INVALID_FIELD :
throw new MsiException("Record field does not exist.");
case ERROR_INSTALL_SERVICE_FAILURE :
throw new MsiException("The Windows Installer service could not be accessed. Contact your support personnel to verify that the Windows Installer service is properly registered.");
case ERROR_INSTALL_PACKAGE_VERSION :
throw new MsiException("This installation package cannot be installed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.");
case ERROR_INSTALL_ALREADY_RUNNING :
throw new MsiException("Another installation is already in progress. Complete that installation before proceeding with this install.");
case ERROR_INSTALL_PACKAGE_OPEN_FAILED :
throw new MsiException("This installation package could not be opened. Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package.");
case ERROR_INSTALL_PACKAGE_INVALID :
throw new MsiException("This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package.");
case ERROR_INSTALL_UI_FAILURE :
throw new MsiException("There was an error starting the Windows Installer service user interface. Contact your support personnel.");
case ERROR_INSTALL_LOG_FAILURE :
throw new MsiException("Error opening installation log file. Verify that the specified log file location exists and is writable.");
case ERROR_INSTALL_LANGUAGE_UNSUPPORTED :
throw new MsiException("This language of this installation package is not supported by your system.");
case ERROR_INSTALL_PACKAGE_REJECTED :
throw new MsiException("The system administrator has set policies to prevent this installation.");
case ERROR_FUNCTION_NOT_CALLED :
throw new MsiException("Function could not be executed.");
case ERROR_FUNCTION_FAILED :
throw new MsiException(" Function failed during execution.");
case ERROR_INVALID_TABLE :
throw new MsiException("Invalid or unknown table specified.");
case ERROR_DATATYPE_MISMATCH :
throw new MsiException("Data supplied is of wrong type.");
case ERROR_UNSUPPORTED_TYPE :
throw new MsiException("Data of this type is not supported.");
case ERROR_CREATE_FAILED :
throw new MsiException("The Windows Installer service failed to start. Contact your support personnel.");
case ERROR_INSTALL_TEMP_UNWRITABLE :
throw new MsiException("The Temp folder is on a drive that is full or is inaccessible. Free up space on the drive or verify that you have write permission on the Temp folder.");
case ERROR_INSTALL_PLATFORM_UNSUPPORTED :
throw new MsiException("This installation package is not supported by this processor type. Contact your product vendor.");
case ERROR_INSTALL_NOTUSED :
throw new MsiException("Component not used on this machine");
case ERROR_INSTALL_TRANSFORM_FAILURE :
throw new MsiException("Error applying transforms. Verify that the specified transform paths are valid.");
case ERROR_PATCH_PACKAGE_OPEN_FAILED :
throw new MsiException("This patch package could not be opened. Verify that the patch package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer patch package.");
case ERROR_PATCH_PACKAGE_INVALID :
throw new MsiException("This patch package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer patch package.");
case ERROR_PATCH_PACKAGE_UNSUPPORTED :
throw new MsiException("This patch package cannot be processed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service.");
case ERROR_PRODUCT_VERSION :
throw new MsiException("Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs on the Control Panel.");
case ERROR_INVALID_COMMAND_LINE :
throw new MsiException("Invalid command line argument. Consult the Windows Installer SDK for detailed command line help.");
case ERROR_INSTALL_REMOTE_DISALLOWED :
throw new MsiException("Configuration of this product is not permitted from remote sessions. Contact your administrator.");
case ERROR_SUCCESS_REBOOT_INITIATED :
throw new MsiException("The requested operation completed successfully. The system will be restarted so the changes can take effect.");
case ERROR_PATCH_TARGET_NOT_FOUND :
throw new MsiException("The upgrade patch cannot be installed by the Windows Installer service because the program to be upgraded may be missing, or the upgrade patch may update a different version of the program. Verify that the program to be upgraded exists on your computer and that you have the correct upgrade patch.");
case ERROR_PATCH_PACKAGE_REJECTED :
throw new MsiException("The patch package is not permitted by system policy. It is not signed with an appropriate certificate.");
case ERROR_INSTALL_TRANSFORM_REJECTED :
throw new MsiException("One or more customizations are not permitted by system policy. They are not signed with an appropriate certificate.");
}
}
~MsiCheck()
{
}
}
#endregion
#region MsiDBCheck
public class MsiDBCheck
{
// public enum MSIDBERROR : int
// {
public const int MSIDBERROR_INVALIDARG = -3; // invalid argument
public const int MSIDBERROR_MOREDATA = -2; // buffer too small
public const int MSIDBERROR_FUNCTIONERROR = -1; // function error
public const int MSIDBERROR_NOERROR = 0; // no error
public const int MSIDBERROR_DUPLICATEKEY = 1; // new record duplicates primary keys of existing record in table
public const int MSIDBERROR_REQUIRED = 2; // non-nullable column; no null values allowed
public const int MSIDBERROR_BADLINK = 3; // corresponding record in foreign table not found
public const int MSIDBERROR_OVERFLOW = 4; // data greater than maximum value allowed
public const int MSIDBERROR_UNDERFLOW = 5; // data less than minimum value allowed
public const int MSIDBERROR_NOTINSET = 6; // data not a member of the values permitted in the set
public const int MSIDBERROR_BADVERSION = 7; // invalid version string
public const int MSIDBERROR_BADCASE = 8; // invalid case; must be all upper-case or all lower-case
public const int MSIDBERROR_BADGUID = 9; // invalid GUID
public const int MSIDBERROR_BADWILDCARD = 10; // invalid wildcardfilename or use of wildcards
public const int MSIDBERROR_BADIDENTIFIER = 11; // bad identifier
public const int MSIDBERROR_BADLANGUAGE = 12; // bad language Id(s)
public const int MSIDBERROR_BADFILENAME = 13; // bad filename
public const int MSIDBERROR_BADPATH = 14; // bad path
public const int MSIDBERROR_BADCONDITION = 15; // bad conditional statement
public const int MSIDBERROR_BADFORMATTED = 16; // bad format string
public const int MSIDBERROR_BADTEMPLATE = 17; // bad template string
public const int MSIDBERROR_BADDEFAULTDIR = 18; // bad string in DefaultDir column of Directory table
public const int MSIDBERROR_BADREGPATH = 19; // bad registry path string
public const int MSIDBERROR_BADCUSTOMSOURCE = 20; // bad string in CustomSource column of CustomAction table
public const int MSIDBERROR_BADPROPERTY = 21; // bad property string
public const int MSIDBERROR_MISSINGDATA = 22; // _Validation table missing reference to column
public const int MSIDBERROR_BADCATEGORY = 23; // Category column of _Validation table for column is invalid
public const int MSIDBERROR_BADKEYTABLE = 24; // table in KeyTable column of _Validation table could not be found/loaded
public const int MSIDBERROR_BADMAXMINVALUES = 25; // value in MaxValue column of _Validation table is less than value in MinValue column
public const int MSIDBERROR_BADCABINET = 26; // bad cabinet name
public const int MSIDBERROR_BADSHORTCUT = 27; // bad shortcut target
public const int MSIDBERROR_STRINGOVERFLOW = 28; // string overflow (greater than length allowed in column def)
public const int MSIDBERROR_BADLOCALIZEATTRIB = 29; // invalid localization attribute (primary keys cannot be localized)
//}
public MsiDBCheck ()
{
}
public static void CheckEx (int ErrorCode)
{
switch(ErrorCode)
{
case MSIDBERROR_INVALIDARG :
throw new MsiDBException("invalid argument");
case MSIDBERROR_MOREDATA :
throw new MsiDBException("buffer too small");
case MSIDBERROR_FUNCTIONERROR :
throw new MsiDBException("function error");
//case MSIDBERROR_NOERROR :
// throw new MsiException("no error");
case MSIDBERROR_DUPLICATEKEY :
throw new MsiDBException("new record duplicates primary keys of existing record in table");
case MSIDBERROR_REQUIRED :
throw new MsiDBException("non-nullable column, no null values allowed");
case MSIDBERROR_BADLINK :
throw new MsiDBException("corresponding record in foreign table not found");
case MSIDBERROR_OVERFLOW :
throw new MsiDBException("data greater than maximum value allowed");
case MSIDBERROR_UNDERFLOW :
throw new MsiDBException("data less than minimum value allowed");
case MSIDBERROR_NOTINSET :
throw new MsiDBException("data not a member of the values permitted in the set");
case MSIDBERROR_BADVERSION :
throw new MsiDBException("invalid version string");
case MSIDBERROR_BADCASE :
throw new MsiDBException("invalid case, must be all upper-case or all lower-case");
case MSIDBERROR_BADGUID :
throw new MsiDBException("invalid GUID");
case MSIDBERROR_BADWILDCARD :
throw new MsiDBException("invalid wildcardfilename or use of wildcards");
case MSIDBERROR_BADIDENTIFIER :
throw new MsiDBException("bad identifier");
case MSIDBERROR_BADLANGUAGE :
throw new MsiDBException("bad language Id(s)");
case MSIDBERROR_BADFILENAME :
throw new MsiDBException("bad filename");
case MSIDBERROR_BADPATH :
throw new MsiDBException("bad path");
case MSIDBERROR_BADCONDITION :
throw new MsiDBException("bad conditional statement");
case MSIDBERROR_BADFORMATTED :
throw new MsiDBException("bad format string");
case MSIDBERROR_BADTEMPLATE :
throw new MsiDBException("bad template string");
case MSIDBERROR_BADDEFAULTDIR :
throw new MsiDBException("bad string in DefaultDir column of Directory table");
case MSIDBERROR_BADREGPATH :
throw new MsiDBException("bad registry path string");
case MSIDBERROR_BADCUSTOMSOURCE :
throw new MsiDBException("bad string in CustomSource column of CustomAction table");
case MSIDBERROR_BADPROPERTY :
throw new MsiDBException("bad property string");
case MSIDBERROR_MISSINGDATA :
throw new MsiDBException("Validation table missing reference to column");
case MSIDBERROR_BADCATEGORY :
throw new MsiDBException("Category column of _Validation table for column is invalid");
case MSIDBERROR_BADKEYTABLE :
throw new MsiDBException("table in KeyTable column of _Validation table could not be found/loaded");
case MSIDBERROR_BADMAXMINVALUES :
throw new MsiDBException("value in MaxValue column of _Validation table is less than value in MinValue column");
case MSIDBERROR_BADCABINET :
throw new MsiDBException("bad cabinet name");
case MSIDBERROR_BADSHORTCUT :
throw new MsiDBException("bad shortcut target");
case MSIDBERROR_STRINGOVERFLOW :
throw new MsiDBException("string overflow (greater than length allowed in column def)");
case MSIDBERROR_BADLOCALIZEATTRIB :
throw new MsiDBException("invalid localization attribute (primary keys cannot be localized)");
} // switch(ErrorCode)
}
~MsiDBCheck()
{
}
}
#endregion
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Encryption.TripleDes.Tests
{
public static class TripleDESCipherTests
{
[Fact]
public static void TripleDESDefaults()
{
using (TripleDES des = TripleDESFactory.Create())
{
Assert.Equal(192, des.KeySize);
Assert.Equal(64, des.BlockSize);
}
}
[Fact]
public static void TripleDESGenerate128Key()
{
using (TripleDES des = TripleDESFactory.Create())
{
des.KeySize = 128;
byte[] key = des.Key;
Assert.Equal(128, key.Length * 8);
}
}
[Fact]
public static void TripleDESInvalidKeySizes()
{
using (TripleDES des = TripleDESFactory.Create())
{
Assert.Throws<CryptographicException>(() => des.KeySize = 128 - des.BlockSize);
Assert.Throws<CryptographicException>(() => des.KeySize = 192 + des.BlockSize);
}
}
[Theory]
[InlineData(192, "e56f72478c7479d169d54c0548b744af5b53efb1cdd26037", "c5629363d957054eba793093b83739bb78711db221a82379")]
[InlineData(128, "1387b981dbb40f34b915c4ed89fd681a740d3b4869c0b575", "c5629363d957054eba793093b83739bb")]
[InlineData(192, "1387b981dbb40f34b915c4ed89fd681a740d3b4869c0b575", "c5629363d957054eba793093b83739bbc5629363d957054e")]
public static void TripleDESRoundTripNoneECB(int keySize, string expectedCipherHex, string keyHex)
{
byte[] key = keyHex.HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
Assert.Equal(keySize, alg.KeySize);
alg.Padding = PaddingMode.None;
alg.Mode = CipherMode.ECB;
byte[] plainText = "de7d2dddea96b691e979e647dc9d3ca27d7f1ad673ca9570".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = expectedCipherHex.HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "de7d2dddea96b691e979e647dc9d3ca27d7f1ad673ca9570".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Theory]
[InlineData(192, "dea36279600f19c602b6ed9bf3ffdac5ebf25c1c470eb61c", "b43eaf0260813fb47c87ae073a146006d359ad04061eb0e6")]
[InlineData(128, "a25e55381f0cc45541741b9ce6e96b7799aa1e0db70780f7", "b43eaf0260813fb47c87ae073a146006")]
[InlineData(192, "a25e55381f0cc45541741b9ce6e96b7799aa1e0db70780f7", "b43eaf0260813fb47c87ae073a146006b43eaf0260813fb4")]
public static void TripleDESRoundTripNoneCBC(int keySize, string expectedCipherHex, string keyHex)
{
byte[] key = keyHex.HexToByteArray();
byte[] iv = "5fbc5bc21b8597d8".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
Assert.Equal(keySize, alg.KeySize);
alg.IV = iv;
alg.Padding = PaddingMode.None;
alg.Mode = CipherMode.CBC;
byte[] plainText = "79a86903608e133e020e1dc68c9835250c2f17b0ebeed91b".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = expectedCipherHex.HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "79a86903608e133e020e1dc68c9835250c2f17b0ebeed91b".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Theory]
[InlineData(192, "149ec32f558b27c7e4151e340d8184f18b4e25d2518f69d9", "9da5b265179d65f634dfc95513f25094411e51bb3be877ef")]
[InlineData(128, "02ac5db31cfada874f6042c4e92b09175fd08e93a20f936b", "9da5b265179d65f634dfc95513f25094")]
[InlineData(192, "02ac5db31cfada874f6042c4e92b09175fd08e93a20f936b", "9da5b265179d65f634dfc95513f250949da5b265179d65f6")]
public static void TripleDESRoundTripZerosECB(int keySize, string expectedCipherHex, string keyHex)
{
byte[] key = keyHex.HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
Assert.Equal(keySize, alg.KeySize);
alg.Padding = PaddingMode.Zeros;
alg.Mode = CipherMode.ECB;
byte[] plainText = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = expectedCipherHex.HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8000000".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Theory]
[InlineData(192, "9da5b265179d65f634dfc95513f25094411e51bb3be877ef")]
[InlineData(128, "9da5b265179d65f634dfc95513f25094")]
[InlineData(192, "9da5b265179d65f634dfc95513f250949da5b265179d65f6")]
public static void TripleDESRoundTripISO10126ECB(int keySize, string keyHex)
{
byte[] key = keyHex.HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
Assert.Equal(keySize, alg.KeySize);
alg.Padding = PaddingMode.ISO10126;
alg.Mode = CipherMode.ECB;
byte[] plainText = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
// the padding data for ISO10126 is made up of random bytes, so we cannot actually test
// the full encrypted text. We need to strip the padding and then compare
byte[] decrypted = alg.Decrypt(cipher);
Assert.Equal<byte>(plainText, decrypted);
}
}
[Theory]
[InlineData(192, "149ec32f558b27c7e4151e340d8184f1c90f0a499e20fda9", "9da5b265179d65f634dfc95513f25094411e51bb3be877ef")]
[InlineData(128, "02ac5db31cfada874f6042c4e92b091783620e54a1e75957", "9da5b265179d65f634dfc95513f25094")]
[InlineData(192, "02ac5db31cfada874f6042c4e92b091783620e54a1e75957", "9da5b265179d65f634dfc95513f250949da5b265179d65f6")]
public static void TripleDESRoundTripANSIX923ECB(int keySize, string expectedCipherHex, string keyHex)
{
byte[] key = keyHex.HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
Assert.Equal(keySize, alg.KeySize);
alg.Padding = PaddingMode.ANSIX923;
alg.Mode = CipherMode.ECB;
byte[] plainText = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = expectedCipherHex.HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray();
Assert.Equal<byte>(plainText, decrypted);
}
}
[Fact]
public static void TripleDES_FailureToRoundTrip192Bits_DifferentPadding_ANSIX923_ZerosECB()
{
byte[] key = "9da5b265179d65f634dfc95513f25094411e51bb3be877ef".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
alg.Padding = PaddingMode.ANSIX923;
alg.Mode = CipherMode.ECB;
byte[] plainText = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = "149ec32f558b27c7e4151e340d8184f1c90f0a499e20fda9".HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
alg.Padding = PaddingMode.Zeros;
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray();
// They should not decrypt to the same value
Assert.NotEqual<byte>(plainText, decrypted);
}
}
[Theory]
[InlineData(192, "65f3dc211876a9daad238aa7d0c7ed7a3662296faf77dff9", "5e970c0d2323d53b28fa3de507d6d20f9f0cd97123398b4d")]
[InlineData(128, "2f55ff6bd8270f1d68dcb342bb674f914d9e1c0e61017a77", "5e970c0d2323d53b28fa3de507d6d20f")]
[InlineData(192, "2f55ff6bd8270f1d68dcb342bb674f914d9e1c0e61017a77", "5e970c0d2323d53b28fa3de507d6d20f5e970c0d2323d53b")]
public static void TripleDESRoundTripZerosCBC(int keySize, string expectedCipherHex, string keyHex)
{
byte[] key = keyHex.HexToByteArray();
byte[] iv = "95498b5bf570f4c8".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
Assert.Equal(keySize, alg.KeySize);
alg.IV = iv;
alg.Padding = PaddingMode.Zeros;
alg.Mode = CipherMode.CBC;
byte[] plainText = "f9e9a1385bf3bd056d6a06eac662736891bd3e6837".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = expectedCipherHex.HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "f9e9a1385bf3bd056d6a06eac662736891bd3e6837000000".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Theory]
[InlineData(192, "7b8d982ee0c14821daf1b8cf4e407c2eb328627b696ac36e", "155425f12109cd89378795a4ca337b3264689dca497ba2fa")]
[InlineData(128, "ce7daa4723c4f880fb44c2809821fc2183b46f0c32084620", "155425f12109cd89378795a4ca337b32")]
[InlineData(192, "ce7daa4723c4f880fb44c2809821fc2183b46f0c32084620", "155425f12109cd89378795a4ca337b32155425f12109cd89")]
public static void TripleDESRoundTripPKCS7ECB(int keySize, string expectedCipherHex, string keyHex)
{
byte[] key = keyHex.HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
Assert.Equal(keySize, alg.KeySize);
alg.Padding = PaddingMode.PKCS7;
alg.Mode = CipherMode.ECB;
byte[] plainText = "5bd3c4e16a723a17ac60dd0efdb158e269cddfd0fa".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = expectedCipherHex.HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "5bd3c4e16a723a17ac60dd0efdb158e269cddfd0fa".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Theory]
[InlineData(192, "446f57875e107702afde16b57eaf250b87b8110bef29af89", "6b42da08f93e819fbd26fce0785b0eec3d0cb6bfa053c505")]
[InlineData(128, "ebf995606ceceddf5c90a7302521bc1f6d31f330969cb768", "6b42da08f93e819fbd26fce0785b0eec")]
[InlineData(192, "ebf995606ceceddf5c90a7302521bc1f6d31f330969cb768", "6b42da08f93e819fbd26fce0785b0eec6b42da08f93e819f")]
public static void TripleDESRoundTripPKCS7CBC(int keySize, string expectedCipherHex, string keyHex)
{
byte[] key = keyHex.HexToByteArray();
byte[] iv = "8fc67ce5e7f28cde".HexToByteArray();
using (TripleDES alg = TripleDESFactory.Create())
{
alg.Key = key;
Assert.Equal(keySize, alg.KeySize);
alg.IV = iv;
alg.Padding = PaddingMode.PKCS7;
alg.Mode = CipherMode.CBC;
byte[] plainText = "e867f915e275eab27d6951165d26dec6dd0acafcfc".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = expectedCipherHex.HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "e867f915e275eab27d6951165d26dec6dd0acafcfc".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void EncryptWithLargeOutputBuffer(bool blockAlignedOutput)
{
using (TripleDES alg = TripleDESFactory.Create())
using (ICryptoTransform xform = alg.CreateEncryptor())
{
// 8 blocks, plus maybe three bytes
int outputPadding = blockAlignedOutput ? 0 : 3;
byte[] output = new byte[alg.BlockSize + outputPadding];
// 2 blocks of 0x00
byte[] input = new byte[alg.BlockSize / 4];
int outputOffset = 0;
outputOffset += xform.TransformBlock(input, 0, input.Length, output, outputOffset);
byte[] overflow = xform.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
Buffer.BlockCopy(overflow, 0, output, outputOffset, overflow.Length);
outputOffset += overflow.Length;
Assert.Equal(3 * (alg.BlockSize / 8), outputOffset);
string outputAsHex = output.ByteArrayToHex();
Assert.NotEqual(new string('0', outputOffset * 2), outputAsHex.Substring(0, outputOffset * 2));
Assert.Equal(new string('0', (output.Length - outputOffset) * 2), outputAsHex.Substring(outputOffset * 2));
}
}
[Theory]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public static void TransformWithTooShortOutputBuffer(bool encrypt, bool blockAlignedOutput)
{
using (TripleDES alg = TripleDESFactory.Create())
using (ICryptoTransform xform = encrypt ? alg.CreateEncryptor() : alg.CreateDecryptor())
{
// 1 block, plus maybe three bytes
int outputPadding = blockAlignedOutput ? 0 : 3;
byte[] output = new byte[alg.BlockSize / 8 + outputPadding];
// 3 blocks of 0x00
byte[] input = new byte[3 * (alg.BlockSize / 8)];
Type exceptionType = typeof(ArgumentOutOfRangeException);
// TripleDESCryptoServiceProvider doesn't throw the ArgumentOutOfRangeException,
// giving a CryptographicException when CAPI reports the destination too small.
if (PlatformDetection.IsFullFramework)
{
exceptionType = typeof(CryptographicException);
}
Assert.Throws(
exceptionType,
() => xform.TransformBlock(input, 0, input.Length, output, 0));
Assert.Equal(new byte[output.Length], output);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void MultipleBlockDecryptTransform(bool blockAlignedOutput)
{
const string ExpectedOutput = "This is a test";
int outputPadding = blockAlignedOutput ? 0 : 3;
byte[] key = "0123456789ABCDEFFEDCBA9876543210ABCDEF0123456789".HexToByteArray();
byte[] iv = "0123456789ABCDEF".HexToByteArray();
byte[] outputBytes = new byte[iv.Length * 2 + outputPadding];
byte[] input = "A61C8F1D393202E1E3C71DCEAB9B08DB".HexToByteArray();
int outputOffset = 0;
using (TripleDES alg = TripleDESFactory.Create())
using (ICryptoTransform xform = alg.CreateDecryptor(key, iv))
{
Assert.Equal(2 * alg.BlockSize, (outputBytes.Length - outputPadding) * 8);
outputOffset += xform.TransformBlock(input, 0, input.Length, outputBytes, outputOffset);
byte[] overflow = xform.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
Buffer.BlockCopy(overflow, 0, outputBytes, outputOffset, overflow.Length);
outputOffset += overflow.Length;
}
string decrypted = Encoding.ASCII.GetString(outputBytes, 0, outputOffset);
Assert.Equal(ExpectedOutput, decrypted);
}
}
}
| |
// 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.Runtime;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.Runtime
{
// Fundamental runtime type representation
internal unsafe struct EEType
{
[StructLayout(LayoutKind.Explicit)]
private unsafe struct RelatedTypeUnion
{
// Kinds.CanonicalEEType
[FieldOffset(0)]
public EEType* _pBaseType;
[FieldOffset(0)]
public EEType** _ppBaseTypeViaIAT;
// Kinds.ClonedEEType
[FieldOffset(0)]
public EEType** _ppCanonicalTypeViaIAT;
// Kinds.ArrayEEType
[FieldOffset(0)]
public EEType* _pRelatedParameterType;
[FieldOffset(0)]
public EEType** _ppRelatedParameterTypeViaIAT;
}
// CS0169: The private field '{blah}' is never used
// CS0649: Field '{blah}' is never assigned to, and will always have its default value
#pragma warning disable 169, 649
private UInt16 _usComponentSize;
private UInt16 _usFlags;
private UInt32 _uBaseSize;
private RelatedTypeUnion _relatedType;
private UInt16 _usNumVtableSlots;
private UInt16 _usNumInterfaces;
private UInt32 _uHashCode;
#if CORERT
private IntPtr _ppModuleManager;
#endif
// vtable follows
#pragma warning restore
private EETypeKind Kind
{
get
{
return (EETypeKind)(_usFlags & (ushort)EETypeFlags.EETypeKindMask);
}
}
internal UInt16 FlagBits
{
get
{
return _usFlags;
}
}
internal UInt32 BaseSize
{
get
{
return _uBaseSize;
}
}
internal UInt16 ComponentSize
{
get
{
return _usComponentSize;
}
}
internal UInt16 NumVTableSlots
{
get
{
return _usNumVtableSlots;
}
}
internal bool IsFinalizable
{
get
{
return ((_usFlags & (ushort)EETypeFlags.HasFinalizerFlag) != 0);
}
}
internal bool IsInterface
{
get
{
return ((_usFlags & (ushort)EETypeFlags.IsInterfaceFlag) != 0);
}
}
internal bool IsCanonical
{
get
{
return Kind == EETypeKind.CanonicalEEType;
}
}
internal bool IsCloned
{
get
{
return Kind == EETypeKind.ClonedEEType;
}
}
internal bool HasReferenceFields
{
get
{
return ((_usFlags & (UInt16)EETypeFlags.HasPointersFlag) != 0);
}
}
internal bool HasOptionalFields
{
get
{
return ((_usFlags & (UInt16)EETypeFlags.OptionalFieldsFlag) != 0);
}
}
// RH only natively supports single-dimensional arrays, so this check implicitly means
// "is single dimensional array"
internal bool IsArray
{
get
{
return IsParameterizedType && ParameterizedTypeShape != 0; // See comment above ParameterizedTypeShape for details.
}
}
internal bool IsParameterizedType
{
get
{
return Kind == EETypeKind.ParameterizedEEType;
}
}
// The parameterized type shape defines the particular form of parameterized type that
// is being represented.
// Currently, the meaning is a shape of 0 indicates that this is a Pointer
// and non-zero indicates that this is an array.
// Two types are not equivalent if their shapes do not exactly match.
internal UInt32 ParameterizedTypeShape
{
get
{
return _uBaseSize;
}
}
internal bool IsRelatedTypeViaIAT
{
get
{
return ((_usFlags & (UInt16)EETypeFlags.RelatedTypeViaIATFlag) != 0);
}
}
internal bool IsValueType
{
get
{
return ((_usFlags & (UInt16)EETypeFlags.ValueTypeFlag) != 0);
}
}
internal bool IsReferenceType
{
get
{
return !IsValueType;
}
}
internal bool IsRuntimeAllocated
{
get
{
return ((_usFlags & (UInt16)EETypeFlags.RuntimeAllocatedFlag) != 0);
}
}
internal bool IsGeneric
{
get
{
return (_usFlags & (UInt16)EETypeFlags.IsGenericFlag) != 0;
}
}
// Mark or determine that a type is generic and one or more of it's type parameters is co- or
// contra-variant. This only applies to interface and delegate types.
internal bool HasGenericVariance
{
get
{
return ((_usFlags & (UInt16)EETypeFlags.GenericVarianceFlag) != 0);
}
}
// Mark or determine that a type requires 8-byte alignment for its fields (required only on certain
// platforms, only ARM so far).
internal unsafe bool RequiresAlign8
{
get
{
#if FEATURE_64BIT_ALIGNMENT
// For now this access to RareFlags is the only managed access required to optional fields. So
// do the flags lookup via a co-op call into the runtime rather than duplicate all of the
// logic to locate and decompress optional fields in managed code.
fixed (EEType* pThis = &this)
return (InternalCalls.RhpGetEETypeRareFlags(pThis) & (UInt32)EETypeRareFlags.RequiresAlign8Flag) != 0;
#else
return false;
#endif
}
}
// Determine whether a type supports ICastable.
internal unsafe bool IsICastable
{
get
{
fixed (EEType* pThis = &this)
return (InternalCalls.RhpGetEETypeRareFlags(pThis) & (UInt32)EETypeRareFlags.ICastableFlag) != 0;
}
}
// For an ICastable type return a pointer to code that implements ICastable.IsInstanceOfInterface.
internal unsafe IntPtr ICastableIsInstanceOfInterfaceMethod
{
get
{
fixed (EEType* pThis = &this)
return InternalCalls.RhpGetICastableIsInstanceOfInterfaceMethod(pThis);
}
}
// For an ICastable type return a pointer to code that implements ICastable.GetImplTypeMethod.
internal unsafe IntPtr ICastableGetImplTypeMethod
{
get
{
fixed (EEType* pThis = &this)
return InternalCalls.RhpGetICastableGetImplTypeMethod(pThis);
}
}
// Determine whether a type is an instantiation of Nullable<T>.
internal unsafe bool IsNullable
{
get
{
fixed (EEType* pThis = &this)
return (InternalCalls.RhpGetEETypeRareFlags(pThis) & (UInt32)EETypeRareFlags.IsNullableFlag) != 0;
}
}
// Retrieve the value type T from a Nullable<T>.
internal unsafe EEType* GetNullableType()
{
fixed (EEType* pThis = &this)
return InternalCalls.RhpGetNullableEEType(pThis);
}
// Retrieve the offset of the value embedded in a Nullable<T>.
internal unsafe byte GetNullableValueOffset()
{
fixed (EEType* pThis = &this)
return InternalCalls.RhpGetNullableEETypeValueOffset(pThis);
}
internal unsafe bool IsDynamicType
{
get
{
fixed (EEType* pThis = &this)
return (InternalCalls.RhpGetEETypeRareFlags(pThis) & (UInt32)EETypeRareFlags.IsDynamicTypeFlag) != 0;
}
}
internal EEType* CanonicalEEType
{
get
{
// cloned EETypes must always refer to types in other modules
Debug.Assert(IsCloned, "only cloned EETypes have canonical equivalents");
Debug.Assert(IsRelatedTypeViaIAT, "cloned types should point to their master via IAT");
return *_relatedType._ppCanonicalTypeViaIAT;
}
}
internal EEType* NonArrayBaseType
{
get
{
Debug.Assert(!IsArray, "array type not supported in BaseType");
if (IsCloned)
{
// Assuming that since this is not an Array, the CanonicalEEType is also not an array
return CanonicalEEType->NonArrayBaseType;
}
Debug.Assert(IsCanonical, "we expect canonical types here");
if (IsRelatedTypeViaIAT)
{
return *_relatedType._ppBaseTypeViaIAT;
}
return _relatedType._pBaseType;
}
}
internal EEType* ArrayBaseType
{
get
{
fixed (EEType* pThis = &this)
return InternalCalls.RhpGetArrayBaseType(pThis);
}
}
internal EEType* NonClonedNonArrayBaseType
{
get
{
Debug.Assert(!IsArray, "array type not supported in NonArrayBaseType");
Debug.Assert(!IsCloned, "cloned type not supported in NonClonedNonArrayBaseType");
Debug.Assert(IsCanonical || IsGenericTypeDefinition, "we expect canonical types here");
if (IsRelatedTypeViaIAT)
{
return *_relatedType._ppBaseTypeViaIAT;
}
return _relatedType._pBaseType;
}
}
internal EEType* BaseType
{
get
{
Debug.Assert(!IsParameterizedType, "array type not supported in NonArrayBaseType");
Debug.Assert(!IsCloned, "cloned type not supported in NonClonedNonArrayBaseType");
Debug.Assert(IsCanonical, "we expect canonical types here");
Debug.Assert(!IsRelatedTypeViaIAT, "Non IAT");
return _relatedType._pBaseType;
}
set
{
Debug.Assert(!IsParameterizedType, "array type not supported in NonArrayBaseType");
Debug.Assert(!IsCloned, "cloned type not supported in NonClonedNonArrayBaseType");
Debug.Assert(IsCanonical, "we expect canonical types here");
_usFlags &= (ushort)~EETypeFlags.RelatedTypeViaIATFlag;
_relatedType._pBaseType = value;
}
}
internal EEType* RelatedParameterType
{
get
{
Debug.Assert(IsParameterizedType, "RelatedParameterType can only be used on array or pointer EETypees");
Debug.Assert(!IsCloned, "cloned array types are not allowed");
if (IsRelatedTypeViaIAT)
{
return *_relatedType._ppRelatedParameterTypeViaIAT;
}
return _relatedType._pRelatedParameterType;
}
}
internal int NumInterfaces
{
get
{
return _usNumInterfaces;
}
}
internal uint HashCode
{
get
{
return _uHashCode;
}
}
internal EEInterfaceInfo* InterfaceMap
{
get
{
fixed (EEType* start = &this)
{
// interface info table starts after the vtable and has m_usNumInterfaces entries
return (EEInterfaceInfo*)((byte*)start + sizeof(EEType) + sizeof(void*) * _usNumVtableSlots);
}
}
}
internal bool HasDispatchMap
{
get
{
fixed (EEType* pThis = &this)
return InternalCalls.RhpHasDispatchMap(pThis);
}
}
internal DispatchResolve.DispatchMap* DispatchMap
{
get
{
fixed (EEType* pThis = &this)
return InternalCalls.RhpGetDispatchMap(pThis);
}
}
internal TypeCast.CorElementType CorElementType
{
get
{
return (TypeCast.CorElementType)((_usFlags & (ushort)EETypeFlags.CorElementTypeMask) >> (ushort)EETypeFlags.CorElementTypeShift);
}
}
internal unsafe IntPtr* GetVTableStartAddress()
{
byte* pResult;
// EETypes are always in unmanaged memory, so 'leaking' the 'fixed pointer' is safe.
fixed (EEType* pThis = &this)
pResult = (byte*)pThis;
pResult += sizeof(EEType);
return (IntPtr*)pResult;
}
internal IntPtr GetSealedVirtualSlot(ushort index)
{
fixed (EEType* pThis = &this)
return InternalCalls.RhpGetSealedVirtualSlot(pThis, index);
}
// Returns an address in the module most closely associated with this EEType that can be handed to
// EH.GetClasslibException and use to locate the compute the correct exception type. In most cases
// this is just the EEType pointer itself, but when this type represents a generic that has been
// unified at runtime (and thus the EEType pointer resides in the process heap rather than a specific
// module) we need to do some work.
internal unsafe IntPtr GetAssociatedModuleAddress()
{
fixed (EEType* pThis = &this)
{
if (!IsRuntimeAllocated && !IsDynamicType)
return (IntPtr)pThis;
// There are currently three types of runtime allocated EETypes, arrays, pointers, and generic types.
// Arrays/Pointers can be handled by looking at their element type.
if (IsParameterizedType)
return pThis->RelatedParameterType->GetAssociatedModuleAddress();
// Generic types are trickier. Often we could look at the parent type (since eventually it
// would derive from the class library's System.Object which is definitely not runtime
// allocated). But this breaks down for generic interfaces. Instead we fetch the generic
// instantiation information and use the generic type definition, which will always be module
// local. We know this lookup will succeed since we're dealing with a unified generic type
// and the unification process requires this metadata.
EETypeRef* pInstantiation;
int arity;
GenericVariance* pVarianceInfo;
EEType* pGenericType = InternalCalls.RhGetGenericInstantiation(pThis,
&arity,
&pInstantiation,
&pVarianceInfo);
Debug.Assert(pGenericType != null, "Generic type expected");
return (IntPtr)pGenericType;
}
}
internal bool IsGenericTypeDefinition
{
get
{
return Kind == EETypeKind.GenericTypeDefEEType;
}
}
internal bool IsPointerTypeDefinition
{
get
{
if (Kind != EETypeKind.ParameterizedEEType)
return false;
return ParameterizedTypeShape == 0; // See comment above ParameterizedTypeShape for details.
}
}
// Get the address of the finalizer method for finalizable types.
internal IntPtr FinalizerCode
{
get
{
Debug.Assert(IsFinalizable, "Can't get finalizer for non-finalizeable type");
fixed (EEType* start = &this)
{
// Finalizer code address is stored after the vtable and interface map.
return *(IntPtr*)((byte*)start +
sizeof(EEType) +
(sizeof(void*) * _usNumVtableSlots) +
(sizeof(EEInterfaceInfo) * NumInterfaces));
}
}
}
/// <summary>
/// Return true if type is good for simple casting : canonical, no related type via IAT, no generic variance
/// </summary>
internal bool SimpleCasting()
{
return (_usFlags & (ushort)EETypeFlags.ComplexCastingMask) == (ushort)EETypeKind.CanonicalEEType;
}
/// <summary>
/// Does this type have a class constructor.
/// </summary>
internal bool HasCctor
{
get
{
fixed (EEType* pThis = &this)
return (InternalCalls.RhpGetEETypeRareFlags(pThis) & (UInt32)EETypeRareFlags.HasCctorFlag) != 0;
}
}
/// <summary>
/// Return true if both types are good for simple casting: canonical, no related type via IAT, no generic variance
/// </summary>
static internal bool BothSimpleCasting(EEType* pThis, EEType* pOther)
{
return ((pThis->_usFlags | pOther->_usFlags) & (ushort)EETypeFlags.ComplexCastingMask) == (ushort)EETypeKind.CanonicalEEType;
}
internal bool IsEquivalentTo(EEType* pOtherEEType)
{
fixed (EEType* pThis = &this)
{
if (pThis == pOtherEEType)
return true;
EEType* pThisEEType = pThis;
if (pThisEEType->IsCloned)
pThisEEType = pThisEEType->CanonicalEEType;
if (pOtherEEType->IsCloned)
pOtherEEType = pOtherEEType->CanonicalEEType;
if (pThisEEType == pOtherEEType)
return true;
if (pThisEEType->IsParameterizedType && pOtherEEType->IsParameterizedType)
{
return pThisEEType->RelatedParameterType->IsEquivalentTo(pOtherEEType->RelatedParameterType) &&
pThisEEType->ParameterizedTypeShape == pOtherEEType->ParameterizedTypeShape;
}
}
return false;
}
}
// CS0169: The private field '{blah}' is never used
// CS0649: Field '{blah}' is never assigned to, and will always have its default value
#pragma warning disable 169, 649
// Wrapper around EEType pointers that may be indirected through the IAT if their low bit is set.
internal unsafe struct EETypeRef
{
private byte* _value;
public EEType* Value
{
get
{
if (((int)_value & 1) == 0)
return (EEType*)_value;
return *(EEType**)(_value - 1);
}
}
}
internal unsafe struct EEInterfaceInfo
{
[StructLayout(LayoutKind.Explicit)]
private unsafe struct InterfaceTypeUnion
{
[FieldOffset(0)]
public EEType* _pInterfaceEEType;
[FieldOffset(0)]
public EEType** _ppInterfaceEETypeViaIAT;
}
private InterfaceTypeUnion _interfaceType;
internal EEType* InterfaceType
{
get
{
if ((unchecked((uint)_interfaceType._pInterfaceEEType) & 1u) != 0)
{
#if BIT64
EEType** ppInterfaceEETypeViaIAT = (EEType**)(((ulong)_interfaceType._ppInterfaceEETypeViaIAT) & ~1ul);
#else
EEType** ppInterfaceEETypeViaIAT = (EEType**)(((uint)_interfaceType._ppInterfaceEETypeViaIAT) & ~1u);
#endif
return *ppInterfaceEETypeViaIAT;
}
return _interfaceType._pInterfaceEEType;
}
set { _interfaceType._pInterfaceEEType = value; }
}
#pragma warning restore
};
internal static class WellKnownEETypes
{
// Returns true if the passed in EEType is the EEType for System.Object
// This is recognized by the fact that System.Object and interfaces are the only ones without a base type
internal static unsafe bool IsSystemObject(EEType* pEEType)
{
if (pEEType->IsArray)
return false;
return (pEEType->NonArrayBaseType == null) && !pEEType->IsInterface;
}
// Returns true if the passed in EEType is the EEType for System.Array.
// The binder sets a special CorElementType for this well known type
internal static unsafe bool IsSystemArray(EEType* pEEType)
{
return (pEEType->CorElementType == TypeCast.CorElementType.ELEMENT_TYPE_ARRAY);
}
}
} // System.Runtime
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.WSMan.Management.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.WSMan.Management\Get-WSManInstance command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class GetWSManInstance : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public GetWSManInstance()
{
this.DisplayName = "Get-WSManInstance";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.WSMan.Management\\Get-WSManInstance"; } }
// Arguments
/// <summary>
/// Provides access to the ApplicationName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ApplicationName { get; set; }
/// <summary>
/// Provides access to the BasePropertiesOnly parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> BasePropertiesOnly { get; set; }
/// <summary>
/// Provides access to the ComputerName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ComputerName { get; set; }
/// <summary>
/// Provides access to the ConnectionURI parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Uri> ConnectionURI { get; set; }
/// <summary>
/// Provides access to the Dialect parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Uri> Dialect { get; set; }
/// <summary>
/// Provides access to the Enumerate parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Enumerate { get; set; }
/// <summary>
/// Provides access to the Filter parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Filter { get; set; }
/// <summary>
/// Provides access to the Fragment parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Fragment { get; set; }
/// <summary>
/// Provides access to the OptionSet parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Collections.Hashtable> OptionSet { get; set; }
/// <summary>
/// Provides access to the Port parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int32> Port { get; set; }
/// <summary>
/// Provides access to the Associations parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Associations { get; set; }
/// <summary>
/// Provides access to the ResourceURI parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Uri> ResourceURI { get; set; }
/// <summary>
/// Provides access to the ReturnType parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ReturnType { get; set; }
/// <summary>
/// Provides access to the SelectorSet parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Collections.Hashtable> SelectorSet { get; set; }
/// <summary>
/// Provides access to the SessionOption parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.WSMan.Management.SessionOption> SessionOption { get; set; }
/// <summary>
/// Provides access to the Shallow parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Shallow { 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 Credential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> Credential { get; set; }
/// <summary>
/// Provides access to the Authentication parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.WSMan.Management.AuthenticationMechanism> Authentication { get; set; }
/// <summary>
/// Provides access to the CertificateThumbprint parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> CertificateThumbprint { get; set; }
/// <summary>
/// Declares that this activity supports its own remoting.
/// </summary>
protected override bool SupportsCustomRemoting { get { return true; } }
// Module defining this command
// Optional custom code for this activity
/// <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 Sytem.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(ApplicationName.Expression != null)
{
targetCommand.AddParameter("ApplicationName", ApplicationName.Get(context));
}
if(BasePropertiesOnly.Expression != null)
{
targetCommand.AddParameter("BasePropertiesOnly", BasePropertiesOnly.Get(context));
}
if ((ComputerName.Expression != null) && (PSRemotingBehavior.Get(context) != RemotingBehavior.Custom))
{
targetCommand.AddParameter("ComputerName", ComputerName.Get(context));
}
if(ConnectionURI.Expression != null)
{
targetCommand.AddParameter("ConnectionURI", ConnectionURI.Get(context));
}
if(Dialect.Expression != null)
{
targetCommand.AddParameter("Dialect", Dialect.Get(context));
}
if(Enumerate.Expression != null)
{
targetCommand.AddParameter("Enumerate", Enumerate.Get(context));
}
if(Filter.Expression != null)
{
targetCommand.AddParameter("Filter", Filter.Get(context));
}
if(Fragment.Expression != null)
{
targetCommand.AddParameter("Fragment", Fragment.Get(context));
}
if(OptionSet.Expression != null)
{
targetCommand.AddParameter("OptionSet", OptionSet.Get(context));
}
if(Port.Expression != null)
{
targetCommand.AddParameter("Port", Port.Get(context));
}
if(Associations.Expression != null)
{
targetCommand.AddParameter("Associations", Associations.Get(context));
}
if(ResourceURI.Expression != null)
{
targetCommand.AddParameter("ResourceURI", ResourceURI.Get(context));
}
if(ReturnType.Expression != null)
{
targetCommand.AddParameter("ReturnType", ReturnType.Get(context));
}
if(SelectorSet.Expression != null)
{
targetCommand.AddParameter("SelectorSet", SelectorSet.Get(context));
}
if(SessionOption.Expression != null)
{
targetCommand.AddParameter("SessionOption", SessionOption.Get(context));
}
if(Shallow.Expression != null)
{
targetCommand.AddParameter("Shallow", Shallow.Get(context));
}
if(UseSSL.Expression != null)
{
targetCommand.AddParameter("UseSSL", UseSSL.Get(context));
}
if(Credential.Expression != null)
{
targetCommand.AddParameter("Credential", Credential.Get(context));
}
if(Authentication.Expression != null)
{
targetCommand.AddParameter("Authentication", Authentication.Get(context));
}
if(CertificateThumbprint.Expression != null)
{
targetCommand.AddParameter("CertificateThumbprint", CertificateThumbprint.Get(context));
}
if(GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom))
{
targetCommand.AddParameter("ComputerName", PSComputerName.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Text;
using Internal.Runtime.Augments;
namespace System.Globalization
{
internal partial class CultureData
{
private const uint LOCALE_NOUSEROVERRIDE = 0x80000000;
private const uint LOCALE_RETURN_NUMBER = 0x20000000;
private const uint LOCALE_SISO3166CTRYNAME = 0x0000005A;
private const uint TIME_NOSECONDS = 0x00000002;
/// <summary>
/// Check with the OS to see if this is a valid culture.
/// If so we populate a limited number of fields. If its not valid we return false.
///
/// The fields we populate:
///
/// sWindowsName -- The name that windows thinks this culture is, ie:
/// en-US if you pass in en-US
/// de-DE_phoneb if you pass in de-DE_phoneb
/// fj-FJ if you pass in fj (neutral, on a pre-Windows 7 machine)
/// fj if you pass in fj (neutral, post-Windows 7 machine)
///
/// sRealName -- The name you used to construct the culture, in pretty form
/// en-US if you pass in EN-us
/// en if you pass in en
/// de-DE_phoneb if you pass in de-DE_phoneb
///
/// sSpecificCulture -- The specific culture for this culture
/// en-US for en-US
/// en-US for en
/// de-DE_phoneb for alt sort
/// fj-FJ for fj (neutral)
///
/// sName -- The IETF name of this culture (ie: no sort info, could be neutral)
/// en-US if you pass in en-US
/// en if you pass in en
/// de-DE if you pass in de-DE_phoneb
///
/// bNeutral -- TRUE if it is a neutral locale
///
/// For a neutral we just populate the neutral name, but we leave the windows name pointing to the
/// windows locale that's going to provide data for us.
/// </summary>
private unsafe bool InitCultureData()
{
const int LOCALE_NAME_MAX_LENGTH = 85;
const uint LOCALE_ILANGUAGE = 0x00000001;
const uint LOCALE_INEUTRAL = 0x00000071;
const uint LOCALE_SNAME = 0x0000005c;
int result;
string realNameBuffer = _sRealName;
char* pBuffer = stackalloc char[LOCALE_NAME_MAX_LENGTH];
result = Interop.mincore.GetLocaleInfoEx(realNameBuffer, LOCALE_SNAME, pBuffer, LOCALE_NAME_MAX_LENGTH);
// Did it fail?
if (result == 0)
{
return false;
}
// It worked, note that the name is the locale name, so use that (even for neutrals)
// We need to clean up our "real" name, which should look like the windows name right now
// so overwrite the input with the cleaned up name
_sRealName = new String(pBuffer, 0, result - 1);
realNameBuffer = _sRealName;
// Check for neutrality, don't expect to fail
// (buffer has our name in it, so we don't have to do the gc. stuff)
result = Interop.mincore.GetLocaleInfoEx(realNameBuffer, LOCALE_INEUTRAL | LOCALE_RETURN_NUMBER, pBuffer, sizeof(int) / sizeof(char));
if (result == 0)
{
return false;
}
// Remember our neutrality
_bNeutral = *((uint*)pBuffer) != 0;
// Note: Parents will be set dynamically
// Start by assuming the windows name'll be the same as the specific name since windows knows
// about specifics on all versions. Only for downlevel Neutral locales does this have to change.
_sWindowsName = realNameBuffer;
// Neutrals and non-neutrals are slightly different
if (_bNeutral)
{
// Neutral Locale
// IETF name looks like neutral name
_sName = realNameBuffer;
// Specific locale name is whatever ResolveLocaleName (win7+) returns.
// (Buffer has our name in it, and we can recycle that because windows resolves it before writing to the buffer)
result = Interop.mincore.ResolveLocaleName(realNameBuffer, pBuffer, LOCALE_NAME_MAX_LENGTH);
// 0 is failure, 1 is invariant (""), which we expect
if (result < 1)
{
return false;
}
// We found a locale name, so use it.
// In vista this should look like a sort name (de-DE_phoneb) or a specific culture (en-US) and be in the "pretty" form
_sSpecificCulture = new String(pBuffer, 0, result - 1);
}
else
{
// Specific Locale
// Specific culture's the same as the locale name since we know its not neutral
// On mac we'll use this as well, even for neutrals. There's no obvious specific
// culture to use and this isn't exposed, but behaviorally this is correct on mac.
// Note that specifics include the sort name (de-DE_phoneb)
_sSpecificCulture = realNameBuffer;
_sName = realNameBuffer;
// We need the IETF name (sname)
// If we aren't an alt sort locale then this is the same as the windows name.
// If we are an alt sort locale then this is the same as the part before the _ in the windows name
// This is for like de-DE_phoneb and es-ES_tradnl that hsouldn't have the _ part
result = Interop.mincore.GetLocaleInfoEx(realNameBuffer, LOCALE_ILANGUAGE | LOCALE_RETURN_NUMBER, pBuffer, sizeof(int) / sizeof(char));
if (result == 0)
{
return false;
}
_iLanguage = *((int*)pBuffer);
if (!IsCustomCultureId(_iLanguage))
{
// not custom locale
int index = realNameBuffer.IndexOf('_');
if (index > 0 && index < realNameBuffer.Length)
{
_sName = realNameBuffer.Substring(0, index);
}
}
}
// It succeeded.
return true;
}
[System.Security.SecurityCritical]
private string GetLocaleInfo(LocaleStringData type)
{
Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by already");
return GetLocaleInfo(_sWindowsName, type);
}
// For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
// "windows" name, which can be specific for downlevel (< windows 7) os's.
[System.Security.SecurityCritical]
private string GetLocaleInfo(string localeName, LocaleStringData type)
{
uint lctype = (uint)type;
return GetLocaleInfoFromLCType(localeName, lctype, UseUserOverride);
}
private int GetLocaleInfo(LocaleNumberData type)
{
uint lctype = (uint)type;
// Fix lctype if we don't want overrides
if (!UseUserOverride)
{
lctype |= LOCALE_NOUSEROVERRIDE;
}
// Ask OS for data, note that we presume it returns success, so we have to know that
// sWindowsName is valid before calling.
Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by already");
int result = Interop.mincore.GetLocaleInfoExInt(_sWindowsName, lctype);
return result;
}
private int[] GetLocaleInfo(LocaleGroupingData type)
{
return ConvertWin32GroupString(GetLocaleInfoFromLCType(_sWindowsName, (uint)type, UseUserOverride));
}
private string GetTimeFormatString()
{
const uint LOCALE_STIMEFORMAT = 0x00001003;
return ReescapeWin32String(GetLocaleInfoFromLCType(_sWindowsName, LOCALE_STIMEFORMAT, UseUserOverride));
}
private int GetFirstDayOfWeek()
{
Contract.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by already");
const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C;
int result = Interop.mincore.GetLocaleInfoExInt(_sWindowsName, LOCALE_IFIRSTDAYOFWEEK | (!UseUserOverride ? LOCALE_NOUSEROVERRIDE : 0));
// Win32 and .NET disagree on the numbering for days of the week, so we have to convert.
return ConvertFirstDayOfWeekMonToSun(result);
}
private String[] GetTimeFormats()
{
// Note that this gets overrides for us all the time
Contract.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by already");
String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, 0, UseUserOverride));
return result;
}
private String[] GetShortTimeFormats()
{
// Note that this gets overrides for us all the time
Contract.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by already");
String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, TIME_NOSECONDS, UseUserOverride));
return result;
}
// Enumerate all system cultures and then try to find out which culture has
// region name match the requested region name
private static CultureData GetCultureDataFromRegionName(String regionName)
{
Contract.Assert(regionName != null);
const uint LOCALE_SUPPLEMENTAL = 0x00000002;
const uint LOCALE_SPECIFICDATA = 0x00000020;
EnumLocaleData context = new EnumLocaleData();
context.cultureName = null;
context.regionName = regionName;
GCHandle contextHandle = GCHandle.Alloc(context);
try
{
IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, Interop.BOOL>>(EnumSystemLocalesProc);
Interop.mincore.EnumSystemLocalesEx(callback, LOCALE_SPECIFICDATA | LOCALE_SUPPLEMENTAL, (IntPtr)contextHandle, IntPtr.Zero);
}
finally
{
contextHandle.Free();
}
if (context.cultureName != null)
{
// we got a matched culture
return GetCultureData(context.cultureName, true);
}
return null;
}
private static string GetLanguageDisplayName(string cultureName)
{
return WinRTInterop.Callbacks.GetLanguageDisplayName(cultureName);
}
private static string GetRegionDisplayName(string isoCountryCode)
{
return WinRTInterop.Callbacks.GetRegionDisplayName(isoCountryCode);
}
private static CultureInfo GetUserDefaultCulture()
{
return (CultureInfo)WinRTInterop.Callbacks.GetUserDefaultCulture();
}
private static bool IsCustomCultureId(int cultureId)
{
const int LOCALE_CUSTOM_DEFAULT = 0x0c00;
const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000;
return (cultureId == LOCALE_CUSTOM_DEFAULT || cultureId == LOCALE_CUSTOM_UNSPECIFIED);
}
// PAL methods end here.
[System.Security.SecurityCritical]
private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOveride)
{
Contract.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null");
// Fix lctype if we don't want overrides
if (!useUserOveride)
{
lctype |= LOCALE_NOUSEROVERRIDE;
}
// Ask OS for data
string result = Interop.mincore.GetLocaleInfoEx(localeName, lctype);
if (result == null)
{
// Failed, just use empty string
result = String.Empty;
}
return result;
}
////////////////////////////////////////////////////////////////////////////
//
// Reescape a Win32 style quote string as a NLS+ style quoted string
//
// This is also the escaping style used by custom culture data files
//
// NLS+ uses \ to escape the next character, whether in a quoted string or
// not, so we always have to change \ to \\.
//
// NLS+ uses \' to escape a quote inside a quoted string so we have to change
// '' to \' (if inside a quoted string)
//
// We don't build the stringbuilder unless we find something to change
////////////////////////////////////////////////////////////////////////////
internal static String ReescapeWin32String(String str)
{
// If we don't have data, then don't try anything
if (str == null)
return null;
StringBuilder result = null;
bool inQuote = false;
for (int i = 0; i < str.Length; i++)
{
// Look for quote
if (str[i] == '\'')
{
// Already in quote?
if (inQuote)
{
// See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote?
if (i + 1 < str.Length && str[i + 1] == '\'')
{
// Found another ', so we have ''. Need to add \' instead.
// 1st make sure we have our stringbuilder
if (result == null)
result = new StringBuilder(str, 0, i, str.Length * 2);
// Append a \' and keep going (so we don't turn off quote mode)
result.Append("\\'");
i++;
continue;
}
// Turning off quote mode, fall through to add it
inQuote = false;
}
else
{
// Found beginning quote, fall through to add it
inQuote = true;
}
}
// Is there a single \ character?
else if (str[i] == '\\')
{
// Found a \, need to change it to \\
// 1st make sure we have our stringbuilder
if (result == null)
result = new StringBuilder(str, 0, i, str.Length * 2);
// Append our \\ to the string & continue
result.Append("\\\\");
continue;
}
// If we have a builder we need to add our character
if (result != null)
result.Append(str[i]);
}
// Unchanged string? , just return input string
if (result == null)
return str;
// String changed, need to use the builder
return result.ToString();
}
internal static String[] ReescapeWin32Strings(String[] array)
{
if (array != null)
{
for (int i = 0; i < array.Length; i++)
{
array[i] = ReescapeWin32String(array[i]);
}
}
return array;
}
// If we get a group from windows, then its in 3;0 format with the 0 backwards
// of how NLS+ uses it (ie: if the string has a 0, then the int[] shouldn't and vice versa)
// EXCEPT in the case where the list only contains 0 in which NLS and NLS+ have the same meaning.
private static int[] ConvertWin32GroupString(String win32Str)
{
// None of these cases make any sense
if (win32Str == null || win32Str.Length == 0)
{
return (new int[] { 3 });
}
if (win32Str[0] == '0')
{
return (new int[] { 0 });
}
// Since its in n;n;n;n;n format, we can always get the length quickly
int[] values;
if (win32Str[win32Str.Length - 1] == '0')
{
// Trailing 0 gets dropped. 1;0 -> 1
values = new int[(win32Str.Length / 2)];
}
else
{
// Need extra space for trailing zero 1 -> 1;0
values = new int[(win32Str.Length / 2) + 2];
values[values.Length - 1] = 0;
}
int i;
int j;
for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++)
{
// Note that this # shouldn't ever be zero, 'cause 0 is only at end
// But we'll test because its registry that could be anything
if (win32Str[i] < '1' || win32Str[i] > '9')
return new int[] { 3 };
values[j] = (int)(win32Str[i] - '0');
}
return (values);
}
private static int ConvertFirstDayOfWeekMonToSun(int iTemp)
{
// Convert Mon-Sun to Sun-Sat format
iTemp++;
if (iTemp > 6)
{
// Wrap Sunday and convert invalid data to Sunday
iTemp = 0;
}
return iTemp;
}
// Context for EnumCalendarInfoExEx callback.
private class EnumLocaleData
{
public string regionName;
public string cultureName;
}
// EnumSystemLocaleEx callback.
[NativeCallable(CallingConvention = CallingConvention.StdCall)]
private static unsafe Interop.BOOL EnumSystemLocalesProc(IntPtr lpLocaleString, uint flags, IntPtr contextHandle)
{
EnumLocaleData context = (EnumLocaleData)((GCHandle)contextHandle).Target;
try
{
string cultureName = new string((char*)lpLocaleString);
string regionName = Interop.mincore.GetLocaleInfoEx(cultureName, LOCALE_SISO3166CTRYNAME);
if (regionName != null && regionName.Equals(context.regionName, StringComparison.OrdinalIgnoreCase))
{
context.cultureName = cultureName;
return Interop.BOOL.FALSE; // we found a match, then stop the enumeration
}
return Interop.BOOL.TRUE;
}
catch (Exception)
{
return Interop.BOOL.FALSE;
}
}
// Context for EnumTimeFormatsEx callback.
private class EnumData
{
public LowLevelList<string> strings;
}
// EnumTimeFormatsEx callback itself.
[NativeCallable(CallingConvention = CallingConvention.StdCall)]
private static unsafe Interop.BOOL EnumTimeCallback(IntPtr lpTimeFormatString, IntPtr lParam)
{
EnumData context = (EnumData)((GCHandle)lParam).Target;
try
{
context.strings.Add(new string((char*)lpTimeFormatString));
return Interop.BOOL.TRUE;
}
catch (Exception)
{
return Interop.BOOL.FALSE;
}
}
private static unsafe String[] nativeEnumTimeFormats(String localeName, uint dwFlags, bool useUserOverride)
{
const uint LOCALE_SSHORTTIME = 0x00000079;
const uint LOCALE_STIMEFORMAT = 0x00001003;
EnumData data = new EnumData();
data.strings = new LowLevelList<string>();
GCHandle dataHandle = GCHandle.Alloc(data);
try
{
// Now call the enumeration API. Work is done by our callback function
IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, IntPtr, Interop.BOOL>>(EnumTimeCallback);
Interop.mincore.EnumTimeFormatsEx(callback, localeName, (uint)dwFlags, (IntPtr)dataHandle);
}
finally
{
dataHandle.Free();
}
if (data.strings.Count > 0)
{
// Now we need to allocate our stringarray and populate it
string[] results = data.strings.ToArray();
if (!useUserOverride && data.strings.Count > 1)
{
// Since there is no "NoUserOverride" aware EnumTimeFormatsEx, we always get an override
// The override is the first entry if it is overriden.
// We can check if we have overrides by checking the GetLocaleInfo with no override
// If we do have an override, we don't know if it is a user defined override or if the
// user has just selected one of the predefined formats so we can't just remove it
// but we can move it down.
uint lcType = (dwFlags == TIME_NOSECONDS) ? LOCALE_SSHORTTIME : LOCALE_STIMEFORMAT;
string timeFormatNoUserOverride = GetLocaleInfoFromLCType(localeName, lcType, useUserOverride);
if (timeFormatNoUserOverride != "")
{
string firstTimeFormat = results[0];
if (timeFormatNoUserOverride != firstTimeFormat)
{
results[0] = results[1];
results[1] = firstTimeFormat;
}
}
}
return results;
}
return null;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Store
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// AccountOperations operations.
/// </summary>
public partial interface IAccountOperations
{
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<DataLakeStoreAccount>> CreateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to create.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<DataLakeStoreAccount>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccount parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<DataLakeStoreAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the specified Data Lake Store account information.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='name'>
/// The name of the Data Lake Store account to update.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to update the Data Lake Store account.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<DataLakeStoreAccount>> BeginUpdateWithHttpMessagesAsync(string resourceGroupName, string name, DataLakeStoreAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to delete.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to delete.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to retrieve.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<DataLakeStoreAccount>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Attempts to enable a user managed key vault for encryption of the
/// specified Data Lake Store account.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account.
/// </param>
/// <param name='accountName'>
/// The name of the Data Lake Store account to attempt to enable the
/// Key Vault for.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse> EnableKeyVaultWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource
/// group. The response includes a link to the next page of results,
/// if any.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Azure resource group that contains the Data Lake
/// Store account(s).
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to
/// just those requested, e.g.
/// Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// A Boolean value of true or false to request a count of the
/// matching resources included with the resources in the response,
/// e.g. Categories?$count=true. Optional.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='select'>
/// OData Select statement. Limits the properties on each entry to
/// just those requested, e.g.
/// Categories?$select=CategoryName,Description. Optional.
/// </param>
/// <param name='count'>
/// The Boolean value of true or false to request a count of the
/// matching resources included with the resources in the response,
/// e.g. Categories?$count=true. Optional.
/// </param>
/// <param name='customHeaders'>
/// The 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>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListWithHttpMessagesAsync(ODataQuery<DataLakeStoreAccount> odataQuery = default(ODataQuery<DataLakeStoreAccount>), string select = default(string), bool? count = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within a specific resource
/// group. The response includes a link to the next page of results,
/// if any.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="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>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the Data Lake Store accounts within the subscription. The
/// response includes a link to the next page of results, if any.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="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>
Task<AzureOperationResponse<IPage<DataLakeStoreAccount>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using log4net;
using FluorineFx.Util;
using FluorineFx.IO;
using FluorineFx.IO.Mp4;
namespace FluorineFx.IO.M4a
{
/// <summary>
/// A reader used to read the contents of a M4A file.
/// </summary>
class M4aReader : ITagReader
{
private static readonly ILog log = LogManager.GetLogger(typeof(M4aReader));
object _syncLock = new object();
private FileInfo _file;
private FileStream _fs;
private Mp4DataStream _inputStream;
private String _audioCodecId = "mp4a";
/// <summary>
/// Decoder bytes / configs
/// </summary>
private byte[] _audioDecoderBytes;
/// <summary>
/// Duration in milliseconds.
/// </summary>
private long _duration;
private int _timeScale;
/// <summary>
/// Audio sample rate kHz
/// </summary>
private double _audioTimeScale;
private int _audioChannels;
/// <summary>
/// Default to aac lc
/// </summary>
private int _audioCodecType = 1;
private String _formattedDuration;
private long _moovOffset;
private long _mdatOffset;
/// <summary>
/// Samples to chunk mappings
/// </summary>
private List<Mp4Atom.Record> _audioSamplesToChunks;
/// <summary>
/// Samples
/// </summary>
private List<int> _audioSamples;
/// <summary>
/// Chunk offsets
/// </summary>
private List<long> _audioChunkOffsets;
/// <summary>
/// Sample duration
/// </summary>
private int _audioSampleDuration = 1024;
/// <summary>
/// Keep track of current sample
/// </summary>
private int _currentFrame = 1;
private int _prevFrameSize = 0;
private List<Mp4Frame> _frames = new List<Mp4Frame>();
/// <summary>
/// Container for metadata and any other tags that should be sent prior to media data.
/// </summary>
private LinkedList<ITag> _firstTags = new LinkedList<ITag>();
public M4aReader(FileInfo file)
{
_file = file;
_fs = new FileStream(_file.FullName, FileMode.Open);
_inputStream = new Mp4DataStream(_fs);
//Decode all the info that we want from the atoms
DecodeHeader();
//Analyze the samples/chunks and build the keyframe meta data
AnalyzeFrames();
//Add meta data
_firstTags.AddLast(CreateFileMeta());
//Create / add the pre-streaming (decoder config) tags
CreatePreStreamingTags();
}
/// <summary>
/// Gets an object that can be used to synchronize access.
/// </summary>
public object SyncRoot { get { return _syncLock; } }
#region ITagReader Members
public IStreamableFile File
{
get { return null; }
}
public int Offset
{
get { return (int)_inputStream.Offset; }
}
public long BytesRead
{
get { return _inputStream.Offset; }
}
public long Duration
{
get { return _duration; }
}
/// <summary>
/// This handles the moov atom being at the beginning or end of the file, so the mdat may also be before or after the moov atom.
/// </summary>
public void DecodeHeader()
{
try
{
// the first atom will/should be the type
Mp4Atom type = Mp4Atom.CreateAtom(_inputStream);
// expect ftyp
log.Debug(string.Format("Type {0}", type));
// keep a running count of the number of atoms found at the "top" levels
int topAtoms = 0;
// we want a moov and an mdat, anything else throw the invalid file type error
while (topAtoms < 2)
{
Mp4Atom atom = Mp4Atom.CreateAtom(_inputStream);
switch (atom.Type)
{
case 1836019574: //moov
topAtoms++;
Mp4Atom moov = atom;
// expect moov
log.Debug(string.Format("Type {0}", moov));
//log.debug("moov children: {}", moov.getChildren());
_moovOffset = _inputStream.Offset - moov.Size;
Mp4Atom mvhd = moov.Lookup(Mp4Atom.TypeToInt("mvhd"), 0);
if (mvhd != null)
{
log.Debug("Movie header atom found");
//get the initial timescale
_timeScale = mvhd.TimeScale;
_duration = mvhd.Duration;
log.Debug(string.Format("Time scale {0} Duration {1}", _timeScale, _duration));
}
/* nothing needed here yet
MP4Atom meta = moov.lookup(MP4Atom.typeToInt("meta"), 0);
if (meta != null) {
log.debug("Meta atom found");
log.debug("{}", ToStringBuilder.reflectionToString(meta));
}
*/
Mp4Atom trak = moov.Lookup(Mp4Atom.TypeToInt("trak"), 0);
if (trak != null)
{
log.Debug("Track atom found");
//log.debug("trak children: {}", trak.getChildren());
// trak: tkhd, edts, mdia
Mp4Atom edts = trak.Lookup(Mp4Atom.TypeToInt("edts"), 0);
if (edts != null)
{
log.Debug("Edit atom found");
//log.debug("edts children: {}", edts.getChildren());
}
Mp4Atom mdia = trak.Lookup(Mp4Atom.TypeToInt("mdia"), 0);
if (mdia != null)
{
log.Debug("Media atom found");
// mdia: mdhd, hdlr, minf
int scale = 0;
//get the media header atom
Mp4Atom mdhd = mdia.Lookup(Mp4Atom.TypeToInt("mdhd"), 0);
if (mdhd != null)
{
log.Debug("Media data header atom found");
//this will be for either video or audio depending media info
scale = mdhd.TimeScale;
log.Debug(string.Format("Time scale {0}", scale));
}
Mp4Atom hdlr = mdia.Lookup(Mp4Atom.TypeToInt("hdlr"), 0);
if (hdlr != null)
{
log.Debug("Handler ref atom found");
// soun or vide
log.Debug(string.Format("Handler type: {0}", Mp4Atom.IntToType(hdlr.HandlerType)));
String hdlrType = Mp4Atom.IntToType(hdlr.HandlerType);
if ("soun".Equals(hdlrType))
{
if (scale > 0)
{
_audioTimeScale = scale * 1.0;
log.Debug(string.Format("Audio time scale: {0}", _audioTimeScale));
}
}
}
Mp4Atom minf = mdia.Lookup(Mp4Atom.TypeToInt("minf"), 0);
if (minf != null)
{
log.Debug("Media info atom found");
// minf: (audio) smhd, dinf, stbl / (video) vmhd,
// dinf, stbl
Mp4Atom smhd = minf.Lookup(Mp4Atom.TypeToInt("smhd"), 0);
if (smhd != null)
{
log.Debug("Sound header atom found");
Mp4Atom dinf = minf.Lookup(Mp4Atom.TypeToInt("dinf"), 0);
if (dinf != null)
{
log.Debug("Data info atom found");
// dinf: dref
//log.Debug("Sound dinf children: {}", dinf.getChildren());
Mp4Atom dref = dinf.Lookup(Mp4Atom.TypeToInt("dref"), 0);
if (dref != null)
{
log.Debug("Data reference atom found");
}
}
Mp4Atom stbl = minf.Lookup(Mp4Atom.TypeToInt("stbl"), 0);
if (stbl != null)
{
log.Debug("Sample table atom found");
// stbl: stsd, stts, stss, stsc, stsz, stco,
// stsh
//log.debug("Sound stbl children: {}", stbl.getChildren());
// stsd - sample description
// stts - time to sample
// stsc - sample to chunk
// stsz - sample size
// stco - chunk offset
//stsd - has codec child
Mp4Atom stsd = stbl.Lookup(Mp4Atom.TypeToInt("stsd"), 0);
if (stsd != null)
{
//stsd: mp4a
log.Debug("Sample description atom found");
Mp4Atom mp4a = stsd.Children[0];
//could set the audio codec here
SetAudioCodecId(Mp4Atom.IntToType(mp4a.Type));
//log.debug("{}", ToStringBuilder.reflectionToString(mp4a));
log.Debug(string.Format("Sample size: {0}", mp4a.SampleSize));
int ats = mp4a.TimeScale;
//skip invalid audio time scale
if (ats > 0)
{
_audioTimeScale = ats * 1.0;
}
_audioChannels = mp4a.ChannelCount;
log.Debug(string.Format("Sample rate (audio time scale): {0}", _audioTimeScale));
log.Debug(string.Format("Channels: {0}", _audioChannels));
//mp4a: esds
if (mp4a.Children.Count > 0)
{
log.Debug("Elementary stream descriptor atom found");
Mp4Atom esds = mp4a.Children[0];
//log.debug("{}", ToStringBuilder.reflectionToString(esds));
Mp4Descriptor descriptor = esds.EsdDescriptor;
//log.debug("{}", ToStringBuilder.reflectionToString(descriptor));
if (descriptor != null)
{
List<Mp4Descriptor> children = descriptor.Children;
for (int e = 0; e < children.Count; e++)
{
Mp4Descriptor descr = children[e];
//log.debug("{}", ToStringBuilder.reflectionToString(descr));
if (descr.Children.Count > 0)
{
List<Mp4Descriptor> children2 = descr.Children;
for (int e2 = 0; e2 < children2.Count; e2++)
{
Mp4Descriptor descr2 = children2[e2];
//log.debug("{}", ToStringBuilder.reflectionToString(descr2));
if (descr2.Type == Mp4Descriptor.MP4DecSpecificInfoDescriptorTag)
{
//we only want the MP4DecSpecificInfoDescriptorTag
_audioDecoderBytes = descr2.DSID;
//compare the bytes to get the aacaot/aottype
//match first byte
switch (_audioDecoderBytes[0])
{
case 0x12:
default:
//AAC LC - 12 10
_audioCodecType = 1;
break;
case 0x0a:
//AAC Main - 0A 10
_audioCodecType = 0;
break;
case 0x11:
case 0x13:
//AAC LC SBR - 11 90 & 13 xx
_audioCodecType = 2;
break;
}
//we want to break out of top level for loop
e = 99;
break;
}
}
}
}
}
}
}
//stsc - has Records
Mp4Atom stsc = stbl.Lookup(Mp4Atom.TypeToInt("stsc"), 0);
if (stsc != null)
{
log.Debug("Sample to chunk atom found");
_audioSamplesToChunks = stsc.Records;
log.Debug(string.Format("Record count: {0}", _audioSamplesToChunks.Count));
Mp4Atom.Record rec = _audioSamplesToChunks[0];
log.Debug(string.Format("Record data: Description index={0} Samples per chunk={1}", rec.SampleDescriptionIndex, rec.SamplesPerChunk));
}
//stsz - has Samples
Mp4Atom stsz = stbl.Lookup(Mp4Atom.TypeToInt("stsz"), 0);
if (stsz != null)
{
log.Debug("Sample size atom found");
_audioSamples = stsz.Samples;
//vector full of integers
log.Debug(string.Format("Sample size: {0}", stsz.SampleSize));
log.Debug(string.Format("Sample count: {0}", _audioSamples.Count));
}
//stco - has Chunks
Mp4Atom stco = stbl.Lookup(Mp4Atom.TypeToInt("stco"), 0);
if (stco != null)
{
log.Debug("Chunk offset atom found");
//vector full of integers
_audioChunkOffsets = stco.Chunks;
log.Debug(string.Format("Chunk count: {0}", _audioChunkOffsets.Count));
}
//stts - has TimeSampleRecords
Mp4Atom stts = stbl.Lookup(Mp4Atom.TypeToInt("stts"), 0);
if (stts != null)
{
log.Debug("Time to sample atom found");
List<Mp4Atom.TimeSampleRecord> records = stts.TimeToSamplesRecords;
log.Debug(string.Format("Record count: {0}", records.Count));
Mp4Atom.TimeSampleRecord rec = records[0];
log.Debug(string.Format("Record data: Consecutive samples={0} Duration={1}", rec.ConsecutiveSamples, rec.SampleDuration));
//if we have 1 record then all samples have the same duration
if (records.Count > 1)
{
//TODO: handle audio samples with varying durations
log.Debug("Audio samples have differing durations, audio playback may fail");
}
_audioSampleDuration = rec.SampleDuration;
}
}
}
}
}
}
//real duration
StringBuilder sb = new StringBuilder();
double clipTime = ((double)_duration / (double)_timeScale);
log.Debug(string.Format("Clip time: {0}", clipTime));
int minutes = (int)(clipTime / 60);
if (minutes > 0)
{
sb.Append(minutes);
sb.Append('.');
}
//formatter for seconds / millis
//NumberFormat df = DecimalFormat.getInstance();
//df.setMaximumFractionDigits(2);
//sb.append(df.format((clipTime % 60)));
sb.Append(clipTime % 60);
_formattedDuration = sb.ToString();
log.Debug(string.Format("Time: {0}", _formattedDuration));
break;
case 1835295092: //mdat
topAtoms++;
long dataSize = 0L;
Mp4Atom mdat = atom;
dataSize = mdat.Size;
//log.debug("{}", ToStringBuilder.reflectionToString(mdat));
_mdatOffset = _inputStream.Offset - dataSize;
log.Debug(string.Format("File size: {0} mdat size: {1}", _file.Length, dataSize));
break;
case 1718773093: //free
case 2003395685: //wide
break;
default:
log.Warn(string.Format("Unexpected atom: {}", Mp4Atom.IntToType(atom.Type)));
break;
}
}
//add the tag name (size) to the offsets
_moovOffset += 8;
_mdatOffset += 8;
log.Debug(string.Format("Offsets moov: {0} mdat: {1}", _moovOffset, _mdatOffset));
}
catch (Exception ex)
{
log.Error("Exception decoding header / atoms", ex);
}
}
public long Position
{
get
{
return _inputStream.Offset;
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
public bool HasMoreTags()
{
return _currentFrame < _frames.Count;
}
public ITag ReadTag()
{
lock (this.SyncRoot)
{
ITag tag = null;
//empty-out the pre-streaming tags first
if (_firstTags.Count > 0)
{
//log.debug("Returning pre-tag");
// Return first tags before media data
tag = _firstTags.First.Value;
_firstTags.RemoveFirst();
return tag;
}
//log.debug("Read tag - sample {} prevFrameSize {} audio: {} video: {}", new Object[]{currentSample, prevFrameSize, audioCount, videoCount});
//get the current frame
Mp4Frame frame = _frames[_currentFrame];
log.Debug(string.Format("Playback #{0} {1}", _currentFrame, frame));
int sampleSize = frame.Size;
int time = (int)Math.Round(frame.Time * 1000.0);
//log.debug("Read tag - dst: {} base: {} time: {}", new Object[]{frameTs, baseTs, time});
long samplePos = frame.Offset;
//log.debug("Read tag - samplePos {}", samplePos);
//determine frame type and packet body padding
byte type = frame.Type;
//create a byte buffer of the size of the sample
byte[] data = new byte[sampleSize + 2];
try
{
Array.Copy(Mp4Reader.PREFIX_AUDIO_FRAME, data, Mp4Reader.PREFIX_AUDIO_FRAME.Length);
//do we need to add the mdat offset to the sample position?
_fs.Position = samplePos;
_fs.Read(data, Mp4Reader.PREFIX_AUDIO_FRAME.Length, sampleSize);
}
catch (Exception ex)
{
log.Error("Error on channel position / read", ex);
}
//create the tag
tag = new Tag(type, time, data.Length, data, _prevFrameSize);
//increment the frame number
_currentFrame++;
//set the frame / tag size
_prevFrameSize = tag.BodySize;
//log.debug("Tag: {}", tag);
return tag;
}
}
public void Close()
{
_inputStream.Close();
}
public bool HasVideo()
{
return false;
}
#endregion
public void SetAudioCodecId(String audioCodecId)
{
this._audioCodecId = audioCodecId;
}
/// <summary>
/// Tag sequence
/// MetaData, Audio config, remaining audio
///
/// Packet prefixes:
/// af 00 ... 06 = Audio extra data (first audio packet)
/// af 01 = Audio frame
///
/// Audio extra data(s):
/// af 00 = Prefix
/// 11 90 4f 14 = AAC Main = aottype 0
/// 12 10 = AAC LC = aottype 1
/// 13 90 56 e5 a5 48 00 = HE-AAC SBR = aottype 2
/// 06 = Suffix
///
/// Still not absolutely certain about this order or the bytes - need to verify later
/// </summary>
private void CreatePreStreamingTags()
{
log.Debug("Creating pre-streaming tags");
ByteBuffer body = ByteBuffer.Allocate(41);
body.AutoExpand = true;
body.Put(new byte[] { (byte)0xaf, (byte)0 }); //prefix
if (_audioDecoderBytes != null)
{
body.Put(_audioDecoderBytes);
}
else
{
//default to aac-lc when the esds doesnt contain descripter bytes
body.Put(Mp4Reader.AUDIO_CONFIG_FRAME_AAC_LC);
}
body.Put((byte)0x06); //suffix
ITag tag = new Tag(IOConstants.TYPE_AUDIO, 0, (int)body.Length, body.ToArray(), _prevFrameSize);
//add tag
_firstTags.AddLast(tag);
}
/// <summary>
/// Create tag for metadata event.
/// </summary>
/// <returns></returns>
ITag CreateFileMeta()
{
log.Debug("Creating onMetaData");
// Create tag for onMetaData event
ByteBuffer buf = ByteBuffer.Allocate(1024);
buf.AutoExpand = true;
AMFWriter output = new AMFWriter(buf);
output.WriteString("onMetaData");
Hashtable props = new Hashtable();
// Duration property
props.Add("duration", ((double)_duration / (double)_timeScale));
// Audio codec id - watch for mp3 instead of aac
props.Add("audiocodecid", _audioCodecId);
props.Add("aacaot", _audioCodecType);
props.Add("audiosamplerate", _audioTimeScale);
props.Add("audiochannels", _audioChannels);
props.Add("moovposition", _moovOffset);
//tags will only appear if there is an "ilst" atom in the file
//props.put("tags", "");
props.Add("canSeekToEnd", false);
output.WriteAssociativeArray(ObjectEncoding.AMF0, props);
buf.Flip();
//now that all the meta properties are done, update the duration
_duration = (long)Math.Round(_duration * 1000d);
ITag result = new Tag(IOConstants.TYPE_METADATA, 0, buf.Limit, buf.ToArray(), 0);
return result;
}
/// <summary>
/// Performs frame analysis and generates metadata for use in seeking. All the frames are analyzed and sorted together based on time and offset.
/// </summary>
public void AnalyzeFrames()
{
log.Debug("Analyzing frames");
// tag == sample
int sample = 1;
long pos = 0;
//add the audio frames / samples / chunks
for (int i = 0; i < _audioSamplesToChunks.Count; i++)
{
Mp4Atom.Record record = _audioSamplesToChunks[i];
int firstChunk = record.FirstChunk;
int lastChunk = _audioChunkOffsets.Count;
if (i < _audioSamplesToChunks.Count - 1)
{
Mp4Atom.Record nextRecord = _audioSamplesToChunks[i + 1];
lastChunk = nextRecord.FirstChunk - 1;
}
for (int chunk = firstChunk; chunk <= lastChunk; chunk++)
{
int sampleCount = record.SamplesPerChunk;
pos = _audioChunkOffsets[chunk - 1];
while (sampleCount > 0)
{
//calculate ts
double ts = (_audioSampleDuration * (sample - 1)) / _audioTimeScale;
//sample size
int size = _audioSamples[sample - 1];
//create a frame
Mp4Frame frame = new Mp4Frame();
frame.Offset = pos;
frame.Size = size;
frame.Time = ts;
frame.Type = IOConstants.TYPE_AUDIO;
_frames.Add(frame);
//log.debug("Sample #{} {}", sample, frame);
//inc and dec stuff
pos += size;
sampleCount--;
sample++;
}
}
}
//sort the frames
_frames.Sort();
log.Debug(string.Format("Frames count: {0}", _frames.Count));
}
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Telerik.JustMock.Core.Castle.DynamicProxy.Contributors
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using Telerik.JustMock.Core.Castle.DynamicProxy.Generators;
using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters;
using Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using Telerik.JustMock.Core.Castle.DynamicProxy.Internal;
using Telerik.JustMock.Core.Castle.DynamicProxy.Tokens;
internal class ClassProxyTargetContributor : CompositeTypeContributor
{
private readonly IList<MethodInfo> methodsToSkip;
private readonly Type targetType;
public ClassProxyTargetContributor(Type targetType, IList<MethodInfo> methodsToSkip, INamingScope namingScope)
: base(namingScope)
{
this.targetType = targetType;
this.methodsToSkip = methodsToSkip;
}
protected override IEnumerable<MembersCollector> CollectElementsToProxyInternal(IProxyGenerationHook hook)
{
Debug.Assert(hook != null, "hook != null");
var targetItem = new ClassMembersCollector(targetType) { Logger = Logger };
targetItem.CollectMembersToProxy(hook);
yield return targetItem;
foreach (var @interface in interfaces)
{
var item = new InterfaceMembersOnClassCollector(@interface, true,
targetType.GetTypeInfo().GetRuntimeInterfaceMap(@interface)) { Logger = Logger };
item.CollectMembersToProxy(hook);
yield return item;
}
}
protected override MethodGenerator GetMethodGenerator(MetaMethod method, ClassEmitter @class,
ProxyGenerationOptions options,
OverrideMethodDelegate overrideMethod)
{
if (methodsToSkip.Contains(method.Method))
{
return null;
}
if (!method.Proxyable)
{
return new MinimialisticMethodGenerator(method,
overrideMethod);
}
if (ExplicitlyImplementedInterfaceMethod(method))
{
return ExplicitlyImplementedInterfaceMethodGenerator(method, @class, options, overrideMethod);
}
var invocation = GetInvocationType(method, @class, options);
GetTargetExpressionDelegate getTargetTypeExpression = (c, m) => new TypeTokenExpression(targetType);
return new MethodWithInvocationGenerator(method,
@class.GetField("__interceptors"),
invocation,
getTargetTypeExpression,
getTargetTypeExpression,
overrideMethod,
null);
}
private Type BuildInvocationType(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options)
{
var methodInfo = method.Method;
if (!method.HasTarget)
{
return new InheritanceInvocationTypeGenerator(targetType,
method,
null, null)
.Generate(@class, options, namingScope)
.BuildType();
}
var callback = CreateCallbackMethod(@class, methodInfo, method.MethodOnTarget);
return new InheritanceInvocationTypeGenerator(callback.DeclaringType,
method,
callback, null)
.Generate(@class, options, namingScope)
.BuildType();
}
private MethodBuilder CreateCallbackMethod(ClassEmitter emitter, MethodInfo methodInfo, MethodInfo methodOnTarget)
{
var targetMethod = methodOnTarget ?? methodInfo;
var callBackMethod = emitter.CreateMethod(namingScope.GetUniqueName(methodInfo.Name + "_callback"), targetMethod);
if (targetMethod.IsGenericMethod)
{
targetMethod = targetMethod.MakeGenericMethod(callBackMethod.GenericTypeParams.AsTypeArray());
}
var exps = new Expression[callBackMethod.Arguments.Length];
for (var i = 0; i < callBackMethod.Arguments.Length; i++)
{
exps[i] = callBackMethod.Arguments[i].ToExpression();
}
// invocation on base class
callBackMethod.CodeBuilder.AddStatement(
new ReturnStatement(
new MethodInvocationExpression(SelfReference.Self,
targetMethod,
exps)));
return callBackMethod.MethodBuilder;
}
private bool ExplicitlyImplementedInterfaceMethod(MetaMethod method)
{
return method.MethodOnTarget.IsPrivate;
}
private MethodGenerator ExplicitlyImplementedInterfaceMethodGenerator(MetaMethod method, ClassEmitter @class,
ProxyGenerationOptions options,
OverrideMethodDelegate overrideMethod)
{
var @delegate = GetDelegateType(method, @class, options);
var contributor = GetContributor(@delegate, method);
var invocation = new InheritanceInvocationTypeGenerator(targetType, method, null, contributor)
.Generate(@class, options, namingScope)
.BuildType();
return new MethodWithInvocationGenerator(method,
@class.GetField("__interceptors"),
invocation,
(c, m) => new TypeTokenExpression(targetType),
overrideMethod,
contributor);
}
private IInvocationCreationContributor GetContributor(Type @delegate, MetaMethod method)
{
if (@delegate.GetTypeInfo().IsGenericType == false)
{
return new InvocationWithDelegateContributor(@delegate, targetType, method, namingScope);
}
return new InvocationWithGenericDelegateContributor(@delegate,
method,
new FieldReference(InvocationMethods.ProxyObject));
}
private Type GetDelegateType(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options)
{
var scope = @class.ModuleScope;
var key = new CacheKey(
typeof(Delegate).GetTypeInfo(),
targetType,
new[] { method.MethodOnTarget.ReturnType }
.Concat(ArgumentsUtil.GetTypes(method.MethodOnTarget.GetParameters())).
ToArray(),
null);
var type = scope.GetFromCache(key);
if (type != null)
{
return type;
}
type = new DelegateTypeGenerator(method, targetType)
.Generate(@class, options, namingScope)
.BuildType();
scope.RegisterInCache(key, type);
return type;
}
private Type GetInvocationType(MetaMethod method, ClassEmitter @class, ProxyGenerationOptions options)
{
// NOTE: No caching since invocation is tied to this specific proxy type via its invocation method
return BuildInvocationType(method, @class, options);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.IdentityModel.Tokens;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
namespace System.ServiceModel.Security.Tokens
{
internal sealed class DerivedKeySecurityToken : SecurityToken
{
// public const string DefaultLabel = "WS-SecureConversationWS-SecureConversation";
private static readonly byte[] s_DefaultLabel = new byte[]
{
(byte)'W', (byte)'S', (byte)'-', (byte)'S', (byte)'e', (byte)'c', (byte)'u', (byte)'r', (byte)'e',
(byte)'C', (byte)'o', (byte)'n', (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'a', (byte)'t', (byte)'i', (byte)'o', (byte)'n',
(byte)'W', (byte)'S', (byte)'-', (byte)'S', (byte)'e', (byte)'c', (byte)'u', (byte)'r', (byte)'e',
(byte)'C', (byte)'o', (byte)'n', (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'a', (byte)'t', (byte)'i', (byte)'o', (byte)'n'
};
public const int DefaultNonceLength = 16;
public const int DefaultDerivedKeyLength = 32;
// fields are read from in this class, but lack of implemenation means we never assign them yet.
private string _id;
private byte[] _key;
private string _label;
private byte[] _nonce;
private ReadOnlyCollection<SecurityKey> _securityKeys;
internal DerivedKeySecurityToken(int generation, int offset, int length,
string label, int minNonceLength, SecurityToken tokenToDerive,
SecurityKeyIdentifierClause tokenToDeriveIdentifier,
string derivationAlgorithm, string id)
{
byte[] nonce = new byte[minNonceLength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(nonce);
Initialize(id, generation, offset, length, label, nonce, tokenToDerive, tokenToDeriveIdentifier, derivationAlgorithm);
}
// create from xml
internal DerivedKeySecurityToken(int generation, int offset, int length,
string label, byte[] nonce, SecurityToken tokenToDerive,
SecurityKeyIdentifierClause tokenToDeriveIdentifier, string derivationAlgorithm, string id)
{
Initialize(id, generation, offset, length, label, nonce, tokenToDerive, tokenToDeriveIdentifier, derivationAlgorithm, false);
}
public override string Id
{
get { return _id; }
}
public override DateTime ValidFrom
{
get { return TokenToDerive.ValidFrom; }
}
public override DateTime ValidTo
{
get { return TokenToDerive.ValidTo; }
}
public string KeyDerivationAlgorithm { get; private set; }
public int Generation { get; private set; } = -1;
public string Label
{
get { return _label; }
}
public int Length { get; private set; } = -1;
internal byte[] Nonce
{
get { return _nonce; }
}
public int Offset { get; private set; } = -1;
internal SecurityToken TokenToDerive { get; private set; }
internal SecurityKeyIdentifierClause TokenToDeriveIdentifier { get; private set; }
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
if (_securityKeys == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.DerivedKeyNotInitialized));
}
return _securityKeys;
}
}
public byte[] GetKeyBytes()
{
return SecurityUtils.CloneBuffer(_key);
}
public byte[] GetNonce()
{
return SecurityUtils.CloneBuffer(_nonce);
}
internal bool TryGetSecurityKeys(out ReadOnlyCollection<SecurityKey> keys)
{
keys = _securityKeys;
return (keys != null);
}
public override string ToString()
{
StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
writer.WriteLine("DerivedKeySecurityToken:");
writer.WriteLine(" Generation: {0}", Generation);
writer.WriteLine(" Offset: {0}", Offset);
writer.WriteLine(" Length: {0}", Length);
writer.WriteLine(" Label: {0}", Label);
writer.WriteLine(" Nonce: {0}", Convert.ToBase64String(Nonce));
writer.WriteLine(" TokenToDeriveFrom:");
using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
{
xmlWriter.Formatting = Formatting.Indented;
SecurityStandardsManager.DefaultInstance.SecurityTokenSerializer.WriteKeyIdentifierClause(XmlDictionaryWriter.CreateDictionaryWriter(xmlWriter), TokenToDeriveIdentifier);
}
return writer.ToString();
}
private void Initialize(string id, int generation, int offset, int length, string label, byte[] nonce,
SecurityToken tokenToDerive, SecurityKeyIdentifierClause tokenToDeriveIdentifier, string derivationAlgorithm)
{
Initialize(id, generation, offset, length, label, nonce, tokenToDerive, tokenToDeriveIdentifier, derivationAlgorithm, true);
}
private void Initialize(string id, int generation, int offset, int length, string label, byte[] nonce,
SecurityToken tokenToDerive, SecurityKeyIdentifierClause tokenToDeriveIdentifier, string derivationAlgorithm,
bool initializeDerivedKey)
{
if (tokenToDerive == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(tokenToDerive));
}
if (!SecurityUtils.IsSupportedAlgorithm(derivationAlgorithm, tokenToDerive))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.DerivedKeyCannotDeriveFromSecret));
}
if (length == -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(length)));
}
if (offset == -1 && generation == -1)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.DerivedKeyPosAndGenNotSpecified);
}
if (offset >= 0 && generation >= 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.DerivedKeyPosAndGenBothSpecified);
}
_id = id ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(id));
_label = label;
_nonce = nonce ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(nonce));
Length = length;
Offset = offset;
Generation = generation;
TokenToDerive = tokenToDerive;
TokenToDeriveIdentifier = tokenToDeriveIdentifier ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(tokenToDeriveIdentifier));
KeyDerivationAlgorithm = derivationAlgorithm;
if (initializeDerivedKey)
{
InitializeDerivedKey(Length);
}
}
internal void InitializeDerivedKey(int maxKeyLength)
{
if (_key != null)
{
return;
}
if (Length > maxKeyLength)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.DerivedKeyLengthTooLong, Length, maxKeyLength));
}
_key = SecurityUtils.GenerateDerivedKey(TokenToDerive, KeyDerivationAlgorithm,
(_label != null ? Encoding.UTF8.GetBytes(_label) : s_DefaultLabel), _nonce, Length * 8,
((Offset >= 0) ? Offset : Generation * Length));
if ((_key == null) || (_key.Length == 0))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.DerivedKeyCannotDeriveFromSecret);
}
List<SecurityKey> temp = new List<SecurityKey>(1);
temp.Add(new InMemorySymmetricSecurityKey(_key, false));
_securityKeys = temp.AsReadOnly();
}
internal static void EnsureAcceptableOffset(int offset, int generation, int length, int maxOffset)
{
if (offset != -1)
{
if (offset > maxOffset)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(SR.DerivedKeyTokenOffsetTooHigh, offset, maxOffset)));
}
}
else
{
int effectiveOffset = generation * length;
if ((effectiveOffset < generation && effectiveOffset < length) || effectiveOffset > maxOffset)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(SR.DerivedKeyTokenGenerationAndLengthTooHigh, generation, length, maxOffset)));
}
}
}
}
}
| |
//BSD, 2014-present, WinterDev
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// Adaptation for high precision colors has been sponsored by
// Liberty Technology Systems, Inc., visit http://lib-sys.com
//
// Liberty Technology Systems, Inc. is the provider of
// PostScript and PDF technology for software developers.
//
//----------------------------------------------------------------------------
using System;
using PixelFarm.Drawing;
using CO = PixelFarm.Drawing.Internal.CO;
namespace PixelFarm.CpuBlit.PixelProcessing
{
/// <summary>
/// change destination alpha change with red color from source
/// </summary>
public class PixelBlenderGrey : PixelBlender32
{
internal override void BlendPixel(int[] dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
fixed (int* head = &dstBuffer[arrayOffset])
{
BlendPixel32Internal(head, srcColor);
}
}
}
internal override unsafe void BlendPixel32(int* dstPtr, Color srcColor)
{
BlendPixel32Internal(dstPtr, srcColor);
}
internal override void BlendPixels(int[] dstBuffer,
int arrayElemOffset,
Color[] srcColors,
int srcColorOffset,
byte[] covers,
int coversIndex,
bool firstCoverForAll, int count)
{
if (firstCoverForAll)
{
int cover = covers[coversIndex];
if (cover == 255)
{
unsafe
{
fixed (int* head = &dstBuffer[arrayElemOffset])
{
int* header2 = head;
if (count % 2 != 0)
{
//odd
//
BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
header2++;//move next
count--;
}
//now count is even number
while (count > 0)
{
//now count is even number
//---------
//1
BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
header2++;//move next
count--;
//---------
//2
BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
header2++;//move next
count--;
}
}
}
}
else
{
unsafe
{
fixed (int* head = &dstBuffer[arrayElemOffset])
{
int* header2 = head;
if (count % 2 != 0)
{
//odd
//
BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
header2++;//move next
count--;
}
while (count > 0)
{
//Blend32PixelInternal(header2, sourceColors[sourceColorsOffset++].NewFromChangeCoverage(cover));
//1.
BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
header2++;//move next
count--;
//2.
BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
header2++;//move next
count--;
}
}
}
}
}
else
{
unsafe
{
fixed (int* dstHead = &dstBuffer[arrayElemOffset])
{
int* dstBufferPtr = dstHead;
do
{
//cover may diff in each loop
int cover = covers[coversIndex++];
if (cover == 255)
{
BlendPixel32Internal(dstBufferPtr, srcColors[srcColorOffset]);
}
else
{
BlendPixel32Internal(dstBufferPtr, srcColors[srcColorOffset].NewFromChangeCoverage(cover));
}
dstBufferPtr++;
++srcColorOffset;
}
while (--count != 0);
}
}
}
}
internal override void CopyPixel(int[] dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
fixed (int* ptr = &dstBuffer[arrayOffset])
{
//TODO: consider use memcpy() impl***
*ptr = srcColor.ToGrayValueARGB();
}
}
}
internal override void CopyPixels(int[] dstBuffer, int arrayOffset, Color srcColor, int count)
{
unsafe
{
unchecked
{
fixed (int* ptr_byte = &dstBuffer[arrayOffset])
{
//TODO: consider use memcpy() impl***
//byte y = (byte)(((srcColor.R * 77) + (srcColor.G * 151) + (srcColor.B * 28)) >> 8);
//srcColor = new Color(srcColor.A, y, y, y);
int* ptr = ptr_byte;
int argb = srcColor.ToGrayValueARGB();
//---------
if ((count % 2) != 0)
{
*ptr = argb;
ptr++; //move next
count--;
}
while (count > 0)
{
//-----------
//1.
*ptr = argb;
ptr++; //move next
count--;
//-----------
//2
*ptr = argb;
ptr++; //move next
count--;
}
}
}
}
}
static unsafe void BlendPixel32Internal(int* dstPtr, Color srcColor, int coverageValue)
{
//calculate new alpha
int src_a = (byte)((srcColor.A * coverageValue + 255) >> 8);
//after apply the alpha
unchecked
{
if (src_a == 255)
{
*dstPtr = srcColor.ToGrayValueARGB(); //just copy
}
else
{
byte y = (byte)(((srcColor.R * 77) + (srcColor.G * 151) + (srcColor.B * 28)) >> 8);
srcColor = new Color(srcColor.A, y, y, y);
int dest = *dstPtr;
//separate each component
byte a = (byte)((dest >> CO.A_SHIFT) & 0xff);
byte r = (byte)((dest >> CO.R_SHIFT) & 0xff);
byte g = (byte)((dest >> CO.G_SHIFT) & 0xff);
byte b = (byte)((dest >> CO.B_SHIFT) & 0xff);
*dstPtr =
((byte)((src_a + a) - ((src_a * a + BASE_MASK) >> CO.BASE_SHIFT)) << CO.A_SHIFT) |
((byte)(((srcColor.R - r) * src_a + (r << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.R_SHIFT) |
((byte)(((srcColor.G - g) * src_a + (g << CO.BASE_SHIFT)) >> (int)CO.BASE_SHIFT) << CO.G_SHIFT) |
((byte)(((srcColor.B - b) * src_a + (b << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.B_SHIFT);
}
}
}
static unsafe void BlendPixel32Internal(int* dstPtr, Color srcColor)
{
unchecked
{
//convert srcColor to grey-scale image
if (srcColor.A == 255)
{
*dstPtr = srcColor.ToGrayValueARGB(); //just copy
}
else
{
byte y = (byte)(((srcColor.R * 77) + (srcColor.G * 151) + (srcColor.B * 28)) >> 8);
srcColor = new Color(srcColor.A, y, y, y);
int dest = *dstPtr;
//separate each component
byte a = (byte)((dest >> CO.A_SHIFT) & 0xff);
byte r = (byte)((dest >> CO.R_SHIFT) & 0xff);
byte g = (byte)((dest >> CO.G_SHIFT) & 0xff);
byte b = (byte)((dest >> CO.B_SHIFT) & 0xff);
byte src_a = srcColor.A;
*dstPtr =
((byte)((src_a + a) - ((src_a * a + BASE_MASK) >> CO.BASE_SHIFT)) << CO.A_SHIFT) |
((byte)(((srcColor.R - r) * src_a + (r << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.B_SHIFT) |
((byte)(((srcColor.G - g) * src_a + (g << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.G_SHIFT) |
((byte)(((srcColor.B - b) * src_a + (b << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.B_SHIFT);
}
}
}
internal override void BlendPixels(TempMemPtr dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
int* ptr = (int*)dstBuffer.Ptr;
int* head = &ptr[arrayOffset];
{
BlendPixel32Internal(head, srcColor);
}
}
}
internal override void BlendPixels(TempMemPtr dstBuffer1, int arrayElemOffset, Color[] srcColors, int srcColorOffset, byte[] covers, int coversIndex, bool firstCoverForAll, int count)
{
if (firstCoverForAll)
{
int cover = covers[coversIndex];
if (cover == 255)
{
unsafe
{
int* dstBuffer = (int*)dstBuffer1.Ptr;
int* head = &dstBuffer[arrayElemOffset];
{
int* header2 = (int*)(IntPtr)head;
if (count % 2 != 0)
{
//odd
//
BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
header2++;//move next
count--;
}
//now count is even number
while (count > 0)
{
//now count is even number
//---------
//1
BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
header2++;//move next
count--;
//---------
//2
BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
header2++;//move next
count--;
}
}
}
}
else
{
unsafe
{
int* dstBuffer = (int*)dstBuffer1.Ptr;
int* head = &dstBuffer[arrayElemOffset];
{
int* header2 = (int*)(IntPtr)head;
if (count % 2 != 0)
{
//odd
//
BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
header2++;//move next
count--;
}
while (count > 0)
{
//Blend32PixelInternal(header2, sourceColors[sourceColorsOffset++].NewFromChangeCoverage(cover));
//1.
BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
header2++;//move next
count--;
//2.
BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
header2++;//move next
count--;
}
}
}
}
}
else
{
unsafe
{
int* dstBuffer = (int*)dstBuffer1.Ptr;
int* dstHead = &dstBuffer[arrayElemOffset];
{
int* dstBufferPtr = dstHead;
do
{
//cover may diff in each loop
int cover = covers[coversIndex++];
if (cover == 255)
{
BlendPixel32Internal(dstBufferPtr, srcColors[srcColorOffset]);
}
else
{
BlendPixel32Internal(dstBufferPtr, srcColors[srcColorOffset].NewFromChangeCoverage(cover));
}
dstBufferPtr++;
++srcColorOffset;
}
while (--count != 0);
}
}
}
}
internal override void CopyPixels(TempMemPtr dstBuffer, int arrayOffset, Color srcColor, int count)
{
unsafe
{
int* ptr1 = (int*)dstBuffer.Ptr;
int* ptr_byte = &ptr1[arrayOffset];
{
//TODO: consider use memcpy() impl***
int* ptr = ptr_byte;
int argb = srcColor.ToGrayValueARGB();
//---------
if ((count % 2) != 0)
{
*ptr = argb;
ptr++; //move next
count--;
}
while (count > 0)
{
//-----------
//1.
*ptr = argb;
ptr++; //move next
count--;
//-----------
//2
*ptr = argb;
ptr++; //move next
count--;
}
}
}
}
internal override void CopyPixel(TempMemPtr dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
int* ptr1 = (int*)dstBuffer.Ptr;
int* ptr = &ptr1[arrayOffset];
{
//TODO: consider use memcpy() impl***
*ptr = srcColor.ToGrayValueARGB();
}
}
}
}
static class ColorExtensions
{
/// <summary>
/// with ratio, R77,B151,B28
/// </summary>
/// <param name="srcColor"></param>
/// <returns></returns>
public static int ToGrayValueARGB(this in Color srcColor)
{
byte y = (byte)(((srcColor.R * 77) + (srcColor.G * 151) + (srcColor.B * 28)) >> 8);
return ((srcColor.A << 24) | (y << 16) | (y << 8) | y);
}
}
public abstract class CustomPixelBlender : PixelBlender32
{
internal sealed override void BlendPixel(int[] dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
fixed (int* head = &dstBuffer[arrayOffset])
{
BlendPixel32Internal(head, srcColor);
}
}
}
internal sealed override unsafe void BlendPixel32(int* dstPtr, Color srcColor)
{
BlendPixel32Internal(dstPtr, srcColor);
}
internal sealed override void BlendPixels(int[] dstBuffer,
int arrayElemOffset,
Color[] srcColors,
int srcColorOffset,
byte[] covers,
int coversIndex,
bool firstCoverForAll, int count)
{
if (firstCoverForAll)
{
int cover = covers[coversIndex];
if (cover == 255)
{
unsafe
{
fixed (int* head = &dstBuffer[arrayElemOffset])
{
int* header2 = (int*)(IntPtr)head;
if (count % 2 != 0)
{
//odd
//
BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
header2++;//move next
count--;
}
//now count is even number
while (count > 0)
{
//now count is even number
//---------
//1
BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
header2++;//move next
count--;
//---------
//2
BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
header2++;//move next
count--;
}
}
}
}
else
{
unsafe
{
fixed (int* head = &dstBuffer[arrayElemOffset])
{
int* header2 = (int*)(IntPtr)head;
if (count % 2 != 0)
{
//odd
//
BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
header2++;//move next
count--;
}
while (count > 0)
{
//Blend32PixelInternal(header2, sourceColors[sourceColorsOffset++].NewFromChangeCoverage(cover));
//1.
BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
header2++;//move next
count--;
//2.
BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
header2++;//move next
count--;
}
}
}
}
}
else
{
unsafe
{
fixed (int* dstHead = &dstBuffer[arrayElemOffset])
{
int* dstBufferPtr = dstHead;
do
{
//cover may diff in each loop
int cover = covers[coversIndex++];
if (cover == 255)
{
BlendPixel32Internal(dstBufferPtr, srcColors[srcColorOffset]);
}
else
{
BlendPixel32Internal(dstBufferPtr, srcColors[srcColorOffset].NewFromChangeCoverage(cover));
}
dstBufferPtr++;
++srcColorOffset;
}
while (--count != 0);
}
}
}
}
internal sealed override void CopyPixel(int[] dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
fixed (int* ptr = &dstBuffer[arrayOffset])
{
//TODO: consider use memcpy() impl***
*ptr = srcColor.ToGrayValueARGB();
}
}
}
internal sealed override void CopyPixels(int[] dstBuffer, int arrayOffset, Color srcColor, int count)
{
unsafe
{
unchecked
{
fixed (int* ptr_byte = &dstBuffer[arrayOffset])
{
//TODO: consider use memcpy() impl***
int* ptr = ptr_byte;
int argb = srcColor.ToGrayValueARGB();
//---------
if ((count % 2) != 0)
{
*ptr = argb;
ptr++; //move next
count--;
}
while (count > 0)
{
//-----------
//1.
*ptr = argb;
ptr++; //move next
count--;
//-----------
//2
*ptr = argb;
ptr++; //move next
count--;
}
}
}
}
}
protected abstract unsafe void BlendPixel32Internal(int* dstPtr, Color srcColor, int coverageValue);
protected abstract unsafe void BlendPixel32Internal(int* dstPtr, Color srcColor);
internal sealed override void BlendPixels(TempMemPtr dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
int* ptr = (int*)dstBuffer.Ptr;
int* head = &ptr[arrayOffset];
{
BlendPixel32Internal(head, srcColor);
}
}
}
internal sealed override void BlendPixels(TempMemPtr dstBuffer1, int arrayElemOffset, Color[] srcColors, int srcColorOffset, byte[] covers, int coversIndex, bool firstCoverForAll, int count)
{
if (firstCoverForAll)
{
int cover = covers[coversIndex];
if (cover == 255)
{
unsafe
{
int* dstBuffer = (int*)dstBuffer1.Ptr;
int* head = &dstBuffer[arrayElemOffset];
{
int* header2 = (int*)(IntPtr)head;
if (count % 2 != 0)
{
//odd
//
BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
header2++;//move next
count--;
}
//now count is even number
while (count > 0)
{
//now count is even number
//---------
//1
BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
header2++;//move next
count--;
//---------
//2
BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
header2++;//move next
count--;
}
}
}
}
else
{
unsafe
{
int* dstBuffer = (int*)dstBuffer1.Ptr;
int* head = &dstBuffer[arrayElemOffset];
{
int* header2 = (int*)(IntPtr)head;
if (count % 2 != 0)
{
//odd
//
BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
header2++;//move next
count--;
}
while (count > 0)
{
//Blend32PixelInternal(header2, sourceColors[sourceColorsOffset++].NewFromChangeCoverage(cover));
//1.
BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
header2++;//move next
count--;
//2.
BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
header2++;//move next
count--;
}
}
}
}
}
else
{
unsafe
{
int* dstBuffer = (int*)dstBuffer1.Ptr;
int* dstHead = &dstBuffer[arrayElemOffset];
{
int* dstBufferPtr = dstHead;
do
{
//cover may diff in each loop
int cover = covers[coversIndex++];
if (cover == 255)
{
BlendPixel32Internal(dstBufferPtr, srcColors[srcColorOffset]);
}
else
{
BlendPixel32Internal(dstBufferPtr, srcColors[srcColorOffset].NewFromChangeCoverage(cover));
}
dstBufferPtr++;
++srcColorOffset;
}
while (--count != 0);
}
}
}
}
internal sealed override void CopyPixels(TempMemPtr dstBuffer, int arrayOffset, Color srcColor, int count)
{
unsafe
{
int* ptr1 = (int*)dstBuffer.Ptr;
int* ptr_byte = &ptr1[arrayOffset];
{
int* ptr = ptr_byte;
//---------
if ((count % 2) != 0)
{
BlendPixel32Internal(ptr, srcColor);
ptr++; //move next
count--;
}
while (count > 0)
{
//-----------
//1.
BlendPixel32Internal(ptr, srcColor);
ptr++; //move next
count--;
//-----------
//2
BlendPixel32Internal(ptr, srcColor);
ptr++; //move next
count--;
}
}
}
}
internal sealed override void CopyPixel(TempMemPtr dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
int* ptr1 = (int*)dstBuffer.Ptr;
int* ptr = &ptr1[arrayOffset];
{
BlendPixel32Internal(ptr, srcColor);
}
}
}
}
/// <summary>
/// apply mask to srcColor before send it to dest bmp
/// </summary>
public class PixelBlenderWithMask : PixelBlender32
{
TempMemPtr _maskInnerBuffer;
int _mask_shift;//default
PixelBlenderColorComponent _selectedMaskComponent;
public PixelBlenderWithMask()
{
SelectedMaskComponent = PixelBlenderColorComponent.R; //default
}
/// <summary>
/// set mask image, please note that size of mask must be the same size of the dest buffer
/// </summary>
/// <param name="maskBmp"></param>
public void SetMaskBitmap(MemBitmap maskBmp)
{
//please note that size of mask must be the same size of the dest buffer
_maskInnerBuffer = MemBitmap.GetBufferPtr(maskBmp);
}
public PixelBlenderColorComponent SelectedMaskComponent
{
get => _selectedMaskComponent;
set
{
_selectedMaskComponent = value;
switch (value)
{
default: throw new NotSupportedException();
case PixelBlenderColorComponent.A:
_mask_shift = CO.A_SHIFT;
break;
case PixelBlenderColorComponent.R:
_mask_shift = CO.R_SHIFT;
break;
case PixelBlenderColorComponent.G:
_mask_shift = CO.G_SHIFT;
break;
case PixelBlenderColorComponent.B:
_mask_shift = CO.B_SHIFT;
break;
}
}
}
Color NewColorFromMask(Color srcColor, int arrayOffset)
{
unsafe
{
int* buff = (int*)_maskInnerBuffer.Ptr;
return srcColor.NewFromChangeCoverage((byte)((buff[arrayOffset]) >> _mask_shift));
}
}
internal override void BlendPixel(int[] dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
fixed (int* head = &dstBuffer[arrayOffset])
{
BlendPixel32Internal(head, NewColorFromMask(srcColor, arrayOffset));
}
}
}
internal override unsafe void BlendPixel32(int* dstPtr, Color srcColor)
{
BlendPixel32Internal(dstPtr, srcColor);
}
internal override void BlendPixels(int[] dstBuffer,
int arrayElemOffset,
Color[] srcColors,
int srcColorOffset,
byte[] covers,
int coversIndex,
bool firstCoverForAll, int count)
{
if (firstCoverForAll)
{
int cover = covers[coversIndex];
if (cover == 255)
{
unsafe
{
fixed (int* head = &dstBuffer[arrayElemOffset])
{
int* header2 = head;
if (count % 2 != 0)
{
//odd
//
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
header2++;//move next
count--;
arrayElemOffset++;
}
//now count is even number
while (count > 0)
{
//now count is even number
//---------
//1
//BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
header2++;//move next
count--;
arrayElemOffset++;
//---------
//2
//BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
header2++;//move next
count--;
arrayElemOffset++;
}
}
}
}
else
{
unsafe
{
fixed (int* head = &dstBuffer[arrayElemOffset])
{
int* header2 = head;
if (count % 2 != 0)
{
//odd
//
//BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
arrayElemOffset++;
header2++;//move next
count--;
}
while (count > 0)
{
//Blend32PixelInternal(header2, sourceColors[sourceColorsOffset++].NewFromChangeCoverage(cover));
//1.
//BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
arrayElemOffset++;
header2++;//move next
count--;
//2.
//BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
arrayElemOffset++;
header2++;//move next
count--;
}
}
}
}
}
else
{
unsafe
{
fixed (int* dstHead = &dstBuffer[arrayElemOffset])
{
int* dstBufferPtr = dstHead;
do
{
//cover may diff in each loop
int cover = covers[coversIndex++];
if (cover == 255)
{
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset], arrayElemOffset));
}
else
{
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset].NewFromChangeCoverage(cover), arrayElemOffset));
}
arrayElemOffset++;
dstBufferPtr++;
++srcColorOffset;
}
while (--count != 0);
}
}
}
}
internal override void CopyPixel(int[] dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
unchecked
{
fixed (int* ptr = &dstBuffer[arrayOffset])
{
BlendPixel32(ptr, NewColorFromMask(srcColor, arrayOffset));
}
}
}
}
internal override void CopyPixels(int[] dstBuffer, int arrayOffset, Color srcColor, int count)
{
unsafe
{
fixed (int* ptr_byte = &dstBuffer[arrayOffset])
{
//TODO: consider use memcpy() impl***
int* ptr = ptr_byte;
Color newColor = NewColorFromMask(srcColor, arrayOffset);
//---------
if ((count % 2) != 0)
{
BlendPixel32(ptr, newColor);
arrayOffset++;//move next
ptr++; //move next
count--;
}
while (count > 0)
{
//-----------
newColor = NewColorFromMask(srcColor, arrayOffset);
//1.
BlendPixel32(ptr, newColor);
arrayOffset++;//move next
ptr++; //move next
count--;
//-----------
//2
newColor = NewColorFromMask(srcColor, arrayOffset);
//1.
BlendPixel32(ptr, newColor);
arrayOffset++;//move next
ptr++; //move next
count--;
}
}
}
}
static unsafe void BlendPixel32Internal(int* dstPtr, Color srcColor)
{
unchecked
{
if (srcColor.A == 255)
{
*dstPtr = srcColor.ToARGB(); //just copy
}
else
{
int dest = *dstPtr;
//separate each component
byte a = (byte)((dest >> CO.A_SHIFT) & 0xff);
byte r = (byte)((dest >> CO.R_SHIFT) & 0xff);
byte g = (byte)((dest >> CO.G_SHIFT) & 0xff);
byte b = (byte)((dest >> CO.B_SHIFT) & 0xff);
byte src_a = srcColor.A;
*dstPtr =
((byte)((src_a + a) - ((src_a * a + BASE_MASK) >> CO.BASE_SHIFT)) << CO.A_SHIFT) |
((byte)(((srcColor.R - r) * src_a + (r << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.R_SHIFT) |
((byte)(((srcColor.G - g) * src_a + (g << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.G_SHIFT) |
((byte)(((srcColor.B - b) * src_a + (b << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.B_SHIFT);
}
}
}
internal override void BlendPixels(TempMemPtr dst, int arrayOffset, Color srcColor)
{
unsafe
{
int* dstBuffer = (int*)dst.Ptr;
int* head = &dstBuffer[arrayOffset];
{
BlendPixel32Internal(head, NewColorFromMask(srcColor, arrayOffset));
}
}
}
internal override void BlendPixels(TempMemPtr dst, int arrayElemOffset, Color[] srcColors, int srcColorOffset, byte[] covers, int coversIndex, bool firstCoverForAll, int count)
{
if (firstCoverForAll)
{
int cover = covers[coversIndex];
if (cover == 255)
{
unsafe
{
int* dstBuffer = (int*)dst.Ptr;
int* head = &dstBuffer[arrayElemOffset];
{
int* header2 = head;
if (count % 2 != 0)
{
//odd
//
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
header2++;//move next
count--;
arrayElemOffset++;
}
//now count is even number
while (count > 0)
{
//now count is even number
//---------
//1
//BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
header2++;//move next
count--;
arrayElemOffset++;
//---------
//2
//BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
header2++;//move next
count--;
arrayElemOffset++;
}
}
}
}
else
{
unsafe
{
int* dstBuffer = (int*)dst.Ptr;
int* head = &dstBuffer[arrayElemOffset];
{
int* header2 = head;
if (count % 2 != 0)
{
//odd
//
//BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
arrayElemOffset++;
header2++;//move next
count--;
}
while (count > 0)
{
//Blend32PixelInternal(header2, sourceColors[sourceColorsOffset++].NewFromChangeCoverage(cover));
//1.
//BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
arrayElemOffset++;
header2++;//move next
count--;
//2.
//BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
arrayElemOffset++;
header2++;//move next
count--;
}
}
}
}
}
else
{
unsafe
{
int* dstBuffer = (int*)dst.Ptr;
int* head = &dstBuffer[arrayElemOffset];
{
int* dstBufferPtr = head;
do
{
//cover may diff in each loop
int cover = covers[coversIndex++];
if (cover == 255)
{
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset], arrayElemOffset));
}
else
{
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset].NewFromChangeCoverage(cover), arrayElemOffset));
}
arrayElemOffset++;
dstBufferPtr++;
++srcColorOffset;
}
while (--count != 0);
}
}
}
}
internal override void CopyPixels(TempMemPtr dst, int arrayOffset, Color srcColor, int count)
{
unsafe
{
int* dstBuffer = (int*)dst.Ptr;
int* ptr_byte = &dstBuffer[arrayOffset];
{
//TODO: consider use memcpy() impl***
int* ptr = ptr_byte;
Color newColor = NewColorFromMask(srcColor, arrayOffset);
//---------
if ((count % 2) != 0)
{
BlendPixel32(ptr, newColor);
arrayOffset++;//move next
ptr++; //move next
count--;
}
while (count > 0)
{
//-----------
newColor = NewColorFromMask(srcColor, arrayOffset);
//1.
BlendPixel32(ptr, newColor);
arrayOffset++;//move next
ptr++; //move next
count--;
//-----------
//2
newColor = NewColorFromMask(srcColor, arrayOffset);
//1.
BlendPixel32(ptr, newColor);
arrayOffset++;//move next
ptr++; //move next
count--;
}
}
}
}
internal override void CopyPixel(TempMemPtr dst, int arrayOffset, Color srcColor)
{
unsafe
{
int* dstBuffer = (int*)dst.Ptr;
int* ptr = &dstBuffer[arrayOffset];
{
BlendPixel32(ptr, NewColorFromMask(srcColor, arrayOffset));
}
}
}
}
public enum PixelBlenderColorComponent
{
A, //24
R, //16
G, //8
B //0
}
public enum EnableOutputColorComponent
{
EnableAll, //=0
A,
R,
G,
B
}
//TODO: review this again ...
/// <summary>
/// only apply to some dest color component
/// </summary>
public class PixelBlenderPerColorComponentWithMask : PixelBlender32
{
TempMemPtr _maskInnerBuffer;
int _mask_shift;//default
PixelBlenderColorComponent _selectedMaskComponent;
EnableOutputColorComponent _selectedDestMaskComponent;
public PixelBlenderPerColorComponentWithMask()
{
SelectedMaskComponent = PixelBlenderColorComponent.R; //default
EnableOutputColorComponent = EnableOutputColorComponent.EnableAll;
}
/// <summary>
/// set mask image, please note that size of mask must be the same size of the dest buffer
/// </summary>
/// <param name="maskBmp"></param>
public void SetMaskBitmap(MemBitmap maskBmp)
{
//in this version
//please note that size of mask must be the same size of the dest buffer
_maskInnerBuffer = MemBitmap.GetBufferPtr(maskBmp);
}
public EnableOutputColorComponent EnableOutputColorComponent
{
get => _selectedDestMaskComponent;
set => _selectedDestMaskComponent = value;
}
public PixelBlenderColorComponent SelectedMaskComponent
{
get => _selectedMaskComponent;
set
{
_selectedMaskComponent = value;
switch (value)
{
default: throw new NotSupportedException();
case PixelBlenderColorComponent.A:
_mask_shift = CO.A_SHIFT;
break;
case PixelBlenderColorComponent.R:
_mask_shift = CO.R_SHIFT;
break;
case PixelBlenderColorComponent.G:
_mask_shift = CO.G_SHIFT;
break;
case PixelBlenderColorComponent.B:
_mask_shift = CO.B_SHIFT;
break;
}
}
}
/// <summary>
/// new color output after applying with mask
/// </summary>
/// <param name="srcColor"></param>
/// <param name="arrayOffset"></param>
/// <returns></returns>
Color NewColorFromMask(Color srcColor, int arrayOffset)
{
unsafe
{
int* ptr = (int*)_maskInnerBuffer.Ptr;
return srcColor.NewFromChangeCoverage((byte)((ptr[arrayOffset]) >> _mask_shift));
}
}
internal override void BlendPixel(int[] dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
fixed (int* head = &dstBuffer[arrayOffset])
{
BlendPixel32Internal(head, NewColorFromMask(srcColor, arrayOffset), _selectedDestMaskComponent);
}
}
}
internal override unsafe void BlendPixel32(int* dstPtr, Color srcColor)
{
BlendPixel32Internal(dstPtr, srcColor, _selectedDestMaskComponent);
}
internal override void BlendPixels(int[] dstBuffer,
int arrayElemOffset,
Color[] srcColors,
int srcColorOffset,
byte[] covers,
int coversIndex,
bool firstCoverForAll, int count)
{
if (firstCoverForAll)
{
int cover = covers[coversIndex];
if (cover == 255)
{
unsafe
{
fixed (int* head = &dstBuffer[arrayElemOffset])
{
int* header2 = head;
if (count % 2 != 0)
{
//odd
//
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
header2++;//move next
count--;
arrayElemOffset++;
}
//now count is even number
while (count > 0)
{
//now count is even number
//---------
//1
//BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
header2++;//move next
count--;
arrayElemOffset++;
//---------
//2
//BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
header2++;//move next
count--;
arrayElemOffset++;
}
}
}
}
else
{
unsafe
{
fixed (int* head = &dstBuffer[arrayElemOffset])
{
int* header2 = head;
if (count % 2 != 0)
{
//odd
//
//BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
arrayElemOffset++;
header2++;//move next
count--;
}
while (count > 0)
{
//Blend32PixelInternal(header2, sourceColors[sourceColorsOffset++].NewFromChangeCoverage(cover));
//1.
//BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
arrayElemOffset++;
header2++;//move next
count--;
//2.
//BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
arrayElemOffset++;
header2++;//move next
count--;
}
}
}
}
}
else
{
unsafe
{
fixed (int* dstHead = &dstBuffer[arrayElemOffset])
{
int* dstBufferPtr = dstHead;
do
{
//cover may diff in each loop
int cover = covers[coversIndex++];
if (cover == 255)
{
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset], arrayElemOffset));
}
else
{
BlendPixel(dstBuffer, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset].NewFromChangeCoverage(cover), arrayElemOffset));
}
arrayElemOffset++;
dstBufferPtr++;
++srcColorOffset;
}
while (--count != 0);
}
}
}
}
internal override void CopyPixel(int[] dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
fixed (int* ptr = &dstBuffer[arrayOffset])
{
BlendPixel32(ptr, NewColorFromMask(srcColor, arrayOffset));
}
}
}
internal override void CopyPixels(int[] dstBuffer, int arrayOffset, Color srcColor, int count)
{
unsafe
{
fixed (int* ptr_byte = &dstBuffer[arrayOffset])
{
//TODO: consider use memcpy() impl***
int* ptr = ptr_byte;
Color newColor = NewColorFromMask(srcColor, arrayOffset);
//---------
if ((count % 2) != 0)
{
BlendPixel32(ptr, newColor);
arrayOffset++;//move next
ptr++; //move next
count--;
}
while (count > 0)
{
//-----------
newColor = NewColorFromMask(srcColor, arrayOffset);
//1.
BlendPixel32(ptr, newColor);
arrayOffset++;//move next
ptr++; //move next
count--;
//-----------
//2
newColor = NewColorFromMask(srcColor, arrayOffset);
//1.
BlendPixel32(ptr, newColor);
arrayOffset++;//move next
ptr++; //move next
count--;
}
}
}
}
static unsafe void BlendPixel32Internal(int* dstPtr, Color srcColor, EnableOutputColorComponent enableCompo)
{
unchecked
{
if (srcColor.A == 255)
{
*dstPtr = srcColor.ToARGB(); //just copy
}
else
{
int dest = *dstPtr;
//separate each component
byte a = (byte)((dest >> CO.A_SHIFT) & 0xff);
byte r = (byte)((dest >> CO.R_SHIFT) & 0xff);
byte g = (byte)((dest >> CO.G_SHIFT) & 0xff);
byte b = (byte)((dest >> CO.B_SHIFT) & 0xff);
byte src_a = srcColor.A;
switch (enableCompo)
{
case EnableOutputColorComponent.EnableAll:
{
*dstPtr =
((byte)((src_a + a) - ((src_a * a + BASE_MASK) >> CO.BASE_SHIFT)) << CO.A_SHIFT) |
((byte)(((srcColor.R - r) * src_a + (r << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.R_SHIFT) |
((byte)(((srcColor.G - g) * src_a + (g << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.G_SHIFT) |
((byte)(((srcColor.B - b) * src_a + (b << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.B_SHIFT);
}
break;
case EnableOutputColorComponent.R:
{
*dstPtr =
((byte)((src_a + a) - ((src_a * a + BASE_MASK) >> CO.BASE_SHIFT)) << CO.A_SHIFT) |
((byte)(((srcColor.R - r) * src_a + (r << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.R_SHIFT) |
(g << CO.G_SHIFT) |
(b << CO.B_SHIFT);
}
break;
case EnableOutputColorComponent.G:
{
*dstPtr =
((byte)((src_a + a) - ((src_a * a + BASE_MASK) >> CO.BASE_SHIFT)) << CO.A_SHIFT) |
(r << CO.R_SHIFT) |
((byte)(((srcColor.G - g) * src_a + (g << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.G_SHIFT) |
(b << CO.B_SHIFT);
}
break;
case EnableOutputColorComponent.B:
{
*dstPtr =
((byte)((src_a + a) - ((src_a * a + BASE_MASK) >> CO.BASE_SHIFT)) << CO.A_SHIFT) |
(r << CO.R_SHIFT) |
(g << CO.G_SHIFT) |
((byte)(((srcColor.B - b) * src_a + (b << CO.BASE_SHIFT)) >> CO.BASE_SHIFT) << CO.B_SHIFT);
}
break;
}
}
}
}
internal override void BlendPixels(TempMemPtr dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
int* dst = (int*)dstBuffer.Ptr;
int* head = &dst[arrayOffset];
{
BlendPixel32Internal(head, NewColorFromMask(srcColor, arrayOffset), _selectedDestMaskComponent);
}
}
}
internal override void BlendPixels(TempMemPtr dst, int arrayElemOffset, Color[] srcColors,
int srcColorOffset, byte[] covers, int coversIndex, bool firstCoverForAll, int count)
{
if (firstCoverForAll)
{
int cover = covers[coversIndex];
if (cover == 255)
{
unsafe
{
int* dstBuffer = (int*)dst.Ptr;
int* head = &dstBuffer[arrayElemOffset];
{
int* header2 = head;
if (count % 2 != 0)
{
//odd
//
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
header2++;//move next
count--;
arrayElemOffset++;
}
//now count is even number
while (count > 0)
{
//now count is even number
//---------
//1
//BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
header2++;//move next
count--;
arrayElemOffset++;
//---------
//2
//BlendPixel32Internal(header2, srcColors[srcColorOffset++]);
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
header2++;//move next
count--;
arrayElemOffset++;
}
}
}
}
else
{
unsafe
{
int* dstBuffer = (int*)dst.Ptr;
int* head = &dstBuffer[arrayElemOffset];
{
int* header2 = head;
if (count % 2 != 0)
{
//odd
//
//BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
arrayElemOffset++;
header2++;//move next
count--;
}
while (count > 0)
{
//Blend32PixelInternal(header2, sourceColors[sourceColorsOffset++].NewFromChangeCoverage(cover));
//1.
//BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
arrayElemOffset++;
header2++;//move next
count--;
//2.
//BlendPixel32Internal(header2, srcColors[srcColorOffset++], cover);
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset++], arrayElemOffset));
arrayElemOffset++;
header2++;//move next
count--;
}
}
}
}
}
else
{
unsafe
{
int* dstBuffer = (int*)dst.Ptr;
int* dstHead = &dstBuffer[arrayElemOffset];
{
int* dstBufferPtr = dstHead;
do
{
//cover may diff in each loop
int cover = covers[coversIndex++];
if (cover == 255)
{
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset], arrayElemOffset));
}
else
{
BlendPixels(dst, arrayElemOffset, NewColorFromMask(srcColors[srcColorOffset].NewFromChangeCoverage(cover), arrayElemOffset));
}
arrayElemOffset++;
dstBufferPtr++;
++srcColorOffset;
}
while (--count != 0);
}
}
}
}
internal override void CopyPixels(TempMemPtr dst, int arrayOffset, Color srcColor, int count)
{
unsafe
{
int* dstBuffer = (int*)dst.Ptr;
int* ptr_byte = &dstBuffer[arrayOffset];
{
//TODO: consider use memcpy() impl***
int* ptr = ptr_byte;
Color newColor = NewColorFromMask(srcColor, arrayOffset);
//---------
if ((count % 2) != 0)
{
BlendPixel32(ptr, newColor);
arrayOffset++;//move next
ptr++; //move next
count--;
}
while (count > 0)
{
//-----------
newColor = NewColorFromMask(srcColor, arrayOffset);
//1.
BlendPixel32(ptr, newColor);
arrayOffset++;//move next
ptr++; //move next
count--;
//-----------
//2
newColor = NewColorFromMask(srcColor, arrayOffset);
//1.
BlendPixel32(ptr, newColor);
arrayOffset++;//move next
ptr++; //move next
count--;
}
}
}
}
internal override void CopyPixel(TempMemPtr dstBuffer, int arrayOffset, Color srcColor)
{
unsafe
{
int* dst = (int*)dstBuffer.Ptr;
int* ptr = &dst[arrayOffset];
{
BlendPixel32(ptr, NewColorFromMask(srcColor, arrayOffset));
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Threading;
using Rdr.Common;
using RdrLib;
using RdrLib.Model;
namespace Rdr.Gui
{
public class MainWindowViewModel : BindableBase
{
private DelegateCommandAsync? _refreshAllCommand = null;
public DelegateCommandAsync RefreshAllCommand
{
get
{
if (_refreshAllCommand is null)
{
_refreshAllCommand = new DelegateCommandAsync(RefreshAllAsync, CanExecuteAsync);
}
return _refreshAllCommand;
}
}
private DelegateCommandAsync<Feed>? _refreshCommand = null;
public DelegateCommandAsync<Feed> RefreshCommand
{
get
{
if (_refreshCommand is null)
{
_refreshCommand = new DelegateCommandAsync<Feed>(RefreshAsync, CanExecuteAsync);
}
return _refreshCommand;
}
}
private DelegateCommand<Feed>? _goToFeedCommand = null;
public DelegateCommand<Feed> GoToFeedCommand
{
get
{
if (_goToFeedCommand is null)
{
_goToFeedCommand = new DelegateCommand<Feed>(GoToFeed, (_) => true);
}
return _goToFeedCommand;
}
}
private DelegateCommand<Item>? _goToItemCommand = null;
public DelegateCommand<Item> GoToItemCommand
{
get
{
if (_goToItemCommand is null)
{
_goToItemCommand = new DelegateCommand<Item>(GoToItem, (_) => true);
}
return _goToItemCommand;
}
}
private DelegateCommand? _markAllAsReadCommand = null;
public DelegateCommand MarkAllAsReadCommand
{
get
{
if (_markAllAsReadCommand is null)
{
_markAllAsReadCommand = new DelegateCommand(MarkAllAsRead, (_) => true);
}
return _markAllAsReadCommand;
}
}
private DelegateCommand? _openFeedsFileCommand = null;
public DelegateCommand OpenFeedsFileCommand
{
get
{
if (_openFeedsFileCommand is null)
{
_openFeedsFileCommand = new DelegateCommand(OpenFeedsFile, (_) => true);
}
return _openFeedsFileCommand;
}
}
private DelegateCommandAsync? _reloadCommand = null;
public DelegateCommandAsync ReloadCommand
{
get
{
if (_reloadCommand is null)
{
_reloadCommand = new DelegateCommandAsync(ReloadAsync, CanExecuteAsync);
}
return _reloadCommand;
}
}
public DelegateCommandAsync<Enclosure> DownloadEnclosureCommand
=> new DelegateCommandAsync<Enclosure>(DownloadEnclosureAsync, CanExecuteAsync);
private bool CanExecuteAsync(object _) => !Activity;
private readonly DispatcherTimer refreshTimer = new DispatcherTimer(DispatcherPriority.ApplicationIdle)
{
Interval = TimeSpan.FromMinutes(10d)
};
private readonly string feedsFilePath = string.Empty;
private readonly RdrService service = new RdrService();
private Feed? selectedFeed = null;
public IReadOnlyCollection<Feed> Feeds => service.Feeds;
private readonly ObservableCollection<Item> _items = new ObservableCollection<Item>();
public IReadOnlyCollection<Item> Items => _items;
public bool IsRefreshTimerRunning => refreshTimer.IsEnabled;
private bool _activity = false;
public bool Activity
{
get => _activity;
set
{
SetProperty(ref _activity, value, nameof(Activity));
RaiseCanExecuteChangedOnAsyncCommands();
}
}
private int activeDownloads = 0;
public bool HasActiveDownload => activeDownloads > 0;
private void RaiseCanExecuteChangedOnAsyncCommands()
{
RefreshAllCommand.RaiseCanExecuteChanged();
RefreshCommand.RaiseCanExecuteChanged();
ReloadCommand.RaiseCanExecuteChanged();
}
public MainWindowViewModel(string feedsFilePath)
{
this.feedsFilePath = feedsFilePath;
refreshTimer.Tick += RefreshTimer_Tick;
}
public void StartTimer()
{
if (!refreshTimer.IsEnabled)
{
refreshTimer.Start();
}
}
public void StopTimer()
{
if (refreshTimer.IsEnabled)
{
refreshTimer.Stop();
}
}
private void RefreshTimer_Tick(object? sender, EventArgs e)
{
RefreshAllCommand.Execute(null);
}
public async Task RefreshAllAsync()
{
Activity = true;
await service.UpdateAllAsync();
if (selectedFeed is null)
{
MoveUnreadItems(false);
}
else
{
MoveItems(selectedFeed);
}
Activity = false;
}
public async Task RefreshAsync(Feed feed)
{
Activity = true;
await service.UpdateAsync(feed);
if (selectedFeed == feed)
{
MoveItems(feed);
}
Activity = false;
}
public async Task RefreshAsync(IEnumerable<Feed> feeds)
{
Activity = true;
await service.UpdateAsync(feeds);
if (selectedFeed is null)
{
MoveUnreadItems(false);
}
else
{
MoveItems(selectedFeed);
}
Activity = false;
}
private void GoToFeed(Feed feed)
{
if (feed.Link is Uri uri)
{
if (!SystemLaunch.Uri(uri))
{
LogStatic.Message($"feed link launch failed ({feed.Name})");
}
}
else
{
LogStatic.Message($"feed link was null ({feed.Name})");
}
}
private void GoToItem(Item item)
{
if (item.Link is Uri uri)
{
if (SystemLaunch.Uri(uri))
{
service.MarkAsRead(item);
// we only want to remove the item if we are looking at unread items and _items contains it
if ((selectedFeed is null) && (_items.Contains(item)))
{
_items.Remove(item);
}
}
else
{
LogStatic.Message($"item link launch failed ({item.Name})");
}
}
else
{
LogStatic.Message($"item link was null ({item.Name})");
}
}
private void MarkAllAsRead()
{
service.MarkAllAsRead();
if (selectedFeed is null)
{
_items.Clear();
}
}
public void OpenFeedsFile()
{
if (!SystemLaunch.Path(feedsFilePath))
{
LogStatic.Message($"feeds file path does not exist ({feedsFilePath}), or process launch failed");
}
}
public async Task ReloadAsync()
{
string[] lines = await ReadLinesAsync(feedsFilePath, "#");
IReadOnlyCollection<Feed> feeds = CreateFeeds(lines);
if (feeds.Count == 0)
{
service.Clear();
_items.Clear();
return;
}
// something service.Feeds has that our loaded feeds doesn't
var toRemove = service.Feeds.Where(f => !feeds.Contains(f)).ToList();
service.Remove(toRemove);
List<Feed> toRefresh = new List<Feed>();
foreach (Feed feed in feeds)
{
if (service.Add(feed))
{
toRefresh.Add(feed);
}
}
await RefreshAsync(toRefresh);
}
private static async Task<string[]> ReadLinesAsync(string path, string commentChar)
{
try
{
return await FileSystem.LoadLinesFromFileAsync(path, commentChar).ConfigureAwait(false);
}
catch (FileNotFoundException)
{
await LogStatic.MessageAsync($"file not found: {path}").ConfigureAwait(false);
return Array.Empty<string>();
}
}
private static IReadOnlyCollection<Feed> CreateFeeds(string[] lines)
{
List<Feed> feeds = new List<Feed>();
foreach (string line in lines)
{
if (Uri.TryCreate(line, UriKind.Absolute, out Uri? uri))
{
Feed feed = new Feed(uri);
feeds.Add(feed);
}
}
return feeds.AsReadOnly();
}
public async Task DownloadEnclosureAsync(Enclosure enclosure)
{
string profileFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string filename = enclosure.Link.Segments.Last();
string path = Path.Combine(profileFolder, "share", filename);
var progress = new Progress<FileProgress>(e =>
{
if (e.ContentLength.HasValue)
{
enclosure.Message = e.GetPercentFormatted(CultureInfo.CurrentCulture) ?? "error!";
}
else
{
enclosure.Message = $"{e.TotalBytesWritten} bytes written";
}
});
enclosure.IsDownloading = true;
activeDownloads++;
FileResponse response = await service.DownloadEnclosureAsync(enclosure, path, progress);
enclosure.IsDownloading = false;
activeDownloads--;
enclosure.Message = (response.Reason == Reason.Success) ? "Download" : response.Reason.ToString();
}
public void SetSelectedFeed(Feed? feed)
{
if (feed is null)
{
selectedFeed = null;
MoveUnreadItems(true);
}
else
{
selectedFeed = feed;
MoveItems(selectedFeed.Items, clearFirst: true);
}
}
public void SeeAll()
{
_items.Clear();
var allItems = from feed in Feeds
from item in feed.Items
orderby item.Published descending
select item;
MoveItems(allItems, clearFirst: true);
}
private void MoveUnreadItems(bool clearFirst)
{
var unreadItems = from f in Feeds
from i in f.Items
where i.Unread
select i;
MoveItems(unreadItems, clearFirst);
}
private void MoveItems(Feed feed) => MoveItems(feed.Items, clearFirst: false);
private void MoveItems(IEnumerable<Item> items, bool clearFirst)
{
if (clearFirst)
{
_items.Clear();
}
foreach (Item item in items)
{
if (!_items.Contains(item))
{
_items.Add(item);
}
}
}
}
}
| |
// 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.
// ----------------------------------------------------------------------------------
// Interop library code
//
// Type marshalling helpers used by MCG
//
// NOTE:
// These source code are being published to InternalAPIs and consumed by RH builds
// Use PublishInteropAPI.bat to keep the InternalAPI copies in sync
// ----------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading;
using System.Text;
using System.Runtime;
using System.Diagnostics.Contracts;
using Internal.NativeFormat;
using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices
{
internal static class McgTypeHelpers
{
static readonly Type[] s_wellKnownTypes = new Type[]
{
typeof(Boolean),
typeof(Char),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(String),
typeof(Object),
typeof(Guid)
};
static readonly string[] s_wellKnownTypeNames = new string[]
{
"Boolean",
"Char16",
"UInt8",
"Int16",
"UInt16",
"Int32",
"UInt32",
"Int64",
"UInt64",
"Single",
"Double",
"String",
"Object",
"Guid"
};
private const string PseudonymPrefix = "System.Runtime.InteropServices.RuntimePseudonyms.";
#if ENABLE_WINRT
/// <summary>
/// A 'fake' System.Type instance for native WinMD types (metadata types) that are not needed in
/// managed code, which means it is:
/// 1. Imported in MCG, but reduced away by reducer
/// 2. Not imported by MCG at all
/// In either case, it is possible that it is needed only in native code, and native code can return
/// a IXamlType instance to C# xaml compiler generated code that attempts to call get_UnderlyingType
/// which tries to convert a TypeName to System.Type and then stick it into a cache. In order to make
/// such scenario work, we need to create a fake System.Type instance that is unique to the name
/// and is roundtrippable.
/// As long as it is only used in the cache scenarios in xaml compiler generated code, we should be
/// fine. Any other attempt to use such types will surely result an exception
/// NOTE: in order to avoid returning fake types for random non-existent metadata types, we look
/// in McgAdditionalClassData (which encodes all interesting class data) before we create such fake
/// types
/// </summary>
class McgFakeMetadataType
#if RHTESTCL
: Type
#else
: Internal.Reflection.Extensibility.ExtensibleType
#endif
{
/// <summary>
/// Full type name of the WinMD type
/// </summary>
string _fullTypeName;
public McgFakeMetadataType(string fullTypeName, TypeKind typeKind)
#if RHTESTCL
: base(default(RuntimeTypeHandle))
#else
: base()
#endif
{
_fullTypeName = fullTypeName;
TypeKind = typeKind;
}
public TypeKind TypeKind { get; private set; }
#if RHTESTCL
public string FullName { get { return _fullTypeName; } }
#else
public override String AssemblyQualifiedName { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override Type DeclaringType { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override String FullName { get { return _fullTypeName; } }
public override int GenericParameterPosition { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override Type[] GenericTypeArguments { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override bool IsConstructedGenericType { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override bool IsGenericParameter { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override String Name { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override String Namespace { get { throw new System.Reflection.MissingMetadataException(_fullTypeName); } }
public override int GetArrayRank() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type GetElementType() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type GetGenericTypeDefinition() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type MakeArrayType() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type MakeArrayType(int rank) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type MakeByRefType() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type MakeGenericType(params Type[] typeArguments) { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override Type MakePointerType() { throw new System.Reflection.MissingMetadataException(_fullTypeName); }
public override String ToString()
{
return "Type: " + _fullTypeName;
}
public override bool Equals(Object o)
{
if (o == null)
return false;
//
// We guarantee uniqueness in Mcg marshalling code
//
if (o == this)
return true;
return false;
}
public override int GetHashCode()
{
return _fullTypeName.GetHashCode();
}
#endif //RHTESTCL
}
internal unsafe static void TypeToTypeName(
Type type,
out HSTRING nativeTypeName,
out int nativeTypeKind)
{
if (type == null)
{
nativeTypeName.handle = default(IntPtr);
nativeTypeKind = (int)TypeKind.Custom;
}
else
{
McgFakeMetadataType fakeType = type as McgFakeMetadataType;
if (fakeType != null)
{
//
// Handle round tripping fake types
// See McgFakeMetadataType for details
//
nativeTypeKind = (int)fakeType.TypeKind;
nativeTypeName = McgMarshal.StringToHString(fakeType.FullName);
}
else
{
string typeName;
TypeKind typeKind;
TypeToTypeName(type.TypeHandle, out typeName, out typeKind);
nativeTypeName = McgMarshal.StringToHString(typeName);
nativeTypeKind = (int)typeKind;
}
}
}
#endif //!CORECLR
private unsafe static void TypeToTypeName(
RuntimeTypeHandle typeHandle,
out string typeName,
out TypeKind typeKind)
{
//
// Primitive types
//
for (int i = 0; i < s_wellKnownTypes.Length; i++)
{
if (s_wellKnownTypes[i].TypeHandle.Equals(typeHandle))
{
typeName = s_wellKnownTypeNames[i];
typeKind = TypeKind.Primitive;
return;
}
}
//
// User-imported types
//
bool isWinRT;
string name = McgModuleManager.GetTypeName(typeHandle, out isWinRT);
if (name != null)
{
typeName = name;
typeKind =
(isWinRT ?
TypeKind.Metadata :
TypeKind.Custom);
return;
}
//
// Handle managed types
//
typeName = GetCustomTypeName(typeHandle);
typeKind = TypeKind.Custom;
}
static System.Collections.Generic.Internal.Dictionary<string, Type> s_fakeTypeMap
= new Collections.Generic.Internal.Dictionary<string, Type>();
static Lock s_fakeTypeMapLock = new Lock();
static System.Collections.Generic.Internal.Dictionary<RuntimeTypeHandle, Type> s_realToFakeTypeMap
= new System.Collections.Generic.Internal.Dictionary<RuntimeTypeHandle, Type>();
#if ENABLE_WINRT
/// <summary>
/// Returns a type usable in XAML roundtripping whether it's reflectable or not
/// </summary>
/// <param name="realType">Type for the real object</param>
/// <returns>realType if realType is reflectable, otherwise a fake type that can be roundtripped
/// and won't throw for XAML usage.</returns>
internal static Type GetReflectableOrFakeType(Type realType)
{
#if !RHTESTCL
if(realType.SupportsReflection())
{
return realType;
}
#endif
s_fakeTypeMapLock.Acquire();
try
{
Type fakeType;
RuntimeTypeHandle realTypeHandle = realType.TypeHandle;
if (s_realToFakeTypeMap.TryGetValue(realTypeHandle, out fakeType))
{
return fakeType;
}
string pseudonym = GetPseudonymForType(realTypeHandle, /* useFake: */ true);
fakeType = new McgFakeMetadataType(pseudonym, TypeKind.Custom);
s_realToFakeTypeMap.Add(realTypeHandle, fakeType);
s_fakeTypeMap.Add(pseudonym, fakeType);
return fakeType;
}
finally
{
s_fakeTypeMapLock.Release();
}
}
internal static unsafe Type TypeNameToType(HSTRING nativeTypeName, int nativeTypeKind)
{
string name = McgMarshal.HStringToString(nativeTypeName);
if (!string.IsNullOrEmpty(name))
{
//
// Well-known types
//
for (int i = 0; i < s_wellKnownTypeNames.Length; i++)
{
if (s_wellKnownTypeNames[i] == name)
{
if (nativeTypeKind != (int)TypeKind.Primitive)
throw new ArgumentException(SR.Arg_UnexpectedTypeKind);
return s_wellKnownTypes[i];
}
}
if (nativeTypeKind == (int)TypeKind.Primitive)
{
//
// We've scanned all primitive types that we know of and came back nothing
//
throw new ArgumentException("Unrecognized primitive type name");
}
//
// User-imported types
// Try to get a type if MCG knows what this is
// If the returned type does not have metadata, the type is no good as Jupiter needs to pass
// it to XAML type provider code which needs to call FullName on it
//
bool isWinRT;
Type type = McgModuleManager.GetTypeFromName(name, out isWinRT);
#if !RHTESTCL
if (type != null && !type.SupportsReflection())
type = null;
#endif
//
// If we got back a type that is valid (not reduced)
//
if (type != null && !type.TypeHandle.Equals(McgModule.s_DependencyReductionTypeRemovedTypeHandle))
{
if (nativeTypeKind !=
(int)
(isWinRT ? TypeKind.Metadata : TypeKind.Custom))
throw new ArgumentException(SR.Arg_UnexpectedTypeKind);
return type;
}
if (nativeTypeKind == (int)TypeKind.Metadata)
{
//
// Handle converting native WinMD type names to fake McgFakeMetadataType to make C# xaml
// compiler happy
// See McgFakeMetadataType for more details
//
s_fakeTypeMapLock.Acquire();
try
{
if (s_fakeTypeMap.TryGetValue(name, out type))
{
return type;
}
else
{
type = new McgFakeMetadataType(name, TypeKind.Metadata);
s_fakeTypeMap.Add(name, type);
return type;
}
}
finally
{
s_fakeTypeMapLock.Release();
}
}
if (nativeTypeKind != (int)TypeKind.Custom)
throw new ArgumentException(SR.Arg_UnrecognizedTypeName);
//
// Arbitrary managed types. See comment in TypeToTypeName.
//
return StringToCustomType(name);
}
return null;
}
#endif
private static string GetCustomTypeName(RuntimeTypeHandle type)
{
//
// For types loaded by the runtime, we may not have metadata from which to get the name.
// So we use the RuntimeTypeHandle instead. For types loaded via reflection, we may not
// have a RuntimeTypeHandle, in which case we will try to use the name.
//
#if !RHTESTCL
Type realType = InteropExtensions.GetTypeFromHandle(type);
if (realType.SupportsReflection())
{
//
// Managed types that has reflection metadata
//
// Use the fully assembly qualified name to make Jupiter happy as Jupiter might parse the
// name (!!) to extract the assembly name to look up files from directory with the same
// name. A bug has filed to them to fix this for the next release, because the format
// of Custom TypeKind is up to the interpretation of the projection layer and is supposed
// to be an implementation detail
// NOTE: The try/catch is added as a fail-safe
//
try
{
return realType.AssemblyQualifiedName;
}
catch (MissingMetadataException ex)
{
ExternalInterop.OutputDebugString(
SR.Format(SR.TypeNameMarshalling_MissingMetadata, ex.Message)
);
}
}
#endif
return GetPseudonymForType(type, /* useFake: */ false);
}
private static string GetPseudonymForType(RuntimeTypeHandle type, bool useFake)
{
// I'd really like to use the standard .net string formatting stuff here,
// but not enough of it is supported by rhtestcl.
ulong value = (ulong)type.GetRawValue();
StringBuilder sb = new StringBuilder(PseudonymPrefix, PseudonymPrefix.Length + 17);
if(useFake)
{
sb.Append('f');
}
else
{
sb.Append('r');
}
// append 64 bits, high to low, one nibble at a time
for (int shift = 60; shift >= 0; shift -= 4)
{
ulong nibble = (value >> shift) & 0xf;
if (nibble < 10)
sb.Append((char)(nibble + '0'));
else
sb.Append((char)((nibble - 10) + 'A'));
}
string result = sb.ToString();
return result;
}
private static Type StringToCustomType(string s)
{
ulong value = 0;
if (s.StartsWith(PseudonymPrefix))
{
//
// This is a name created from a RuntimeTypeHandle that does not have reflection metadata
//
if (s.Length != PseudonymPrefix.Length + 17)
throw new ArgumentException(SR.Arg_InvalidCustomTypeNameValue);
bool useFake = s[PseudonymPrefix.Length] == 'f';
if (useFake)
{
s_fakeTypeMapLock.Acquire();
try
{
return s_fakeTypeMap[s];
}
finally
{
s_fakeTypeMapLock.Release();
}
}
for (int i = PseudonymPrefix.Length + 1; i < s.Length; i++)
{
char c = s[i];
ulong nibble;
if (c >= '0' && c <= '9')
nibble = (ulong)(c - '0');
else if (c >= 'A' && c <= 'F')
nibble = (ulong)(c - 'A') + 10;
else
throw new ArgumentException(SR.Arg_InvalidCustomTypeNameValue);
value = (value << 4) | nibble;
}
return InteropExtensions.GetTypeFromHandle((IntPtr)value);
}
#if !RHTESTCL
else
{
//
// Try reflection
// If reflection failed, this is a type name that we don't know about
// In theory we could support round tripping of such types.
//
Type reflectType = Type.GetType(s);
if (reflectType == null)
throw new ArgumentException("Unrecognized custom TypeName");
return reflectType;
}
#else
else
{
return null;
}
#endif
}
/// <summary>
/// Try to get Diagnostic String for given RuntimeTypeHandle
/// Diagnostic usually means MissingMetadata Message
/// </summary>
/// <param name="interfaceType"></param>
/// <returns></returns>
public static string GetDiagnosticMessageForMissingType(RuntimeTypeHandle interfaceType)
{
#if ENABLE_WINRT
string msg = string.Empty;
try
{
// case 1: missing reflection metadata for interfaceType
// if this throws, we just return MissMetadataException Message
string typeName = interfaceType.GetDisplayName();
// case 2: if intefaceType is ICollection<T>/IReadOnlyCollection<T>,
// we need to find out its corresponding WinRT Interface and ask users to root them.
// Current there is an issue for projected type in rd.xml file--if user specify IList<T> in rd.xml,
// DR will only root IList<T> instead of both IList<T> and IVector<T>
Type type = interfaceType.GetType();
if (InteropExtensions.IsGenericType(interfaceType)
&& type.GenericTypeArguments != null
&& type.GenericTypeArguments.Length == 1)
{
List<string> missTypeNames = new List<string>();
Type genericType = type.GetGenericTypeDefinition();
bool isICollectOfT = false;
bool isIReadOnlyCollectOfT = false;
if (genericType.TypeHandle.Equals(typeof(ICollection<>).TypeHandle))
{
isICollectOfT = true;
Type argType = type.GenericTypeArguments[0];
if (argType.IsConstructedGenericType && argType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
// the missing type could be either IMap<K,V> or IVector<IKeyValuePair<K,v>>
missTypeNames.Add(
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IMap",
new string[]
{
argType.GenericTypeArguments[0].ToString(),
argType.GenericTypeArguments[1].ToString()
}
)
);
missTypeNames.Add(
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IVector",
new String[]
{
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IKeyValuePair",
new string[]
{
argType.GenericTypeArguments[0].ToString(),
argType.GenericTypeArguments[1].ToString()
}
)
}
)
);
}
else
{
// the missing type is IVector<T>
missTypeNames.Add(
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IVector",
new string[]
{
argType.ToString()
}
)
);
}
} // genericType == typeof(ICollection<>)
else if (genericType == typeof(IReadOnlyCollection<>))
{
isIReadOnlyCollectOfT = true;
Type argType = type.GenericTypeArguments[0];
if (argType.IsConstructedGenericType && argType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
// the missing type could be either IVectorView<IKeyValuePair<K,v>> or IMapView<K,V>
missTypeNames.Add(
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IVectorView",
new String[]
{
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IKeyValuePair",
new string[]
{
argType.GenericTypeArguments[0].ToString(),
argType.GenericTypeArguments[1].ToString()
}
)
}
)
);
missTypeNames.Add(
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IMapView",
new string[]
{
argType.GenericTypeArguments[0].ToString(),
argType.GenericTypeArguments[1].ToString()
}
)
);
}
else
{
//the missing type is IVectorView<T>
missTypeNames.Add(
McgTypeHelpers.ConstructGenericTypeFullName(
"Windows.Foundation.Collections.IVectorView",
new string[]
{
argType.ToString()
}
)
);
}
}
if (isICollectOfT || isIReadOnlyCollectOfT)
{
// Concat all missing Type Names into one message
for (int i = 0; i < missTypeNames.Count; i++)
{
msg += String.Format(SR.ComTypeMarshalling_MissingInteropData, missTypeNames[i]);
if (i != missTypeNames.Count - 1)
msg += Environment.NewLine;
}
return msg;
}
}
// case 3: We can get type name but not McgTypeInfo, maybe another case similar to case 2
// definitely is a bug.
msg = String.Format(SR.ComTypeMarshalling_MissingInteropData, Type.GetTypeFromHandle(interfaceType));
}
catch (MissingMetadataException ex)
{
msg = ex.Message;
}
return msg;
#else
return interfaceType.ToString();
#endif //ENABLE_WINRT
}
// Construct Generic Type Full Name
private static string ConstructGenericTypeFullName(string genericTypeDefinitionFullName, string[] genericTypeArguments)
{
string fullName = genericTypeDefinitionFullName;
fullName += "<";
for (int i = 0; i < genericTypeArguments.Length; i++)
{
if (i != 0)
fullName += ",";
fullName += genericTypeArguments[i];
}
fullName += ">";
return fullName;
}
}
internal static class TypeHandleExtensions
{
internal static string GetDisplayName(this RuntimeTypeHandle handle)
{
#if ENABLE_WINRT
return Internal.Reflection.Execution.PayForPlayExperience.MissingMetadataExceptionCreator.ComputeUsefulPertainantIfPossible(Type.GetTypeFromHandle(handle));
#else
return handle.ToString();
#endif
}
internal static bool IsClass(this RuntimeTypeHandle handle)
{
#if ENABLE_WINRT
return !InteropExtensions.IsInterface(handle) &&
!handle.IsValueType() &&
!InteropExtensions.AreTypesAssignable(handle, typeof(Delegate).TypeHandle);
#else
return false;
#endif
}
internal static bool IsIJupiterObject(this RuntimeTypeHandle interfaceType)
{
#if ENABLE_WINRT
return interfaceType.Equals(InternalTypes.IJupiterObject);
#else
return false;
#endif
}
internal static bool IsIInspectable(this RuntimeTypeHandle interfaceType)
{
#if ENABLE_WINRT
return interfaceType.Equals(InternalTypes.IInspectable);
#else
return false;
#endif
}
#region "Interface Data"
internal static bool HasInterfaceData(this RuntimeTypeHandle interfaceType)
{
McgInterfaceInfo interfaceInfo = McgModuleManager.GetInterfaceInfoByHandle(interfaceType);
if (interfaceInfo != null)
return true;
return false;
}
internal static bool IsWinRTInterface(this RuntimeTypeHandle interfaceType)
{
McgInterfaceInfo interfaceInfo = McgModuleManager.GetInterfaceInfoByHandle(interfaceType);
if (interfaceInfo != null)
return interfaceInfo.InterfaceData.IsIInspectable;
#if ENABLE_WINRT
throw new MissingInteropDataException(SR.DelegateMarshalling_MissingInteropData, Type.GetTypeFromHandle(interfaceType));
#else
return false;
#endif
}
internal static bool HasDynamicAdapterClass(this RuntimeTypeHandle interfaceType)
{
McgInterfaceInfo interfaceInfo = McgModuleManager.GetInterfaceInfoByHandle(interfaceType);
if (interfaceInfo != null)
{
return interfaceInfo.HasDynamicAdapterClass;
}
#if ENABLE_WINRT
throw new MissingInteropDataException(SR.DelegateMarshalling_MissingInteropData, Type.GetTypeFromHandle(interfaceType));
#else
Environment.FailFast("HasDynamicAdapterClass.");
return false;
#endif
}
internal static RuntimeTypeHandle GetDynamicAdapterClassType(this RuntimeTypeHandle interfaceType)
{
McgInterfaceInfo interfaceInfo = McgModuleManager.GetInterfaceInfoByHandle(interfaceType);
if(interfaceInfo != null)
{
return interfaceInfo.DynamicAdapterClassType;
}
return default(RuntimeTypeHandle);
}
internal static Guid GetInterfaceGuid(this RuntimeTypeHandle interfaceType)
{
McgInterfaceInfo interfaceInfo = McgModuleManager.GetInterfaceInfoByHandle(interfaceType);
if(interfaceInfo != null)
{
return interfaceInfo.ItfGuid;
}
return default(Guid);
}
internal static IntPtr GetCcwVtableThunk(this RuntimeTypeHandle interfaceType)
{
McgInterfaceInfo interfaceInfo = McgModuleManager.GetInterfaceInfoByHandle(interfaceType);
if (interfaceInfo != null)
{
return interfaceInfo.InterfaceData.CcwVtable;
}
return default(IntPtr);
}
internal static IntPtr GetCcwVtable(this RuntimeTypeHandle interfaceType)
{
McgInterfaceInfo interfaceInfo = McgModuleManager.GetInterfaceInfoByHandle(interfaceType);
if (interfaceInfo != null)
{
return interfaceInfo.CcwVtable;
}
return default(IntPtr);
}
internal static int GetMarshalIndex(this RuntimeTypeHandle interfaceType)
{
McgInterfaceInfo interfaceInfo = McgModuleManager.GetInterfaceInfoByHandle(interfaceType);
if (interfaceInfo != null)
return interfaceInfo.MarshalIndex;
return -1;
}
internal static McgInterfaceFlags GetInterfaceFlags(this RuntimeTypeHandle interfaceType)
{
McgInterfaceInfo interfaceInfo = McgModuleManager.GetInterfaceInfoByHandle(interfaceType);
if(interfaceInfo != null)
return interfaceInfo.Flags;
return default(McgInterfaceFlags);
}
internal static RuntimeTypeHandle GetDispatchClassType(this RuntimeTypeHandle interfaceType)
{
McgInterfaceInfo interfaceInfo = McgModuleManager.GetInterfaceInfoByHandle(interfaceType);
if (interfaceInfo != null)
return interfaceInfo.DispatchClassType;
return default(RuntimeTypeHandle);
}
#endregion
#region "Class Data"
internal static GCPressureRange GetGCPressureRange(this RuntimeTypeHandle classType)
{
McgClassInfo classInfo = McgModuleManager.GetClassInfoFromTypeHandle(classType);
if (classInfo != null)
return classInfo.GCPressureRange;
return GCPressureRange.None;
}
internal static bool IsSealed(this RuntimeTypeHandle classType)
{
McgClassInfo classInfo = McgModuleManager.GetClassInfoFromTypeHandle(classType);
if (classInfo != null)
return classInfo.IsSealed;
#if ENABLE_WINRT
throw new MissingInteropDataException(SR.DelegateMarshalling_MissingInteropData, Type.GetTypeFromHandle(classType));
#else
Environment.FailFast("IsSealed");
return false;
#endif
}
internal static ComMarshalingType GetMarshalingType(this RuntimeTypeHandle classType)
{
McgClassInfo classInfo = McgModuleManager.GetClassInfoFromTypeHandle(classType);
if (classInfo != null)
return classInfo.MarshalingType;
return ComMarshalingType.Unknown;
}
internal static RuntimeTypeHandle GetDefaultInterface(this RuntimeTypeHandle classType)
{
McgClassInfo classInfo = McgModuleManager.GetClassInfoFromTypeHandle(classType);
if (classInfo != null)
return classInfo.DefaultInterface;
return default(RuntimeTypeHandle);
}
#endregion
#region "Generic Argument Data"
internal static RuntimeTypeHandle GetIteratorType(this RuntimeTypeHandle interfaceType)
{
McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo;
if (McgModuleManager.TryGetGenericArgumentMarshalInfo(interfaceType, out mcgGenericArgumentMarshalInfo))
{
return mcgGenericArgumentMarshalInfo.IteratorType;
}
return default(RuntimeTypeHandle);
}
internal static RuntimeTypeHandle GetElementClassType(this RuntimeTypeHandle interfaceType)
{
McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo;
if (McgModuleManager.TryGetGenericArgumentMarshalInfo(interfaceType, out mcgGenericArgumentMarshalInfo))
{
return mcgGenericArgumentMarshalInfo.ElementClassType;
}
return default(RuntimeTypeHandle);
}
internal static RuntimeTypeHandle GetElementInterfaceType(this RuntimeTypeHandle interfaceType)
{
McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo;
if (McgModuleManager.TryGetGenericArgumentMarshalInfo(interfaceType, out mcgGenericArgumentMarshalInfo))
{
return mcgGenericArgumentMarshalInfo.ElementInterfaceType;
}
return default(RuntimeTypeHandle);
}
internal static RuntimeTypeHandle GetVectorViewType(this RuntimeTypeHandle interfaceType)
{
McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo;
if (McgModuleManager.TryGetGenericArgumentMarshalInfo(interfaceType, out mcgGenericArgumentMarshalInfo))
{
return mcgGenericArgumentMarshalInfo.VectorViewType;
}
return default(RuntimeTypeHandle);
}
internal static RuntimeTypeHandle GetAsyncOperationType(this RuntimeTypeHandle interfaceType)
{
McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo;
if (McgModuleManager.TryGetGenericArgumentMarshalInfo(interfaceType, out mcgGenericArgumentMarshalInfo))
{
return mcgGenericArgumentMarshalInfo.AsyncOperationType;
}
return default(RuntimeTypeHandle);
}
internal static int GetByteSize(this RuntimeTypeHandle interfaceType)
{
McgGenericArgumentMarshalInfo mcgGenericArgumentMarshalInfo;
if (McgModuleManager.TryGetGenericArgumentMarshalInfo(interfaceType, out mcgGenericArgumentMarshalInfo))
{
return (int)mcgGenericArgumentMarshalInfo.ElementSize;
}
return -1;
}
#endregion
#region "CCWTemplate Data"
internal static string GetCCWRuntimeClassName(this RuntimeTypeHandle ccwType)
{
string ccwRuntimeClassName;
if (McgModuleManager.TryGetCCWRuntimeClassName(ccwType, out ccwRuntimeClassName))
return ccwRuntimeClassName;
return default(string);
}
internal static bool IsSupportCCWTemplate(this RuntimeTypeHandle ccwType)
{
CCWTemplateInfo ccwTemplateInfo = McgModuleManager.GetCCWTemplateDataInfoFromTypeHandle(ccwType);
if (ccwTemplateInfo != null)
{
return true;
}
return false;
}
internal static bool IsCCWWinRTType(this RuntimeTypeHandle ccwType)
{
CCWTemplateInfo ccwTemplateInfo = McgModuleManager.GetCCWTemplateDataInfoFromTypeHandle(ccwType);
if (ccwTemplateInfo != null)
return ccwTemplateInfo.IsWinRTType;
#if ENABLE_WINRT
throw new MissingInteropDataException(SR.DelegateMarshalling_MissingInteropData, Type.GetTypeFromHandle(ccwType));
#else
Environment.FailFast("IsCCWWinRTType");
return false;
#endif
}
internal static IEnumerable<RuntimeTypeHandle> GetImplementedInterfaces(this RuntimeTypeHandle ccwType)
{
CCWTemplateInfo ccwTemplateInfo = McgModuleManager.GetCCWTemplateDataInfoFromTypeHandle(ccwType);
if (ccwTemplateInfo != null)
return ccwTemplateInfo.ImplementedInterfaces;
#if ENABLE_WINRT
throw new MissingInteropDataException(SR.DelegateMarshalling_MissingInteropData, Type.GetTypeFromHandle(ccwType));
#else
Environment.FailFast("GetImplementedInterfaces");
return null;
#endif
}
internal static RuntimeTypeHandle GetBaseClass(this RuntimeTypeHandle ccwType)
{
CCWTemplateInfo ccwTemplateInfo = McgModuleManager.GetCCWTemplateDataInfoFromTypeHandle(ccwType);
if (ccwTemplateInfo != null)
return ccwTemplateInfo.BaseClass;
#if ENABLE_WINRT
throw new MissingInteropDataException(SR.DelegateMarshalling_MissingInteropData, Type.GetTypeFromHandle(ccwType));
#else
Environment.FailFast("GetBaseClass");
return default(RuntimeTypeHandle);
#endif
}
private static void GetIIDsImpl(RuntimeTypeHandle typeHandle, System.Collections.Generic.Internal.List<Guid> iids)
{
RuntimeTypeHandle baseClass = typeHandle.GetBaseClass();
if (!baseClass.IsNull())
{
GetIIDsImpl(baseClass, iids);
}
foreach(RuntimeTypeHandle t in typeHandle.GetImplementedInterfaces())
{
if (t.IsInvalid())
continue;
Guid guid = t.GetInterfaceGuid();
//
// Retrieve the GUID and add it to the list
// Skip ICustomPropertyProvider - we've already added it as the first item
//
if (!InteropExtensions.GuidEquals(ref guid, ref Interop.COM.IID_ICustomPropertyProvider))
{
//
// Avoid duplicated ones
//
// The duplicates comes from duplicated interface declarations in the metadata across
// parent/child classes, as well as the "injected" override interfaces for protected
// virtual methods (for example, if a derived class implements a IShapeInternal protected
// method, it only implements a protected method and doesn't implement IShapeInternal
// directly, and we have to "inject" it in MCG
//
// Doing a linear lookup is slow, but people typically never call GetIIDs perhaps except
// for debugging purposes (because the GUIDs returned back aren't exactly useful and you
// can't map it back to type), so I don't care about perf here that much
//
if (!iids.Contains(guid))
iids.Add(guid);
}
}
}
/// <summary>
/// Return the list of IIDs
/// Used by IInspectable.GetIIDs implementation for every CCW
/// </summary>
internal static System.Collections.Generic.Internal.List<Guid> GetIIDs(this RuntimeTypeHandle ccwType)
{
System.Collections.Generic.Internal.List<Guid> iids = new System.Collections.Generic.Internal.List<Guid>();
// Every CCW implements ICPP
iids.Add(Interop.COM.IID_ICustomPropertyProvider);
// if there isn't any data about this type, just return empty list
if (!ccwType.IsSupportCCWTemplate())
return iids;
GetIIDsImpl(ccwType, iids);
return iids;
}
#endregion
internal static bool IsInvalid(this RuntimeTypeHandle typeHandle)
{
if (typeHandle.IsNull())
return true;
if (typeHandle.Equals(typeof(DependencyReductionTypeRemoved).TypeHandle))
return true;
return false;
}
}
public static class TypeOfHelper
{
static void RuntimeTypeHandleOf_DidntGetTransformedAway()
{
#if !RHTESTCL
Debug.Assert(false);
#endif // RHTESTCL
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName, string arg)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName, string arg1, string arg2)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName, string arg1, string arg2, string arg3)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName, string arg1, string arg2, string arg3, string arg4)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName, string arg1, string arg2, string arg3, string arg4, string arg5)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static RuntimeTypeHandle RuntimeTypeHandleOf(string typeName, string arg1, string arg2, string arg3, string arg4, string arg5, string arg6)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(RuntimeTypeHandle);
}
public static Type TypeOf(string typeName)
{
RuntimeTypeHandleOf_DidntGetTransformedAway();
return default(Type);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System.ServiceModel;
using System.Collections.Generic;
public sealed class DispatchOperation
{
string action;
SynchronizedCollection<ICallContextInitializer> callContextInitializers;
SynchronizedCollection<FaultContractInfo> faultContractInfos;
IDispatchMessageFormatter formatter;
IDispatchFaultFormatter faultFormatter;
bool includeExceptionDetailInFaults;
ImpersonationOption impersonation;
IOperationInvoker invoker;
bool isTerminating;
bool isSessionOpenNotificationEnabled;
string name;
SynchronizedCollection<IParameterInspector> parameterInspectors;
DispatchRuntime parent;
bool releaseInstanceAfterCall;
bool releaseInstanceBeforeCall;
string replyAction;
bool transactionAutoComplete;
bool transactionRequired;
bool deserializeRequest = true;
bool serializeReply = true;
bool isOneWay;
bool autoDisposeParameters = true;
bool hasNoDisposableParameters;
bool isFaultFormatterSetExplicit = false;
bool isInsideTransactedReceiveScope = false;
public DispatchOperation(DispatchRuntime parent, string name, string action)
{
if (parent == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent");
if (name == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");
this.parent = parent;
this.name = name;
this.action = action;
this.impersonation = OperationBehaviorAttribute.DefaultImpersonationOption;
this.callContextInitializers = parent.NewBehaviorCollection<ICallContextInitializer>();
this.faultContractInfos = parent.NewBehaviorCollection<FaultContractInfo>();
this.parameterInspectors = parent.NewBehaviorCollection<IParameterInspector>();
this.isOneWay = true;
}
public DispatchOperation(DispatchRuntime parent, string name, string action, string replyAction)
: this(parent, name, action)
{
this.replyAction = replyAction;
this.isOneWay = false;
}
public bool IsOneWay
{
get { return this.isOneWay; }
}
public string Action
{
get { return this.action; }
}
public SynchronizedCollection<ICallContextInitializer> CallContextInitializers
{
get { return this.callContextInitializers; }
}
public SynchronizedCollection<FaultContractInfo> FaultContractInfos
{
get { return this.faultContractInfos; }
}
public bool AutoDisposeParameters
{
get { return this.autoDisposeParameters; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.autoDisposeParameters = value;
}
}
}
public IDispatchMessageFormatter Formatter
{
get { return this.formatter; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.formatter = value;
}
}
}
internal IDispatchFaultFormatter FaultFormatter
{
get
{
if (this.faultFormatter == null)
{
this.faultFormatter = new DataContractSerializerFaultFormatter(this.faultContractInfos);
}
return this.faultFormatter;
}
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.faultFormatter = value;
this.isFaultFormatterSetExplicit = true;
}
}
}
internal bool IncludeExceptionDetailInFaults
{
get
{
return this.includeExceptionDetailInFaults;
}
set
{
this.includeExceptionDetailInFaults = value;
}
}
internal bool IsFaultFormatterSetExplicit
{
get
{
return this.isFaultFormatterSetExplicit;
}
}
public ImpersonationOption Impersonation
{
get { return this.impersonation; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.impersonation = value;
}
}
}
internal bool HasNoDisposableParameters
{
get { return this.hasNoDisposableParameters; }
set { this.hasNoDisposableParameters = value; }
}
internal IDispatchMessageFormatter InternalFormatter
{
get { return this.formatter; }
set { this.formatter = value; }
}
internal IOperationInvoker InternalInvoker
{
get { return this.invoker; }
set { this.invoker = value; }
}
public IOperationInvoker Invoker
{
get { return this.invoker; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.invoker = value;
}
}
}
public bool IsTerminating
{
get { return this.isTerminating; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.isTerminating = value;
}
}
}
internal bool IsSessionOpenNotificationEnabled
{
get { return this.isSessionOpenNotificationEnabled; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.isSessionOpenNotificationEnabled = value;
}
}
}
public string Name
{
get { return this.name; }
}
public SynchronizedCollection<IParameterInspector> ParameterInspectors
{
get { return this.parameterInspectors; }
}
public DispatchRuntime Parent
{
get { return this.parent; }
}
internal ReceiveContextAcknowledgementMode ReceiveContextAcknowledgementMode
{
get;
set;
}
internal bool BufferedReceiveEnabled
{
get { return this.parent.ChannelDispatcher.BufferedReceiveEnabled; }
set { this.parent.ChannelDispatcher.BufferedReceiveEnabled = value; }
}
public bool ReleaseInstanceAfterCall
{
get { return this.releaseInstanceAfterCall; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.releaseInstanceAfterCall = value;
}
}
}
public bool ReleaseInstanceBeforeCall
{
get { return this.releaseInstanceBeforeCall; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.releaseInstanceBeforeCall = value;
}
}
}
public string ReplyAction
{
get { return this.replyAction; }
}
public bool DeserializeRequest
{
get { return this.deserializeRequest; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.deserializeRequest = value;
}
}
}
public bool SerializeReply
{
get { return this.serializeReply; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.serializeReply = value;
}
}
}
public bool TransactionAutoComplete
{
get { return this.transactionAutoComplete; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.transactionAutoComplete = value;
}
}
}
public bool TransactionRequired
{
get { return this.transactionRequired; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.transactionRequired = value;
}
}
}
public bool IsInsideTransactedReceiveScope
{
get { return this.isInsideTransactedReceiveScope; }
set
{
lock (this.parent.ThisLock)
{
this.parent.InvalidateRuntime();
this.isInsideTransactedReceiveScope = value;
}
}
}
}
}
| |
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace OfficeDevPnP.Core.Utilities
{
/// <summary>
/// Static methods to modify URL paths.
/// </summary>
public static class UrlUtility
{
const char PATH_DELIMITER = '/';
#if !ONPREMISES
const string INVALID_CHARS_REGEX = @"[\\#%*/:<>?+|\""]";
const string REGEX_INVALID_FILEFOLDER_NAME_CHARS = @"[""#%*:<>?/\|\t\r\n]";
#else
const string INVALID_CHARS_REGEX = @"[\\~#%&*{}/:<>?+|\""]";
const string REGEX_INVALID_FILEFOLDER_NAME_CHARS = @"[~#%&*{}\:<>?/|""\t\r\n]";
#endif
const string IIS_MAPPED_PATHS_REGEX = @"/(_layouts|_admin|_app_bin|_controltemplates|_login|_vti_bin|_vti_pvt|_windows|_wpresources)/";
#region [ Combine ]
/// <summary>
/// Combines a path and a relative path.
/// </summary>
/// <param name="path">A SharePoint URL</param>
/// <param name="relativePaths">SharePoint relative URLs</param>
/// <returns>Returns comibed path with a relative paths</returns>
public static string Combine(string path, params string[] relativePaths) {
string pathBuilder = path ?? string.Empty;
if (relativePaths == null)
return pathBuilder;
foreach (string relPath in relativePaths) {
pathBuilder = Combine(pathBuilder, relPath);
}
return pathBuilder;
}
/// <summary>
/// Combines a path and a relative path.
/// </summary>
/// <param name="path">A SharePoint URL</param>
/// <param name="relative">SharePoint relative URL</param>
/// <returns>Returns comibed path with a relative path</returns>
public static string Combine(string path, string relative)
{
if(relative == null)
relative = string.Empty;
if(path == null)
path = string.Empty;
if(relative.Length == 0 && path.Length == 0)
return string.Empty;
if(relative.Length == 0)
return path;
if(path.Length == 0)
return relative;
path = path.Replace('\\', PATH_DELIMITER);
relative = relative.Replace('\\', PATH_DELIMITER);
return path.TrimEnd(PATH_DELIMITER) + PATH_DELIMITER + relative.TrimStart(PATH_DELIMITER);
}
#endregion
#region [ AppendQueryString ]
/// <summary>
/// Adds query string parameters to the end of a querystring and guarantees the proper concatenation with <b>?</b> and <b>&.</b>
/// </summary>
/// <param name="path">A SharePoint URL</param>
/// <param name="queryString">Query string value that need to append to the URL</param>
/// <returns>Returns URL along with appended query string</returns>
public static string AppendQueryString(string path, string queryString)
{
string url = path;
if (queryString != null && queryString.Length > 0)
{
char startChar = (path.IndexOf("?") > 0) ? '&' : '?';
url = string.Concat(path, startChar, queryString.TrimStart('?'));
}
return url;
}
#endregion
#region [ RelativeUrl ]
/// <summary>
/// Returns realtive URL of given URL
/// </summary>
/// <param name="urlToProcess">SharePoint URL to process</param>
/// <returns>Returns realtive URL of given URL</returns>
public static string MakeRelativeUrl(string urlToProcess) {
Uri uri = new Uri(urlToProcess);
return uri.AbsolutePath;
}
/// <summary>
/// Ensures that there is a trailing slash at the end of the URL
/// </summary>
/// <param name="urlToProcess"></param>
/// <returns></returns>
public static string EnsureTrailingSlash(string urlToProcess)
{
if (!urlToProcess.EndsWith("/"))
{
return urlToProcess + "/";
}
return urlToProcess;
}
#endregion
/// <summary>
/// Checks if URL contains invalid characters or not
/// </summary>
/// <param name="content">Url value</param>
/// <returns>Returns true if URL contains invalid characters. Otherwise returns false.</returns>
public static bool ContainsInvalidUrlChars(this string content)
{
return Regex.IsMatch(content, INVALID_CHARS_REGEX);
}
/// <summary>
/// Checks if file or folder contains invalid characters or not
/// </summary>
/// <param name="content">File or folder name to check</param>
/// <returns>True if contains invalid chars, false otherwise</returns>
public static bool ContainsInvalidFileFolderChars(this string content)
{
return Regex.IsMatch(content, REGEX_INVALID_FILEFOLDER_NAME_CHARS);
}
/// <summary>
/// Removes invalid characters
/// </summary>
/// <param name="content">Url value</param>
/// <returns>Returns URL without invalid characters</returns>
public static string StripInvalidUrlChars(this string content)
{
return ReplaceInvalidUrlChars(content, "");
}
/// <summary>
/// Replaces invalid charcters with other characters
/// </summary>
/// <param name="content">Url value</param>
/// <param name="replacer">string need to replace with invalid characters</param>
/// <returns>Returns replaced invalid charcters from URL</returns>
public static string ReplaceInvalidUrlChars(this string content, string replacer)
{
return new Regex(INVALID_CHARS_REGEX).Replace(content, replacer);
}
/// <summary>
/// Tells URL is virtual directory or not
/// </summary>
/// <param name="url">SharePoint URL</param>
/// <returns>Returns true if URL is virtual directory. Otherwise returns false.</returns>
public static bool IsIisVirtualDirectory(string url)
{
return Regex.IsMatch(url, IIS_MAPPED_PATHS_REGEX, RegexOptions.IgnoreCase);
}
/// <summary>
/// Taken from Microsoft.SharePoint.Utilities.SPUtility
/// </summary>
/// <param name="strUrl"></param>
/// <param name="strBaseUrl"></param>
/// <returns></returns>
internal static string ConvertToServiceRelUrl(string strUrl, string strBaseUrl)
{
if (((strBaseUrl == null) || !StsStartsWith(strBaseUrl, "/")) || ((strUrl == null) || !StsStartsWith(strUrl, "/")))
{
throw new ArgumentException();
}
if ((strUrl.Length > 1) && (strUrl[strUrl.Length - 1] == '/'))
{
strUrl = strUrl.Substring(0, strUrl.Length - 1);
}
if ((strBaseUrl.Length > 1) && (strBaseUrl[strBaseUrl.Length - 1] == '/'))
{
strBaseUrl = strBaseUrl.Substring(0, strBaseUrl.Length - 1);
}
if (!StsStartsWith(strUrl, strBaseUrl))
{
throw new ArgumentException();
}
if (strBaseUrl == "/")
{
return strUrl.Substring(1);
}
if (strUrl.Length == strBaseUrl.Length)
{
return "";
}
return strUrl.Substring(strBaseUrl.Length + 1);
}
/// <summary>
/// Taken from Microsoft.SharePoint.Utilities.SPUtility
/// </summary>
/// <param name="strMain"></param>
/// <param name="strBegining"></param>
/// <returns></returns>
internal static bool StsStartsWith(string strMain, string strBegining)
{
return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(strMain, strBegining, CompareOptions.IgnoreCase);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.CompilerServices;
using DelegateTestInternal;
using Xunit;
namespace DelegateTestInternal
{
public static class TestExtensionMethod
{
public static DelegateTests.TestStruct TestFunc(this DelegateTests.TestClass testparam)
{
return testparam.structField;
}
}
}
public static unsafe class DelegateTests
{
public struct TestStruct
{
public object o1;
public object o2;
}
public class TestClass
{
public TestStruct structField;
}
public delegate int SomeDelegate(int x);
private static int SquareNumber(int x)
{
return x * x;
}
private static void EmptyFunc()
{
return;
}
public delegate TestStruct StructReturningDelegate();
[Fact]
public static void TestClosedStaticDelegate()
{
TestClass foo = new TestClass();
foo.structField.o1 = new object();
foo.structField.o2 = new object();
StructReturningDelegate testDelegate = foo.TestFunc;
TestStruct returnedStruct = testDelegate();
Assert.True(RuntimeHelpers.ReferenceEquals(foo.structField.o1, returnedStruct.o1));
Assert.True(RuntimeHelpers.ReferenceEquals(foo.structField.o2, returnedStruct.o2));
}
public class A { }
public class B : A { }
public delegate A DynamicInvokeDelegate(A nonRefParam1, B nonRefParam2, ref A refParam, out B outParam);
public static A DynamicInvokeTestFunction(A nonRefParam1, B nonRefParam2, ref A refParam, out B outParam)
{
outParam = (B)refParam;
refParam = nonRefParam2;
return nonRefParam1;
}
[Fact]
public static void TestDynamicInvoke()
{
A a1 = new A();
A a2 = new A();
B b1 = new B();
B b2 = new B();
DynamicInvokeDelegate testDelegate = DynamicInvokeTestFunction;
// Check that the delegate behaves as expected
A refParam = b2;
B outParam = null;
A returnValue = testDelegate(a1, b1, ref refParam, out outParam);
Assert.True(RuntimeHelpers.ReferenceEquals(returnValue, a1));
Assert.True(RuntimeHelpers.ReferenceEquals(refParam, b1));
Assert.True(RuntimeHelpers.ReferenceEquals(outParam, b2));
// Check dynamic invoke behavior
object[] parameters = new object[4];
parameters[0] = a1;
parameters[1] = b1;
parameters[2] = b2;
parameters[3] = null;
object retVal = testDelegate.DynamicInvoke(parameters);
Assert.True(RuntimeHelpers.ReferenceEquals(retVal, a1));
Assert.True(RuntimeHelpers.ReferenceEquals(parameters[2], b1));
Assert.True(RuntimeHelpers.ReferenceEquals(parameters[3], b2));
// Check invoke on a delegate that takes no parameters.
Action emptyDelegate = EmptyFunc;
emptyDelegate.DynamicInvoke(new object[] { });
emptyDelegate.DynamicInvoke(null);
}
[Fact]
public static void TestDynamicInvokeCastingDefaultValues()
{
{
// Passing Type.Missing without providing default.
Delegate d = new DFoo1(Foo1);
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(7, Type.Missing));
}
{
// Passing Type.Missing with default.
Delegate d = new DFoo1WithDefault(Foo1);
d.DynamicInvoke(7, Type.Missing);
}
return;
}
[Fact]
public static void TestDynamicInvokeCastingByRef()
{
{
Delegate d = new DFoo2(Foo2);
object[] args = { 7 };
d.DynamicInvoke(args);
Assert.Equal(args[0], 8);
}
{
Delegate d = new DFoo2(Foo2);
object[] args = { null };
d.DynamicInvoke(args);
Assert.Equal(args[0], 1);
}
// for "byref ValueType" arguments, the incoming is allowed to be null. The target will receive default(ValueType).
{
Delegate d = new DFoo3(Foo3);
object[] args = { null };
d.DynamicInvoke(args);
MyStruct s = (MyStruct)(args[0]);
Assert.Equal(s.X, 7);
Assert.Equal(s.Y, 8);
}
// For "byref ValueType" arguments, the type must match exactly.
{
Delegate d = new DFoo2(Foo2);
object[] args = { (uint)7 };
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(args));
}
{
Delegate d = new DFoo2(Foo2);
object[] args = { E4.One };
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(args));
}
return;
}
[Fact]
public static void TestDynamicInvokeCastingPrimitiveWiden()
{
{
// For primitives, value-preserving widenings allowed.
Delegate d = new DFoo1(Foo1);
object[] args = { 7, (short)7 };
d.DynamicInvoke(args);
}
{
// For primitives, conversion of enum to underlying integral prior to value-preserving widening allowed.
Delegate d = new DFoo1(Foo1);
object[] args = { 7, E4.Seven };
d.DynamicInvoke(args);
}
{
// For primitives, conversion of enum to underlying integral prior to value-preserving widening allowed.
Delegate d = new DFoo1(Foo1);
object[] args = { 7, E2.Seven };
d.DynamicInvoke(args);
}
{
// For primitives, conversion to enum after value-preserving widening allowed.
Delegate d = new DFoo4(Foo4);
object[] args = { E4.Seven, 7 };
d.DynamicInvoke(args);
}
{
// For primitives, conversion to enum after value-preserving widening allowed.
Delegate d = new DFoo4(Foo4);
object[] args = { E4.Seven, (short)7 };
d.DynamicInvoke(args);
}
{
// Size-preserving but non-value-preserving conversions NOT allowed.
Delegate d = new DFoo1(Foo1);
object[] args = { 7, (uint)7 };
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(args));
}
{
// Size-preserving but non-value-preserving conversions NOT allowed.
Delegate d = new DFoo1(Foo1);
object[] args = { 7, U4.Seven };
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(args));
}
return;
}
[Fact]
public static void TestDynamicInvokeCastingMisc()
{
{
// DynamicInvoke allows "null" for any value type (converts to default(valuetype)).
Delegate d = new DFoo5(Foo5);
object[] args = { null };
d.DynamicInvoke(args);
}
{
// DynamicInvoke allows conversion of T to Nullable<T>
Delegate d = new DFoo6(Foo6);
object[] args = { 7 };
d.DynamicInvoke(args);
}
{
// DynamicInvoke allows conversion of T to Nullable<T> but T must match exactly.
Delegate d = new DFoo6(Foo6);
object[] args = { (short)7 };
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(args));
}
{
// DynamicInvoke allows conversion of T to Nullable<T> but T must match exactly.
Delegate d = new DFoo6(Foo6);
object[] args = { E4.Seven };
Assert.Throws<ArgumentException>(() => d.DynamicInvoke(args));
}
return;
}
private static void Foo1(int expected, int actual)
{
Assert.Equal(expected, actual);
}
private delegate void DFoo1(int expected, int actual);
private delegate void DFoo1WithDefault(int expected, int actual = 7);
private static void Foo2(ref int i)
{
i++;
}
private delegate void DFoo2(ref int i);
private struct MyStruct
{
public int X;
public int Y;
}
private static void Foo3(ref MyStruct s)
{
s.X += 7;
s.Y += 8;
}
private delegate void DFoo3(ref MyStruct s);
private static void Foo4(E4 expected, E4 actual)
{
Assert.Equal(expected, actual);
}
private delegate void DFoo4(E4 expected, E4 actual);
private static void Foo5(MyStruct s)
{
Assert.Equal(s.X, 0);
Assert.Equal(s.Y, 0);
}
private delegate void DFoo5(MyStruct s);
private static void Foo6(Nullable<int> n)
{
Assert.True(n.HasValue);
Assert.Equal(n.Value, 7);
}
private delegate void DFoo6(Nullable<int> s);
private enum E2 : short
{
One = 1,
Seven = 7,
}
private enum E4 : int
{
One = 1,
Seven = 7,
}
private enum U4 : uint
{
One = 1,
Seven = 7,
}
}
| |
// 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;
using System.Data.Common;
using System.Diagnostics;
namespace System.Data.SqlClient
{
internal sealed class SqlConnectionString : DbConnectionOptions
{
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
internal static class DEFAULT
{
internal const ApplicationIntent ApplicationIntent = DbConnectionStringDefaults.ApplicationIntent;
internal const string Application_Name = TdsEnums.SQL_PROVIDER_NAME;
internal const string AttachDBFilename = "";
internal const int Connect_Timeout = ADP.DefaultConnectionTimeout;
internal const string Current_Language = "";
internal const string Data_Source = "";
internal const bool Encrypt = false;
internal const string FailoverPartner = "";
internal const string Initial_Catalog = "";
internal const bool Integrated_Security = false;
internal const int Load_Balance_Timeout = 0; // default of 0 means don't use
internal const bool MARS = false;
internal const int Max_Pool_Size = 100;
internal const int Min_Pool_Size = 0;
internal const bool MultiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover;
internal const int Packet_Size = 8000;
internal const string Password = "";
internal const bool Persist_Security_Info = false;
internal const bool Pooling = true;
internal const bool TrustServerCertificate = false;
internal const string Type_System_Version = "";
internal const string User_ID = "";
internal const bool User_Instance = false;
internal const bool Replication = false;
internal const int Connect_Retry_Count = 1;
internal const int Connect_Retry_Interval = 10;
}
// SqlConnection ConnectionString Options
// keys must be lowercase!
internal static class KEY
{
internal const string ApplicationIntent = "applicationintent";
internal const string Application_Name = "application name";
internal const string AsynchronousProcessing = "asynchronous processing";
internal const string AttachDBFilename = "attachdbfilename";
internal const string Connect_Timeout = "connect timeout";
internal const string Connection_Reset = "connection reset";
internal const string Context_Connection = "context connection";
internal const string Current_Language = "current language";
internal const string Data_Source = "data source";
internal const string Encrypt = "encrypt";
internal const string Enlist = "enlist";
internal const string FailoverPartner = "failover partner";
internal const string Initial_Catalog = "initial catalog";
internal const string Integrated_Security = "integrated security";
internal const string Load_Balance_Timeout = "load balance timeout";
internal const string MARS = "multipleactiveresultsets";
internal const string Max_Pool_Size = "max pool size";
internal const string Min_Pool_Size = "min pool size";
internal const string MultiSubnetFailover = "multisubnetfailover";
internal const string Network_Library = "network library";
internal const string Packet_Size = "packet size";
internal const string Password = "password";
internal const string Persist_Security_Info = "persist security info";
internal const string Pooling = "pooling";
internal const string TransactionBinding = "transaction binding";
internal const string TrustServerCertificate = "trustservercertificate";
internal const string Type_System_Version = "type system version";
internal const string User_ID = "user id";
internal const string User_Instance = "user instance";
internal const string Workstation_Id = "workstation id";
internal const string Replication = "replication";
internal const string Connect_Retry_Count = "connectretrycount";
internal const string Connect_Retry_Interval = "connectretryinterval";
}
// Constant for the number of duplicate options in the connection string
private static class SYNONYM
{
// application name
internal const string APP = "app";
internal const string Async = "async";
// attachDBFilename
internal const string EXTENDED_PROPERTIES = "extended properties";
internal const string INITIAL_FILE_NAME = "initial file name";
// connect timeout
internal const string CONNECTION_TIMEOUT = "connection timeout";
internal const string TIMEOUT = "timeout";
// current language
internal const string LANGUAGE = "language";
// data source
internal const string ADDR = "addr";
internal const string ADDRESS = "address";
internal const string SERVER = "server";
internal const string NETWORK_ADDRESS = "network address";
// initial catalog
internal const string DATABASE = "database";
// integrated security
internal const string TRUSTED_CONNECTION = "trusted_connection";
// load balance timeout
internal const string Connection_Lifetime = "connection lifetime";
// network library
internal const string NET = "net";
internal const string NETWORK = "network";
// password
internal const string Pwd = "pwd";
// persist security info
internal const string PERSISTSECURITYINFO = "persistsecurityinfo";
// user id
internal const string UID = "uid";
internal const string User = "user";
// workstation id
internal const string WSID = "wsid";
// make sure to update SynonymCount value below when adding or removing synonyms
}
internal const int SynonymCount = 18;
internal const int DeprecatedSynonymCount = 3;
internal enum TypeSystem
{
Latest = 2008,
SQLServer2000 = 2000,
SQLServer2005 = 2005,
SQLServer2008 = 2008,
SQLServer2012 = 2012,
}
internal static class TYPESYSTEMVERSION
{
internal const string Latest = "Latest";
internal const string SQL_Server_2000 = "SQL Server 2000";
internal const string SQL_Server_2005 = "SQL Server 2005";
internal const string SQL_Server_2008 = "SQL Server 2008";
internal const string SQL_Server_2012 = "SQL Server 2012";
}
static private Hashtable s_sqlClientSynonyms;
private readonly bool _integratedSecurity;
private readonly bool _encrypt;
private readonly bool _trustServerCertificate;
private readonly bool _mars;
private readonly bool _persistSecurityInfo;
private readonly bool _pooling;
private readonly bool _replication;
private readonly bool _userInstance;
private readonly bool _multiSubnetFailover;
private readonly int _connectTimeout;
private readonly int _loadBalanceTimeout;
private readonly int _maxPoolSize;
private readonly int _minPoolSize;
private readonly int _packetSize;
private readonly int _connectRetryCount;
private readonly int _connectRetryInterval;
private readonly ApplicationIntent _applicationIntent;
private readonly string _applicationName;
private readonly string _attachDBFileName;
private readonly string _currentLanguage;
private readonly string _dataSource;
private readonly string _localDBInstance; // created based on datasource, set to NULL if datasource is not LocalDB
private readonly string _failoverPartner;
private readonly string _initialCatalog;
private readonly string _password;
private readonly string _userID;
private readonly string _workstationId;
private readonly TypeSystem _typeSystemVersion;
internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms())
{
ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing);
ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset);
ThrowUnsupportedIfKeywordSet(KEY.Context_Connection);
ThrowUnsupportedIfKeywordSet(KEY.Enlist);
ThrowUnsupportedIfKeywordSet(KEY.TransactionBinding);
#if MANAGED_SNI
ThrowUnsupportedIfKeywordSet(KEY.Integrated_Security);
#endif
// Network Library has its own special error message
if (ContainsKey(KEY.Network_Library))
{
throw SQL.NetworkLibraryKeywordNotSupported();
}
_integratedSecurity = ConvertValueToIntegratedSecurity();
_encrypt = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt);
_mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS);
_persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info);
_pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling);
_replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication);
_userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance);
_multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover);
_connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout);
_loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout);
_maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size);
_minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size);
_packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size);
_connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count);
_connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval);
_applicationIntent = ConvertValueToApplicationIntent();
_applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name);
_attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename);
_currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language);
_dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source);
_localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
_failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner);
_initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog);
_password = ConvertValueToString(KEY.Password, DEFAULT.Password);
_trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate);
// Temporary string - this value is stored internally as an enum.
string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null);
_userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID);
_workstationId = ConvertValueToString(KEY.Workstation_Id, null);
if (_loadBalanceTimeout < 0)
{
throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout);
}
if (_connectTimeout < 0)
{
throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout);
}
if (_maxPoolSize < 1)
{
throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size);
}
if (_minPoolSize < 0)
{
throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size);
}
if (_maxPoolSize < _minPoolSize)
{
throw ADP.InvalidMinMaxPoolSizeValues();
}
if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize))
{
throw SQL.InvalidPacketSizeValue();
}
ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name);
ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language);
ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner);
ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog);
ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password);
ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID);
if (null != _workstationId)
{
ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id);
}
if (!String.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase))
{
// fail-over partner is set
if (_multiSubnetFailover)
{
throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null);
}
if (String.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase))
{
throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog);
}
}
if (0 <= _attachDBFileName.IndexOf('|'))
{
throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename);
}
else
{
ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename);
}
if (true == _userInstance && !ADP.IsEmpty(_failoverPartner))
{
throw SQL.UserInstanceFailoverNotCompatible();
}
if (ADP.IsEmpty(typeSystemVersionString))
{
typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion;
}
if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.Latest;
}
else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.SQLServer2000;
}
else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.SQLServer2005;
}
else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.SQLServer2008;
}
else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase))
{
_typeSystemVersion = TypeSystem.SQLServer2012;
}
else
{
throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version);
}
if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner))
throw SQL.ROR_FailoverNotSupportedConnString();
if ((_connectRetryCount < 0) || (_connectRetryCount > 255))
{
throw ADP.InvalidConnectRetryCountValue();
}
if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60))
{
throw ADP.InvalidConnectRetryIntervalValue();
}
}
// This c-tor is used to create SSE and user instance connection strings when user instance is set to true
// BUG (VSTFDevDiv) 479687: Using TransactionScope with Linq2SQL against user instances fails with "connection has been broken" message
internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance) : base(connectionOptions)
{
_integratedSecurity = connectionOptions._integratedSecurity;
_encrypt = connectionOptions._encrypt;
_mars = connectionOptions._mars;
_persistSecurityInfo = connectionOptions._persistSecurityInfo;
_pooling = connectionOptions._pooling;
_replication = connectionOptions._replication;
_userInstance = userInstance;
_connectTimeout = connectionOptions._connectTimeout;
_loadBalanceTimeout = connectionOptions._loadBalanceTimeout;
_maxPoolSize = connectionOptions._maxPoolSize;
_minPoolSize = connectionOptions._minPoolSize;
_multiSubnetFailover = connectionOptions._multiSubnetFailover;
_packetSize = connectionOptions._packetSize;
_applicationName = connectionOptions._applicationName;
_attachDBFileName = connectionOptions._attachDBFileName;
_currentLanguage = connectionOptions._currentLanguage;
_dataSource = dataSource;
_localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
_failoverPartner = connectionOptions._failoverPartner;
_initialCatalog = connectionOptions._initialCatalog;
_password = connectionOptions._password;
_userID = connectionOptions._userID;
_workstationId = connectionOptions._workstationId;
_typeSystemVersion = connectionOptions._typeSystemVersion;
_applicationIntent = connectionOptions._applicationIntent;
_connectRetryCount = connectionOptions._connectRetryCount;
_connectRetryInterval = connectionOptions._connectRetryInterval;
ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
}
internal bool IntegratedSecurity { get { return _integratedSecurity; } }
// We always initialize in Async mode so that both synchronous and asynchronous methods
// will work. In the future we can deprecate the keyword entirely.
internal bool Asynchronous { get { return true; } }
// SQLPT 41700: Ignore ResetConnection=False, always reset the connection for security
internal bool ConnectionReset { get { return true; } }
// internal bool EnableUdtDownload { get { return _enableUdtDownload;} }
internal bool Encrypt { get { return _encrypt; } }
internal bool TrustServerCertificate { get { return _trustServerCertificate; } }
internal bool MARS { get { return _mars; } }
internal bool MultiSubnetFailover { get { return _multiSubnetFailover; } }
internal bool PersistSecurityInfo { get { return _persistSecurityInfo; } }
internal bool Pooling { get { return _pooling; } }
internal bool Replication { get { return _replication; } }
internal bool UserInstance { get { return _userInstance; } }
internal int ConnectTimeout { get { return _connectTimeout; } }
internal int LoadBalanceTimeout { get { return _loadBalanceTimeout; } }
internal int MaxPoolSize { get { return _maxPoolSize; } }
internal int MinPoolSize { get { return _minPoolSize; } }
internal int PacketSize { get { return _packetSize; } }
internal int ConnectRetryCount { get { return _connectRetryCount; } }
internal int ConnectRetryInterval { get { return _connectRetryInterval; } }
internal ApplicationIntent ApplicationIntent { get { return _applicationIntent; } }
internal string ApplicationName { get { return _applicationName; } }
internal string AttachDBFilename { get { return _attachDBFileName; } }
internal string CurrentLanguage { get { return _currentLanguage; } }
internal string DataSource { get { return _dataSource; } }
internal string LocalDBInstance { get { return _localDBInstance; } }
internal string FailoverPartner { get { return _failoverPartner; } }
internal string InitialCatalog { get { return _initialCatalog; } }
internal string Password { get { return _password; } }
internal string UserID { get { return _userID; } }
internal string WorkstationId { get { return _workstationId; } }
internal TypeSystem TypeSystemVersion { get { return _typeSystemVersion; } }
// this hashtable is meant to be read-only translation of parsed string
// keywords/synonyms to a known keyword string
internal static Hashtable GetParseSynonyms()
{
Hashtable hash = s_sqlClientSynonyms;
if (null == hash)
{
hash = new Hashtable(SqlConnectionStringBuilder.KeywordsCount + SqlConnectionStringBuilder.DeprecatedKeywordsCount + SynonymCount + DeprecatedSynonymCount);
hash.Add(KEY.ApplicationIntent, KEY.ApplicationIntent);
hash.Add(KEY.Application_Name, KEY.Application_Name);
hash.Add(KEY.AsynchronousProcessing, KEY.AsynchronousProcessing);
hash.Add(KEY.AttachDBFilename, KEY.AttachDBFilename);
hash.Add(KEY.Connect_Timeout, KEY.Connect_Timeout);
hash.Add(KEY.Connection_Reset, KEY.Connection_Reset);
hash.Add(KEY.Context_Connection, KEY.Context_Connection);
hash.Add(KEY.Current_Language, KEY.Current_Language);
hash.Add(KEY.Data_Source, KEY.Data_Source);
hash.Add(KEY.Encrypt, KEY.Encrypt);
hash.Add(KEY.Enlist, KEY.Enlist);
hash.Add(KEY.FailoverPartner, KEY.FailoverPartner);
hash.Add(KEY.Initial_Catalog, KEY.Initial_Catalog);
hash.Add(KEY.Integrated_Security, KEY.Integrated_Security);
hash.Add(KEY.Load_Balance_Timeout, KEY.Load_Balance_Timeout);
hash.Add(KEY.MARS, KEY.MARS);
hash.Add(KEY.Max_Pool_Size, KEY.Max_Pool_Size);
hash.Add(KEY.Min_Pool_Size, KEY.Min_Pool_Size);
hash.Add(KEY.MultiSubnetFailover, KEY.MultiSubnetFailover);
hash.Add(KEY.Network_Library, KEY.Network_Library);
hash.Add(KEY.Packet_Size, KEY.Packet_Size);
hash.Add(KEY.Password, KEY.Password);
hash.Add(KEY.Persist_Security_Info, KEY.Persist_Security_Info);
hash.Add(KEY.Pooling, KEY.Pooling);
hash.Add(KEY.Replication, KEY.Replication);
hash.Add(KEY.TrustServerCertificate, KEY.TrustServerCertificate);
hash.Add(KEY.TransactionBinding, KEY.TransactionBinding);
hash.Add(KEY.Type_System_Version, KEY.Type_System_Version);
hash.Add(KEY.User_ID, KEY.User_ID);
hash.Add(KEY.User_Instance, KEY.User_Instance);
hash.Add(KEY.Workstation_Id, KEY.Workstation_Id);
hash.Add(KEY.Connect_Retry_Count, KEY.Connect_Retry_Count);
hash.Add(KEY.Connect_Retry_Interval, KEY.Connect_Retry_Interval);
hash.Add(SYNONYM.APP, KEY.Application_Name);
hash.Add(SYNONYM.Async, KEY.AsynchronousProcessing);
hash.Add(SYNONYM.EXTENDED_PROPERTIES, KEY.AttachDBFilename);
hash.Add(SYNONYM.INITIAL_FILE_NAME, KEY.AttachDBFilename);
hash.Add(SYNONYM.CONNECTION_TIMEOUT, KEY.Connect_Timeout);
hash.Add(SYNONYM.TIMEOUT, KEY.Connect_Timeout);
hash.Add(SYNONYM.LANGUAGE, KEY.Current_Language);
hash.Add(SYNONYM.ADDR, KEY.Data_Source);
hash.Add(SYNONYM.ADDRESS, KEY.Data_Source);
hash.Add(SYNONYM.NETWORK_ADDRESS, KEY.Data_Source);
hash.Add(SYNONYM.SERVER, KEY.Data_Source);
hash.Add(SYNONYM.DATABASE, KEY.Initial_Catalog);
hash.Add(SYNONYM.TRUSTED_CONNECTION, KEY.Integrated_Security);
hash.Add(SYNONYM.Connection_Lifetime, KEY.Load_Balance_Timeout);
hash.Add(SYNONYM.NET, KEY.Network_Library);
hash.Add(SYNONYM.NETWORK, KEY.Network_Library);
hash.Add(SYNONYM.Pwd, KEY.Password);
hash.Add(SYNONYM.PERSISTSECURITYINFO, KEY.Persist_Security_Info);
hash.Add(SYNONYM.UID, KEY.User_ID);
hash.Add(SYNONYM.User, KEY.User_ID);
hash.Add(SYNONYM.WSID, KEY.Workstation_Id);
Debug.Assert(SqlConnectionStringBuilder.KeywordsCount + SqlConnectionStringBuilder.DeprecatedKeywordsCount + SynonymCount + DeprecatedSynonymCount == hash.Count, "incorrect initial ParseSynonyms size");
s_sqlClientSynonyms = hash;
}
return hash;
}
internal string ObtainWorkstationId()
{
// If not supplied by the user, the default value is the MachineName
// Note: In Longhorn you'll be able to rename a machine without
// rebooting. Therefore, don't cache this machine name.
string result = WorkstationId;
if (null == result)
{
// permission to obtain Environment.MachineName is Asserted
// since permission to open the connection has been granted
// the information is shared with the server, but not directly with the user
result = string.Empty;
}
return result;
}
private void ValidateValueLength(string value, int limit, string key)
{
if (limit < value.Length)
{
throw ADP.InvalidConnectionOptionValueLength(key, limit);
}
}
internal System.Data.SqlClient.ApplicationIntent ConvertValueToApplicationIntent()
{
object value = base.Parsetable[KEY.ApplicationIntent];
if (value == null)
{
return DEFAULT.ApplicationIntent;
}
// when wrong value is used in the connection string provided to SqlConnection.ConnectionString or c-tor,
// wrap Format and Overflow exceptions with Argument one, to be consistent with rest of the keyword types (like int and bool)
try
{
return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(KEY.ApplicationIntent, value);
}
catch (FormatException e)
{
throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e);
}
catch (OverflowException e)
{
throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e);
}
// ArgumentException and other types are raised as is (no wrapping)
}
internal void ThrowUnsupportedIfKeywordSet(string keyword)
{
if (ContainsKey(keyword))
{
throw SQL.UnsupportedKeyword(keyword);
}
}
}
}
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System;
using System.Text;
using System.Collections.Generic;
using Voxalia.Shared;
using Voxalia.ClientGame.ClientMainSystem;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL4;
using BEPUphysics;
using BEPUutilities;
using BEPUphysics.Settings;
using Voxalia.ClientGame.JointSystem;
using Voxalia.ClientGame.EntitySystem;
using BEPUutilities.Threading;
using BEPUphysics.BroadPhaseEntries;
using BEPUphysics.CollisionShapes.ConvexShapes;
using Voxalia.Shared.Collision;
using System.Diagnostics;
using Priority_Queue;
using FreneticScript;
using Voxalia.ClientGame.GraphicsSystems;
using Voxalia.ClientGame.OtherSystems;
using System.Threading.Tasks;
namespace Voxalia.ClientGame.WorldSystem
{
public partial class Region
{
/// <summary>
/// The physics world in which all physics-related activity takes place.
///
/// </summary>
public Space PhysicsWorld;
public CollisionUtil Collision;
public double Delta;
public Location GravityNormal = new Location(0, 0, -1);
public List<Entity> Entities = new List<Entity>();
public List<Entity> Tickers = new List<Entity>();
public List<Entity> ShadowCasters = new List<Entity>();
public PhysicsEntity[] GenShadowCasters = new PhysicsEntity[0];
public AABB[] Highlights = new AABB[0];
/// <summary>
/// Builds the physics world.
/// </summary>
public void BuildWorld()
{
ParallelLooper pl = new ParallelLooper();
for (int i = 0; i < Environment.ProcessorCount; i++)
{
pl.AddThread();
}
CollisionDetectionSettings.AllowedPenetration = 0.01f;
PhysicsWorld = new Space(pl);
PhysicsWorld.TimeStepSettings.MaximumTimeStepsPerFrame = 10;
// Set the world's general default gravity
PhysicsWorld.ForceUpdater.Gravity = new BEPUutilities.Vector3(0, 0, -9.8f * 3f / 2f);
PhysicsWorld.DuringForcesUpdateables.Add(new LiquidVolume(this));
// Load a CollisionUtil instance
Collision = new CollisionUtil(PhysicsWorld);
}
public void AddChunk(FullChunkObject mesh)
{
PhysicsWorld.Add(mesh);
}
public void RemoveChunkQuiet(FullChunkObject mesh)
{
PhysicsWorld.Remove(mesh);
}
public bool SpecialCaseRayTrace(Location start, Location dir, float len, MaterialSolidity considerSolid, Func<BroadPhaseEntry, bool> filter, out RayCastResult rayHit)
{
Ray ray = new Ray(start.ToBVector(), dir.ToBVector());
RayCastResult best = new RayCastResult(new RayHit() { T = len }, null);
bool hA = false;
if (considerSolid.HasFlag(MaterialSolidity.FULLSOLID))
{
RayCastResult rcr;
if (PhysicsWorld.RayCast(ray, len, filter, out rcr))
{
best = rcr;
hA = true;
}
}
AABB box = new AABB();
box.Min = start;
box.Max = start;
box.Include(start + dir * len);
foreach (KeyValuePair<Vector3i, Chunk> chunk in LoadedChunks)
{
if (chunk.Value == null || chunk.Value.FCO == null)
{
continue;
}
if (!box.Intersects(new AABB() { Min = chunk.Value.WorldPosition.ToLocation() * Chunk.CHUNK_SIZE, Max = chunk.Value.WorldPosition.ToLocation() * Chunk.CHUNK_SIZE + new Location(Chunk.CHUNK_SIZE) }))
{
continue;
}
RayHit temp;
if (chunk.Value.FCO.RayCast(ray, len, null, considerSolid, out temp))
{
hA = true;
//temp.T *= len;
if (temp.T < best.HitData.T)
{
best.HitData = temp;
best.HitObject = chunk.Value.FCO;
}
}
}
rayHit = best;
return hA;
}
public bool SpecialCaseConvexTrace(ConvexShape shape, Location start, Location dir, float len, MaterialSolidity considerSolid, Func<BroadPhaseEntry, bool> filter, out RayCastResult rayHit)
{
RigidTransform rt = new RigidTransform(start.ToBVector(), BEPUutilities.Quaternion.Identity);
BEPUutilities.Vector3 sweep = (dir * len).ToBVector();
RayCastResult best = new RayCastResult(new RayHit() { T = len }, null);
bool hA = false;
if (considerSolid.HasFlag(MaterialSolidity.FULLSOLID))
{
RayCastResult rcr;
if (PhysicsWorld.ConvexCast(shape, ref rt, ref sweep, filter, out rcr))
{
best = rcr;
hA = true;
}
}
sweep = dir.ToBVector();
AABB box = new AABB();
box.Min = start;
box.Max = start;
box.Include(start + dir * len);
foreach (KeyValuePair<Vector3i, Chunk> chunk in LoadedChunks)
{
if (chunk.Value == null || chunk.Value.FCO == null)
{
continue;
}
if (!box.Intersects(new AABB() { Min = chunk.Value.WorldPosition.ToLocation() * Chunk.CHUNK_SIZE, Max = chunk.Value.WorldPosition.ToLocation() * Chunk.CHUNK_SIZE + new Location(Chunk.CHUNK_SIZE) }))
{
continue;
}
RayHit temp;
if (chunk.Value.FCO.ConvexCast(shape, ref rt, ref sweep, len, considerSolid, out temp))
{
hA = true;
//temp.T *= len;
if (temp.T < best.HitData.T)
{
best.HitData = temp;
best.HitObject = chunk.Value.FCO;
}
}
}
rayHit = best;
return hA;
}
public double PhysTime;
/// <summary>
/// Ticks the physics world.
/// </summary>
public void TickWorld(double delta)
{
Delta = delta;
if (Delta <= 0)
{
return;
}
GlobalTickTimeLocal += Delta;
Stopwatch sw = new Stopwatch();
sw.Start();
PhysicsWorld.Update((float)delta); // TODO: More specific settings?
sw.Stop();
PhysTime = (double)sw.ElapsedMilliseconds / 1000f;
for (int i = 0; i < Tickers.Count; i++)
{
Tickers[i].Tick();
}
SolveJoints();
TickClouds();
CheckForRenderNeed();
}
public void SolveJoints()
{
for (int i = 0; i < Joints.Count; i++)
{
if (Joints[i].Enabled && Joints[i] is BaseFJoint)
{
((BaseFJoint)Joints[i]).Solve();
}
}
}
/// <summary>
/// Spawns an entity in the world.
/// </summary>
/// <param name="e">The entity to spawn.</param>
public void SpawnEntity(Entity e)
{
Entities.Add(e);
if (e.Ticks)
{
Tickers.Add(e);
}
if (e.CastShadows)
{
ShadowCasters.Add(e);
}
if (e is PhysicsEntity)
{
PhysicsEntity pe = e as PhysicsEntity;
pe.SpawnBody();
if (pe.GenBlockShadows)
{
// TODO: Effic?
PhysicsEntity[] neo = new PhysicsEntity[GenShadowCasters.Length + 1];
Array.Copy(GenShadowCasters, neo, GenShadowCasters.Length);
neo[neo.Length - 1] = pe;
GenShadowCasters = neo;
Chunk ch = TheClient.TheRegion.GetChunk(TheClient.TheRegion.ChunkLocFor(e.GetPosition()));
if (ch != null)
{
ch.CreateVBO(); // TODO: nearby / all affected chunks!
}
}
}
else if (e is PrimitiveEntity)
{
((PrimitiveEntity)e).Spawn();
}
}
public void Despawn(Entity e)
{
Entities.Remove(e);
if (e.Ticks)
{
Tickers.Remove(e);
}
if (e.CastShadows)
{
ShadowCasters.Remove(e);
}
if (e is PhysicsEntity)
{
PhysicsEntity pe = e as PhysicsEntity;
pe.DestroyBody();
for (int i = 0; i < pe.Joints.Count; i++)
{
DestroyJoint(pe.Joints[i]);
}
if (pe.GenBlockShadows)
{
PhysicsEntity[] neo = new PhysicsEntity[GenShadowCasters.Length - 1];
int x = 0;
bool valid = true;
for (int i = 0; i < GenShadowCasters.Length; i++)
{
if (GenShadowCasters[i] != pe)
{
neo[x++] = GenShadowCasters[i];
if (x == GenShadowCasters.Length)
{
valid = false;
return;
}
}
}
if (valid)
{
GenShadowCasters = neo;
}
}
}
else if (e is PrimitiveEntity)
{
((PrimitiveEntity)e).Destroy();
}
}
public InternalBaseJoint GetJoint(long JID)
{
for (int i = 0; i < Joints.Count; i++)
{
if (Joints[i].JID == JID)
{
return Joints[i];
}
}
return null;
}
public Entity GetEntity(long EID)
{
for (int i = 0; i < Entities.Count; i++)
{
if (Entities[i].EID == EID)
{
return Entities[i];
}
}
return null;
}
public Dictionary<Vector3i, Chunk> LoadedChunks = new Dictionary<Vector3i, Chunk>();
public Client TheClient;
public Vector3i ChunkLocFor(Location pos)
{
Vector3i temp;
temp.X = (int)Math.Floor(pos.X / Chunk.CHUNK_SIZE);
temp.Y = (int)Math.Floor(pos.Y / Chunk.CHUNK_SIZE);
temp.Z = (int)Math.Floor(pos.Z / Chunk.CHUNK_SIZE);
return temp;
}
public Chunk LoadChunk(Vector3i pos, int posMult)
{
Chunk chunk;
if (LoadedChunks.TryGetValue(pos, out chunk))
{
while (chunk.SucceededBy != null)
{
chunk = chunk.SucceededBy;
}
// TODO: ?!?!?!?
if (chunk.PosMultiplier != posMult)
{
Chunk ch = chunk;
chunk = new Chunk(posMult);
chunk.OwningRegion = this;
chunk.adding = ch.adding;
chunk.rendering = ch.rendering;
chunk._VBO = null;
chunk.WorldPosition = pos;
ch.SucceededBy = chunk;
chunk.OnRendered = () =>
{
LoadedChunks.Remove(pos);
ch.Destroy();
LoadedChunks.Add(pos, chunk);
};
}
}
else
{
chunk = new Chunk(posMult);
chunk.OwningRegion = this;
chunk.WorldPosition = pos;
LoadedChunks.Add(pos, chunk);
}
return chunk;
}
public Chunk GetChunk(Vector3i pos)
{
Chunk chunk;
if (LoadedChunks.TryGetValue(pos, out chunk))
{
return chunk;
}
return null;
}
public Material GetBlockMaterial(Location pos)
{
return (Material)GetBlockInternal(pos).BlockMaterial;
}
public BlockInternal GetBlockInternal(Location pos)
{
Chunk ch = GetChunk(ChunkLocFor(pos));
if (ch == null)
{
return new BlockInternal((ushort)Material.AIR, 0, 0, 255);
}
int x = (int)Math.Floor(((int)Math.Floor(pos.X) - (int)ch.WorldPosition.X * Chunk.CHUNK_SIZE) / (float)ch.PosMultiplier);
int y = (int)Math.Floor(((int)Math.Floor(pos.Y) - (int)ch.WorldPosition.Y * Chunk.CHUNK_SIZE) / (float)ch.PosMultiplier);
int z = (int)Math.Floor(((int)Math.Floor(pos.Z) - (int)ch.WorldPosition.Z * Chunk.CHUNK_SIZE) / (float)ch.PosMultiplier);
return ch.GetBlockAt(x, y, z);
}
public void Regen(Location pos, Chunk ch, int x = 1, int y = 1, int z = 1)
{
Chunk tch = ch;
bool zupd = false;
if (z == tch.CSize - 1 || TheClient.CVars.r_chunkoverrender.ValueB)
{
ch = GetChunk(ChunkLocFor(pos) + new Vector3i(0, 0, 1));
if (ch != null)
{
UpdateChunk(ch);
zupd = true;
}
}
if (!zupd)
{
UpdateChunk(tch);
}
if (x == 0 || TheClient.CVars.r_chunkoverrender.ValueB)
{
ch = GetChunk(ChunkLocFor(pos) + new Vector3i(-1, 0, 0));
if (ch != null)
{
UpdateChunk(ch);
}
}
if (y == 0 || TheClient.CVars.r_chunkoverrender.ValueB)
{
ch = GetChunk(ChunkLocFor(pos) + new Vector3i(0, -1, 0));
if (ch != null)
{
UpdateChunk(ch);
}
}
if (x == tch.CSize - 1 || TheClient.CVars.r_chunkoverrender.ValueB)
{
ch = GetChunk(ChunkLocFor(pos) + new Vector3i(1, 0, 0));
if (ch != null)
{
UpdateChunk(ch);
}
}
if (y == tch.CSize - 1 || TheClient.CVars.r_chunkoverrender.ValueB)
{
ch = GetChunk(ChunkLocFor(pos) + new Vector3i(0, 1, 0));
if (ch != null)
{
UpdateChunk(ch);
}
}
}
public void SetBlockMaterial(Location pos, ushort mat, byte dat = 0, byte paint = 0, bool regen = true)
{
Chunk ch = LoadChunk(ChunkLocFor(pos), 1);
int x = (int)Math.Floor(((int)Math.Floor(pos.X) - (int)ch.WorldPosition.X * Chunk.CHUNK_SIZE) / (float)ch.PosMultiplier);
int y = (int)Math.Floor(((int)Math.Floor(pos.Y) - (int)ch.WorldPosition.Y * Chunk.CHUNK_SIZE) / (float)ch.PosMultiplier);
int z = (int)Math.Floor(((int)Math.Floor(pos.Z) - (int)ch.WorldPosition.Z * Chunk.CHUNK_SIZE) / (float)ch.PosMultiplier);
ch.SetBlockAt(x, y, z, new BlockInternal(mat, dat, paint, 0));
ch.Edited = true;
if (regen)
{
Regen(pos, ch, x, y, z);
}
}
public void UpdateChunk(Chunk ch)
{
if (ch == null)
{
return;
}
TheClient.Schedule.ScheduleSyncTask(() =>
{
Chunk above = null;
for (int i = 1; i < 5 && above == null; i++) // TODO: 5 -> View height limit
{
above = GetChunk(ch.WorldPosition + new Vector3i(0, 0, i));
}
DoNotRenderYet(ch);
for (int i = 1; i > 5; i++) // TODO: 5 -> View height limit
{
Chunk below = GetChunk(ch.WorldPosition + new Vector3i(0, 0, -i));
if (below != null)
{
DoNotRenderYet(below);
}
else
{
break;
}
}
TheClient.Schedule.StartASyncTask(() =>
{
LightForChunks(ch, above);
});
});
}
public void LightForChunks(Chunk ch, Chunk above)
{
ch.CalcSkyLight(above);
TheClient.Schedule.ScheduleSyncTask(() =>
{
ch.AddToWorld();
if (!ch.CreateVBO())
{
return;
}
Chunk below = GetChunk(ch.WorldPosition + new Vector3i(0, 0, -1));
if (below != null)
{
TheClient.Schedule.StartASyncTask(() =>
{
LightForChunks(below, ch);
});
}
});
}
public Dictionary<Vector3i, Tuple<Matrix4d, Model, Model, Location, Texture>> AxisAlignedModels = new Dictionary<Vector3i, Tuple<Matrix4d, Model, Model, Location, Texture>>();
const double MAX_GRASS_DIST = 9; // TODO: CVar?
const double mgd_sq = MAX_GRASS_DIST * MAX_GRASS_DIST;
public void RenderPlants()
{
if (TheClient.CVars.r_plants.ValueB)
{
TheClient.SetEnts();
RenderGrass();
}
}
public void RenderGrass()
{
if (TheClient.MainWorldView.FBOid == FBOID.FORWARD_SOLID)
{
TheClient.s_forw_grass = TheClient.s_forw_grass.Bind();
}
else if (TheClient.MainWorldView.FBOid == FBOID.MAIN)
{
TheClient.s_fbo_grass = TheClient.s_fbo_grass.Bind();
}
else
{
return;
}
GL.ActiveTexture(TextureUnit.Texture3);
GL.BindTexture(TextureTarget.Texture2DArray, 0);
GL.ActiveTexture(TextureUnit.Texture2);
GL.BindTexture(TextureTarget.Texture2DArray, 0);
GL.ActiveTexture(TextureUnit.Texture1);
GL.BindTexture(TextureTarget.Texture2DArray, 0);
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2DArray, TheClient.GrassTextureID);
GL.UniformMatrix4(1, false, ref TheClient.MainWorldView.PrimaryMatrix);
GL.Uniform1(6, (float)GlobalTickTimeLocal);
GL.Uniform3(7, ClientUtilities.Convert(ActualWind));
TheClient.Rendering.SetColor(GetSunAdjust());
foreach (Chunk chunk in chToRender)
{
if (chunk.Plant_VAO != -1)
{
Matrix4d mat = Matrix4d.CreateTranslation(ClientUtilities.ConvertD(chunk.WorldPosition.ToLocation() * Chunk.CHUNK_SIZE));
TheClient.MainWorldView.SetMatrix(2, mat);
GL.BindVertexArray(chunk.Plant_VAO);
GL.DrawElements(PrimitiveType.Points, chunk.Plant_C, DrawElementsType.UnsignedInt, IntPtr.Zero);
}
}
TheClient.isVox = true;
TheClient.SetEnts();
}
public void RenderEffects()
{
GL.LineWidth(5);
TheClient.Rendering.SetColor(Color4.White);
for (int i = 0; i < Highlights.Length; i++)
{
TheClient.Rendering.RenderLineBox(Highlights[i].Min, Highlights[i].Max);
}
GL.LineWidth(1);
}
public OpenTK.Vector4 GetSunAdjust()
{
if (TheClient.CVars.r_fast.ValueB || !TheClient.CVars.r_lighting.ValueB)
{
return new OpenTK.Vector4(TheClient.TheSun.InternalLights[0].color
+ TheClient.ThePlanet.InternalLights[0].color
+ (TheClient.CVars.r_cloudshadows.ValueB ? TheClient.TheSunClouds.InternalLights[0].color : new OpenTK.Vector3(0, 0, 0))
+ ClientUtilities.Convert(GetAmbient()), 1.0f);
}
else
{
return new OpenTK.Vector4(1f, 1f, 1f, 1f);
}
}
public void Render()
{
TheClient.Rendering.SetColor(GetSunAdjust());
TheClient.Rendering.SetMinimumLight(0f);
if (TheClient.RenderTextures)
{
GL.BindTexture(TextureTarget.Texture2D, 0);
GL.BindTexture(TextureTarget.Texture2DArray, TheClient.TBlock.TextureID);
GL.ActiveTexture(TextureUnit.Texture2);
GL.BindTexture(TextureTarget.Texture2DArray, TheClient.TBlock.NormalTextureID);
GL.ActiveTexture(TextureUnit.Texture1);
GL.BindTexture(TextureTarget.Texture2DArray, TheClient.TBlock.HelpTextureID);
GL.ActiveTexture(TextureUnit.Texture0);
}
/*foreach (Chunk chunk in LoadedChunks.Values)
{
if (TheClient.CFrust == null || TheClient.CFrust.ContainsBox(chunk.WorldPosition.ToLocation() * Chunk.CHUNK_SIZE,
chunk.WorldPosition.ToLocation() * Chunk.CHUNK_SIZE + new Location(Chunk.CHUNK_SIZE)))
{
chunk.Render();
}
}*/
if (TheClient.MainWorldView.FBOid == FBOID.MAIN || TheClient.MainWorldView.FBOid == FBOID.NONE || TheClient.MainWorldView.FBOid == FBOID.FORWARD_SOLID)
{
chToRender.Clear();
if (TheClient.CVars.r_chunkmarch.ValueB)
{
ChunkMarchAndDraw();
}
else
{
foreach (Chunk ch in LoadedChunks.Values)
{
BEPUutilities.Vector3 min = ch.WorldPosition.ToVector3() * Chunk.CHUNK_SIZE;
if (TheClient.MainWorldView.CFrust == null || TheClient.MainWorldView.CFrust.ContainsBox(min, min + new BEPUutilities.Vector3(Chunk.CHUNK_SIZE, Chunk.CHUNK_SIZE, Chunk.CHUNK_SIZE)))
{
ch.Render();
chToRender.Add(ch);
}
}
}
}
else if (TheClient.MainWorldView.FBOid == FBOID.SHADOWS)
{
foreach (Chunk ch in LoadedChunks.Values)
{
BEPUutilities.Vector3 min = ch.WorldPosition.ToVector3() * Chunk.CHUNK_SIZE;
if (TheClient.MainWorldView.CFrust == null || TheClient.MainWorldView.CFrust.ContainsBox(min, min + new BEPUutilities.Vector3(Chunk.CHUNK_SIZE, Chunk.CHUNK_SIZE, Chunk.CHUNK_SIZE)))
{
ch.Render();
}
}
}
else
{
foreach (Chunk ch in chToRender)
{
ch.Render();
}
}
if (TheClient.RenderTextures)
{
GL.BindTexture(TextureTarget.Texture2D, 0);
GL.BindTexture(TextureTarget.Texture2DArray, 0);
GL.ActiveTexture(TextureUnit.Texture2);
GL.BindTexture(TextureTarget.Texture2DArray, 0);
GL.ActiveTexture(TextureUnit.Texture1);
GL.BindTexture(TextureTarget.Texture2DArray, 0);
GL.ActiveTexture(TextureUnit.Texture0);
}
}
public List<Chunk> chToRender = new List<Chunk>();
static Vector3i[] MoveDirs = new Vector3i[] { new Vector3i(-1, 0, 0), new Vector3i(1, 0, 0),
new Vector3i(0, -1, 0), new Vector3i(0, 1, 0), new Vector3i(0, 0, -1), new Vector3i(0, 0, 1) };
public int MaxRenderDistanceChunks = 10;
public void ChunkMarchAndDraw()
{
Vector3i start = ChunkLocFor(TheClient.MainWorldView.CameraPos);
HashSet<Vector3i> seen = new HashSet<Vector3i>();
Queue<Vector3i> toSee = new Queue<Vector3i>();
HashSet<Vector3i> toSeeSet = new HashSet<Vector3i>();
toSee.Enqueue(start);
toSeeSet.Add(start);
while (toSee.Count > 0)
{
Vector3i cur = toSee.Dequeue();
toSeeSet.Remove(cur);
if ((Math.Abs(cur.X - start.X) > MaxRenderDistanceChunks)
|| (Math.Abs(cur.Y - start.Y) > MaxRenderDistanceChunks)
|| (Math.Abs(cur.Z - start.Z) > MaxRenderDistanceChunks))
{
continue;
}
seen.Add(cur);
Chunk chcur = GetChunk(cur);
if (chcur != null)
{
chcur.Render();
chToRender.Add(chcur);
}
for (int i = 0; i < MoveDirs.Length; i++)
{
Vector3i t = cur + MoveDirs[i];
if (!seen.Contains(t) && !toSeeSet.Contains(t))
{
for (int j = 0; j < MoveDirs.Length; j++)
{
if (BEPUutilities.Vector3.Dot(MoveDirs[j].ToVector3(), (TheClient.MainWorldView.CameraTarget - TheClient.MainWorldView.CameraPos).ToBVector()) < -0.8f) // TODO: what is this? Is it needed?
{
continue;
}
Vector3i nt = cur + MoveDirs[j];
if (!seen.Contains(nt) && !toSeeSet.Contains(nt))
{
BEPUutilities.Vector3 min = nt.ToVector3() * Chunk.CHUNK_SIZE;
if (TheClient.MainWorldView.CFrust == null || TheClient.MainWorldView.CFrust.ContainsBox(min, min + new BEPUutilities.Vector3(Chunk.CHUNK_SIZE, Chunk.CHUNK_SIZE, Chunk.CHUNK_SIZE)))
{
toSee.Enqueue(nt);
toSeeSet.Add(nt);
}
else
{
seen.Add(nt);
}
}
}
}
}
}
}
public List<InternalBaseJoint> Joints = new List<InternalBaseJoint>();
public void AddJoint(InternalBaseJoint joint)
{
Joints.Add(joint);
joint.One.Joints.Add(joint);
joint.Two.Joints.Add(joint);
joint.Enable();
if (joint is BaseJoint)
{
BaseJoint pjoint = (BaseJoint)joint;
pjoint.CurrentJoint = pjoint.GetBaseJoint();
PhysicsWorld.Add(pjoint.CurrentJoint);
}
}
public void DestroyJoint(InternalBaseJoint joint)
{
if (!Joints.Remove(joint))
{
SysConsole.Output(OutputType.WARNING, "Destroyed non-existent joint?!");
}
joint.One.Joints.Remove(joint);
joint.Two.Joints.Remove(joint);
joint.Disable();
if (joint is BaseJoint)
{
BaseJoint pjoint = (BaseJoint)joint;
PhysicsWorld.Remove(pjoint.CurrentJoint);
}
}
public double GlobalTickTimeLocal = 0;
public void ForgetChunk(Vector3i cpos)
{
Chunk ch;
if (LoadedChunks.TryGetValue(cpos, out ch))
{
ch.Destroy();
LoadedChunks.Remove(cpos);
}
}
public bool InWater(Location min, Location max)
{
// TODO: Efficiency!
min = min.GetBlockLocation();
max = max.GetUpperBlockBorder();
for (int x = (int)min.X; x < max.X; x++)
{
for (int y = (int)min.Y; y < max.Y; y++)
{
for (int z = (int)min.Z; z < max.Z; z++)
{
if (GetBlockMaterial(min + new Location(x, y, z)).GetSolidity() == MaterialSolidity.LIQUID)
{
return true;
}
}
}
}
return false;
}
public float GetSkyLightBase(Location pos)
{
pos.Z = pos.Z + 1;
int XP = (int)Math.Floor(pos.X / Chunk.CHUNK_SIZE);
int YP = (int)Math.Floor(pos.Y / Chunk.CHUNK_SIZE);
int ZP = (int)Math.Floor(pos.Z / Chunk.CHUNK_SIZE);
Chunk cht = GetChunk(new Vector3i(XP, YP, ZP));
if (cht != null)
{
int x = (int)(Math.Floor(pos.X) - (XP * Chunk.CHUNK_SIZE));
int y = (int)(Math.Floor(pos.Y) - (YP * Chunk.CHUNK_SIZE));
int z = (int)(Math.Floor(pos.Z) - (ZP * Chunk.CHUNK_SIZE));
return cht.GetBlockAtLOD(x, y, z).BlockLocalData / 255f;
}
else
{
return 1f;
}
}
public Location GetSkyLight(Location pos, Location norm)
{
if (norm.Z < -0.99)
{
return Location.Zero;
}
return SkyMod(pos, norm, GetSkyLightBase(pos));
}
Location SkyMod(Location pos, Location norm, float light)
{
if (light > 0 && TheClient.CVars.r_treeshadows.ValueB)
{
BoundingBox bb = new BoundingBox(pos.ToBVector(), (pos + new Location(1, 1, 300)).ToBVector());
if (GenShadowCasters != null)
{
for (int i = 0; i < GenShadowCasters.Length; i++) // TODO: Accelerate somehow! This is too slow!
{
PhysicsEntity pe = GenShadowCasters[i];
if (pe.GenBlockShadows && pe.ShadowCenter.DistanceSquared_Flat(pos) < pe.ShadowRadiusSquaredXY)
{
light -= 0.05f;
if (pe.ShadowMainDupe.Intersects(bb))
{
light = 0;
break;
}
if (pe.ShadowCastShape.Intersects(bb))
{
light -= 0.1f;
}
if (light <= 0)
{
light = 0;
break;
}
}
}
}
}
return Math.Max(norm.Dot(SunLightPathNegative), 0.5) * new Location(light) * SkyLightMod;
}
static Location SunLightPathNegative = new Location(0, 0, 1);
const float SkyLightMod = 0.75f;
public Location GetAmbient()
{
return TheClient.BaseAmbient;
}
public OpenTK.Vector4 Regularize(OpenTK.Vector4 col)
{
if (col.X < 1.0 && col.Y < 1.0 && col.Z < 1.0)
{
return col;
}
return new OpenTK.Vector4(col.Xyz / Math.Max(col.X, Math.Max(col.Y, col.Z)), col.W);
}
public OpenTK.Vector4 RegularizeBig(OpenTK.Vector4 col, float cap)
{
if (col.X < cap && col.Y < cap && col.Z < cap)
{
return col;
}
return new OpenTK.Vector4((col.Xyz / Math.Max(col.X, Math.Max(col.Y, col.Z))) * cap, col.W);
}
public Location Regularize(Location col)
{
if (col.X < 1.0 && col.Y < 1.0 && col.Z < 1.0)
{
return col;
}
return col / Math.Max(col.X, Math.Max(col.Y, col.Z));
}
public Location RegularizeBig(Location col, float cap)
{
if (col.X < cap && col.Y < cap && col.Z < cap)
{
return col;
}
return (col / Math.Max(col.X, Math.Max(col.Y, col.Z))) * cap;
}
public Location GetBlockLight(Location pos, Location norm, List<Chunk> potentials)
{
Location lit = Location.Zero;
foreach (Chunk ch in potentials)
{
foreach (KeyValuePair<Vector3i, Material> pot in ch.Lits)
{
double distsq = (pot.Key.ToLocation() + ch.WorldPosition.ToLocation() * Chunk.CHUNK_SIZE).DistanceSquared(pos);
double range = pot.Value.GetLightEmitRange();
// TODO: Apply normal vector stuff?
if (distsq < range * range)
{
lit += pot.Value.GetLightEmit() * (range - Math.Sqrt(distsq)); // TODO: maybe apply normals?
}
}
}
return lit;
}
public Location GetLightAmountForSkyValue(Location pos, Location norm, List<Chunk> potentials, float skyPrecalc)
{
if (potentials == null)
{
SysConsole.Output(OutputType.WARNING, "Region - GetLightAmountForSkyValue : null potentials! Correcting...");
potentials = new List<Chunk>();
Vector3i pos_c = ChunkLocFor(pos);
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
for (int z = -1; z <= 1; z++)
{
Chunk tch = GetChunk(pos_c + new Vector3i(x, y, z));
if (tch != null)
{
potentials.Add(tch);
}
}
}
}
}
Location amb = GetAmbient();
Location sky = SkyMod(pos, norm, skyPrecalc);
Location blk = GetBlockLight(pos, norm, potentials);
Location res;
Location.AddThree(ref amb, ref sky, ref blk, out res);
return res;
}
public OpenTK.Vector4 GetLightAmountAdjusted(Location pos, Location norm)
{
OpenTK.Vector4 vec = new OpenTK.Vector4(ClientUtilities.Convert(GetLightAmount(pos, norm, null)), 1.0f) * GetSunAdjust();
if (TheClient.CVars.r_fast.ValueB)
{
return Regularize(vec);
}
return RegularizeBig(vec, 5f);
}
public Location GetLightAmount(Location pos, Location norm, List<Chunk> potentials)
{
if (potentials == null)
{
potentials = new List<Chunk>();
Vector3i pos_c = ChunkLocFor(pos);
for (int x = -1; x <= 1; x++)
{
for (int y = -1; y <= 1; y++)
{
for (int z = -1; z <= 1; z++)
{
Chunk tch = GetChunk(pos_c + new Vector3i(x, y, z));
if (tch != null)
{
potentials.Add(tch);
}
}
}
}
}
Location amb = GetAmbient();
Location sky = GetSkyLight(pos, norm);
Location blk = GetBlockLight(pos, norm, potentials);
if (TheClient.CVars.r_fast.ValueB)
{
blk = Regularize(blk);
}
else
{
blk = RegularizeBig(blk, 5);
}
return amb + sky + blk;
}
public SimplePriorityQueue<Action> PrepChunks = new SimplePriorityQueue<Action>();
public SimplePriorityQueue<Vector3i> NeedsRendering = new SimplePriorityQueue<Vector3i>();
public HashSet<Vector3i> RenderingNow = new HashSet<Vector3i>();
public HashSet<Vector3i> PreppingNow = new HashSet<Vector3i>();
public void CheckForRenderNeed()
{
lock (RenderingNow)
{
while (NeedsRendering.Count > 0 && RenderingNow.Count < TheClient.CVars.r_chunksatonce.ValueI)
{
Vector3i temp = NeedsRendering.Dequeue();
Chunk ch = GetChunk(temp);
if (ch != null)
{
ch.MakeVBONow();
RenderingNow.Add(temp);
}
}
}
lock (PreppingNow)
{
while (PrepChunks.Count > 0 && PreppingNow.Count < TheClient.CVars.r_chunksatonce.ValueI)
{
Action temp = PrepChunks.Dequeue();
temp.Invoke();
}
}
}
public void DoneRendering(Chunk ch)
{
lock (RenderingNow)
{
RenderingNow.Remove(ch.WorldPosition);
}
}
/// <summary>
/// Do not call directly, use Chunk.CreateVBO().
/// </summary>
/// <param name="ch"></param>
public bool NeedToRender(Chunk ch)
{
lock (RenderingNow)
{
if (!NeedsRendering.Contains(ch.WorldPosition))
{
NeedsRendering.Enqueue(ch.WorldPosition, (ch.WorldPosition.ToLocation() * Chunk.CHUNK_SIZE).DistanceSquared(TheClient.Player.GetPosition()));
return true;
}
return false;
}
}
public void DoNotRenderYet(Chunk ch)
{
lock (RenderingNow)
{
while (NeedsRendering.Contains(ch.WorldPosition))
{
NeedsRendering.Remove(ch.WorldPosition);
}
}
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using MSAst = System.Linq.Expressions;
#else
using MSAst = Microsoft.Scripting.Ast;
#endif
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Utils;
using Microsoft.Scripting.Interpreter;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Compiler.Ast {
public class CallExpression : Expression, IInstructionProvider {
private readonly Expression _target;
private readonly Arg[] _args;
public CallExpression(Expression target, Arg[] args) {
_target = target;
_args = args;
}
public Expression Target {
get { return _target; }
}
public IList<Arg> Args {
get { return _args; }
}
public bool NeedsLocalsDictionary() {
NameExpression nameExpr = _target as NameExpression;
if (nameExpr == null) return false;
if (_args.Length == 0) {
if (nameExpr.Name == "locals") return true;
if (nameExpr.Name == "vars") return true;
if (nameExpr.Name == "dir") return true;
return false;
} else if (_args.Length == 1 && (nameExpr.Name == "dir" || nameExpr.Name == "vars")) {
if (_args[0].Name == "*" || _args[0].Name == "**") {
// could be splatting empty list or dict resulting in 0-param call which needs context
return true;
}
} else if (_args.Length == 2 && (nameExpr.Name == "dir" || nameExpr.Name == "vars")) {
if (_args[0].Name == "*" && _args[1].Name == "**") {
// could be splatting empty list and dict resulting in 0-param call which needs context
return true;
}
} else {
if (nameExpr.Name == "eval") return true;
if (nameExpr.Name == "execfile") return true;
}
return false;
}
public override MSAst.Expression Reduce() {
MSAst.Expression[] values = new MSAst.Expression[_args.Length + 2];
Argument[] kinds = new Argument[_args.Length];
values[0] = Parent.LocalContext;
values[1] = _target;
for (int i = 0; i < _args.Length; i++) {
kinds[i] = _args[i].GetArgumentInfo();
values[i + 2] = _args[i].Expression;
}
return Parent.Invoke(
new CallSignature(kinds),
values
);
}
#region IInstructionProvider Members
void IInstructionProvider.AddInstructions(LightCompiler compiler) {
for (int i = 0; i < _args.Length; i++) {
if (!_args[i].GetArgumentInfo().IsSimple) {
compiler.Compile(Reduce());
return;
}
}
switch (_args.Length) {
#region Generated Python Call Expression Instruction Switch
// *** BEGIN GENERATED CODE ***
// generated by function: gen_call_expression_instruction_switch from: generate_calls.py
case 0:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Instructions.Emit(new Invoke0Instruction(Parent.PyContext));
return;
case 1:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Compile(_args[0].Expression);
compiler.Instructions.Emit(new Invoke1Instruction(Parent.PyContext));
return;
case 2:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Compile(_args[0].Expression);
compiler.Compile(_args[1].Expression);
compiler.Instructions.Emit(new Invoke2Instruction(Parent.PyContext));
return;
case 3:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Compile(_args[0].Expression);
compiler.Compile(_args[1].Expression);
compiler.Compile(_args[2].Expression);
compiler.Instructions.Emit(new Invoke3Instruction(Parent.PyContext));
return;
case 4:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Compile(_args[0].Expression);
compiler.Compile(_args[1].Expression);
compiler.Compile(_args[2].Expression);
compiler.Compile(_args[3].Expression);
compiler.Instructions.Emit(new Invoke4Instruction(Parent.PyContext));
return;
case 5:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Compile(_args[0].Expression);
compiler.Compile(_args[1].Expression);
compiler.Compile(_args[2].Expression);
compiler.Compile(_args[3].Expression);
compiler.Compile(_args[4].Expression);
compiler.Instructions.Emit(new Invoke5Instruction(Parent.PyContext));
return;
case 6:
compiler.Compile(Parent.LocalContext);
compiler.Compile(_target);
compiler.Compile(_args[0].Expression);
compiler.Compile(_args[1].Expression);
compiler.Compile(_args[2].Expression);
compiler.Compile(_args[3].Expression);
compiler.Compile(_args[4].Expression);
compiler.Compile(_args[5].Expression);
compiler.Instructions.Emit(new Invoke6Instruction(Parent.PyContext));
return;
// *** END GENERATED CODE ***
#endregion
}
compiler.Compile(Reduce());
}
#endregion
abstract class InvokeInstruction : Instruction {
public override int ProducedStack {
get {
return 1;
}
}
public override string InstructionName {
get {
return "Python Invoke" + (ConsumedStack - 1);
}
}
}
#region Generated Python Call Expression Instructions
// *** BEGIN GENERATED CODE ***
// generated by function: gen_call_expression_instructions from: generate_calls.py
class Invoke0Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object>> _site;
public Invoke0Instruction(PythonContext context) {
_site = context.CallSite0;
}
public override int ConsumedStack {
get {
return 2;
}
}
public override int Run(InterpretedFrame frame) {
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target));
return +1;
}
}
class Invoke1Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object>> _site;
public Invoke1Instruction(PythonContext context) {
_site = context.CallSite1;
}
public override int ConsumedStack {
get {
return 3;
}
}
public override int Run(InterpretedFrame frame) {
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0));
return +1;
}
}
class Invoke2Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object>> _site;
public Invoke2Instruction(PythonContext context) {
_site = context.CallSite2;
}
public override int ConsumedStack {
get {
return 4;
}
}
public override int Run(InterpretedFrame frame) {
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1));
return +1;
}
}
class Invoke3Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object>> _site;
public Invoke3Instruction(PythonContext context) {
_site = context.CallSite3;
}
public override int ConsumedStack {
get {
return 5;
}
}
public override int Run(InterpretedFrame frame) {
var arg2 = frame.Pop();
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2));
return +1;
}
}
class Invoke4Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object>> _site;
public Invoke4Instruction(PythonContext context) {
_site = context.CallSite4;
}
public override int ConsumedStack {
get {
return 6;
}
}
public override int Run(InterpretedFrame frame) {
var arg3 = frame.Pop();
var arg2 = frame.Pop();
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2, arg3));
return +1;
}
}
class Invoke5Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object, object>> _site;
public Invoke5Instruction(PythonContext context) {
_site = context.CallSite5;
}
public override int ConsumedStack {
get {
return 7;
}
}
public override int Run(InterpretedFrame frame) {
var arg4 = frame.Pop();
var arg3 = frame.Pop();
var arg2 = frame.Pop();
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2, arg3, arg4));
return +1;
}
}
class Invoke6Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object, object, object>> _site;
public Invoke6Instruction(PythonContext context) {
_site = context.CallSite6;
}
public override int ConsumedStack {
get {
return 8;
}
}
public override int Run(InterpretedFrame frame) {
var arg5 = frame.Pop();
var arg4 = frame.Pop();
var arg3 = frame.Pop();
var arg2 = frame.Pop();
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2, arg3, arg4, arg5));
return +1;
}
}
// *** END GENERATED CODE ***
#endregion
internal override string CheckAssign() {
return "can't assign to function call";
}
internal override string CheckDelete() {
return "can't delete function call";
}
public override void Walk(PythonWalker walker) {
if (walker.Walk(this)) {
if (_target != null) {
_target.Walk(walker);
}
if (_args != null) {
foreach (Arg arg in _args) {
arg.Walk(walker);
}
}
}
walker.PostWalk(this);
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Text;
using Mono.Collections.Generic;
namespace Mono.Cecil {
// HACK - Reflexil - Partial for legacy classes
public partial class MethodReference : MemberReference, IMethodSignature, IGenericParameterProvider, IGenericContext
{
internal ParameterDefinitionCollection parameters;
MethodReturnType return_type;
bool has_this;
bool explicit_this;
MethodCallingConvention calling_convention;
internal Collection<GenericParameter> generic_parameters;
public virtual bool HasThis {
get { return has_this; }
set { has_this = value; }
}
public virtual bool ExplicitThis {
get { return explicit_this; }
set { explicit_this = value; }
}
public virtual MethodCallingConvention CallingConvention {
get { return calling_convention; }
set { calling_convention = value; }
}
public virtual bool HasParameters {
get { return !parameters.IsNullOrEmpty (); }
}
public virtual Collection<ParameterDefinition> Parameters {
get {
if (parameters == null)
parameters = new ParameterDefinitionCollection (this);
return parameters;
}
}
IGenericParameterProvider IGenericContext.Type {
get {
var declaring_type = this.DeclaringType;
var instance = declaring_type as GenericInstanceType;
if (instance != null)
return instance.ElementType;
return declaring_type;
}
}
IGenericParameterProvider IGenericContext.Method {
get { return this; }
}
GenericParameterType IGenericParameterProvider.GenericParameterType {
get { return GenericParameterType.Method; }
}
public virtual bool HasGenericParameters {
get { return !generic_parameters.IsNullOrEmpty (); }
}
public virtual Collection<GenericParameter> GenericParameters {
get {
if (generic_parameters != null)
return generic_parameters;
return generic_parameters = new GenericParameterCollection (this);
}
}
public TypeReference ReturnType {
get {
var return_type = MethodReturnType;
return return_type != null ? return_type.ReturnType : null;
}
set {
var return_type = MethodReturnType;
if (return_type != null)
return_type.ReturnType = value;
}
}
public virtual MethodReturnType MethodReturnType {
get { return return_type; }
set { return_type = value; }
}
public override string FullName {
get {
var builder = new StringBuilder ();
builder.Append (ReturnType.FullName)
.Append (" ")
.Append (MemberFullName ());
this.MethodSignatureFullName (builder);
return builder.ToString ();
}
}
public virtual bool IsGenericInstance {
get { return false; }
}
public override bool ContainsGenericParameter {
get {
if (this.ReturnType.ContainsGenericParameter || base.ContainsGenericParameter)
return true;
if (!HasParameters)
return false;
var parameters = this.Parameters;
for (int i = 0; i < parameters.Count; i++)
if (parameters [i].ParameterType.ContainsGenericParameter)
return true;
return false;
}
}
internal MethodReference ()
{
this.return_type = new MethodReturnType (this);
this.token = new MetadataToken (TokenType.MemberRef);
}
public MethodReference (string name, TypeReference returnType)
: base (name)
{
Mixin.CheckType (returnType, Mixin.Argument.returnType);
this.return_type = new MethodReturnType (this);
this.return_type.ReturnType = returnType;
this.token = new MetadataToken (TokenType.MemberRef);
}
public MethodReference (string name, TypeReference returnType, TypeReference declaringType)
: this (name, returnType)
{
Mixin.CheckType (declaringType, Mixin.Argument.declaringType);
this.DeclaringType = declaringType;
}
public virtual MethodReference GetElementMethod ()
{
return this;
}
protected override IMemberDefinition ResolveDefinition ()
{
return this.Resolve ();
}
public new virtual MethodDefinition Resolve ()
{
var module = this.Module;
if (module == null)
throw new NotSupportedException ();
return module.Resolve (this);
}
}
static partial class Mixin {
public static bool IsVarArg (this IMethodSignature self)
{
return (self.CallingConvention & MethodCallingConvention.VarArg) != 0;
}
public static int GetSentinelPosition (this IMethodSignature self)
{
if (!self.HasParameters)
return -1;
var parameters = self.Parameters;
for (int i = 0; i < parameters.Count; i++)
if (parameters [i].ParameterType.IsSentinel)
return i;
return -1;
}
}
}
| |
// MIT License
//
// Copyright (c) 2017 Maarten van Sambeek.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
namespace ConnectQl.Results
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using ConnectQl.ExtensionMethods;
using ConnectQl.Interfaces;
using JetBrains.Annotations;
/// <summary>
/// The row.
/// </summary>
public abstract class Row : Row.IRowImplementation
{
/// <summary>
/// The <see cref="Create{T}"/> method.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private static readonly MethodInfo RowCreateMethod = typeof(Row).GetGenericMethod(nameof(Row.Create), typeof(IRowFieldResolver), null, typeof(IEnumerable<KeyValuePair<string, object>>));
/// <summary>
/// The values.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly object[] values;
/// <summary>
/// Initializes a new instance of the <see cref="Row"/> class.
/// </summary>
/// <param name="resolver">
/// The resolver.
/// </param>
/// <param name="values">
/// The values.
/// </param>
private Row(IRowFieldResolver resolver, object[] values)
{
this.Resolver = resolver;
this.values = values;
}
/// <summary>
/// Initializes a new instance of the <see cref="Row"/> class.
/// </summary>
/// <param name="resolver">
/// The resolver.
/// </param>
private Row(IRowFieldResolver resolver)
: this(resolver, new object[0])
{
}
/// <summary>
/// The row implementation.
/// </summary>
protected interface IRowImplementation
{
/// <summary>
/// Joins the other row to the current row.
/// </summary>
/// <typeparam name="TOther">
/// The type of the other row's unique id.
/// </typeparam>
/// <param name="rowBuilder">
/// The row Builder.
/// </param>
/// <param name="other">
/// The other row.
/// </param>
/// <returns>
/// The joined row, or null when the rows cannot be joined.
/// </returns>
Row CombineFrom<TOther>(IRowBuilder rowBuilder, RowImplementation<TOther> other);
}
/// <summary>
/// Gets the column names.
/// </summary>
public IReadOnlyList<string> ColumnNames => this.Resolver.Fields;
/// <summary>
/// Gets the unique id of the row.
/// </summary>
public abstract object UniqueId { get; }
/// <summary>
/// Gets the field resolver.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
internal IRowFieldResolver Resolver { get; }
/// <summary>
/// Gets the values for debugging purposes.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
protected IDictionary<string, object> Values => this.ToDictionary();
/// <summary>
/// Gets or sets the values for the specified field name.
/// </summary>
/// <param name="field">
/// The field name.
/// </param>
/// <returns>
/// The value for the field, or null if the field is not in the row.
/// </returns>
[CanBeNull]
public object this[string field]
{
get
{
var index = this.Resolver.GetIndex(field);
return index == null || index.Value >= this.values.Length ? null : this.values[index.Value];
}
}
/// <summary>
/// Converts the row to a dictionary.
/// </summary>
/// <returns>
/// A dictionary containing all fields and their values.
/// </returns>
[NotNull]
public IDictionary<string, object> ToDictionary()
{
return this.ColumnNames.ToDictionary(cn => cn, cn => this[cn], StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Joins the other row to the current row.
/// </summary>
/// <typeparam name="TOther">
/// The type of the other row's unique id.
/// </typeparam>
/// <param name="rowBuilder">
/// The row Builder.
/// </param>
/// <param name="other">
/// The other row.
/// </param>
/// <returns>
/// The joined row, or null when the rows cannot be joined.
/// </returns>
Row IRowImplementation.CombineFrom<TOther>(IRowBuilder rowBuilder, RowImplementation<TOther> other)
{
return this.CombineFrom(rowBuilder, other);
}
/// <summary>
/// Creates a row.
/// </summary>
/// <typeparam name="T">
/// The type of the unique identifier.
/// </typeparam>
/// <param name="fieldResolver">
/// The data Set.
/// </param>
/// <param name="uniqueId">
/// The unique identifier.
/// </param>
/// <param name="values">
/// The values.
/// </param>
/// <returns>
/// The row.
/// </returns>
internal static Row Create<T>(IRowFieldResolver fieldResolver, T uniqueId, IEnumerable<KeyValuePair<string, object>> values)
{
if (typeof(T) == typeof(object) && uniqueId.GetType() != typeof(object))
{
var parameters = new object[]
{
fieldResolver,
uniqueId,
values,
};
return (Row)Row.RowCreateMethod.MakeGenericMethod(uniqueId.GetType()).Invoke(null, parameters);
}
var rowValues = fieldResolver.GetIndices(values);
object[] objects;
if (rowValues.Count > 0)
{
objects = new object[rowValues[0].Item1 + 1];
foreach (var rowValue in rowValues)
{
objects[rowValue.Item1] = rowValue.Item2;
}
}
else
{
objects = new object[0];
}
return new RowImplementation<T>(fieldResolver, uniqueId, objects);
}
/// <summary>
/// Clones the row in the specified row builder.
/// </summary>
/// <param name="rowBuilder">
/// The builder to clone the row into.
/// </param>
/// <returns>
/// The cloned row.
/// </returns>
internal abstract Row Clone(IRowBuilder rowBuilder);
/// <summary>
/// Joins the row with this row and returns the result as new row.
/// </summary>
/// <param name="set">
/// The set.
/// </param>
/// <param name="row">
/// The row to join this row with.
/// </param>
/// <returns>
/// A new <see cref="Row"/> containing fields for both the left row and the right row, or null if he join was an inner
/// join
/// and <paramref name="row"/> was null.
/// </returns>
internal abstract Row CombineWith(IRowBuilder set, Row row);
/// <summary>
/// Gets the value for the specified field name.
/// </summary>
/// <param name="name">
/// The name of the field to get the value for.
/// </param>
/// <typeparam name="T">
/// The type of the value to get.
/// </typeparam>
/// <returns>
/// The value or <c>default(T)</c> if a field is not in the row.
/// </returns>
internal T Get<T>(string name)
{
return this.GetByIndex<T>(this.Resolver.GetIndex(name));
}
/// <summary>
/// Gets the value for the specified field's internal name.
/// </summary>
/// <param name="internalName">
/// The internal name of the field to get the value for.
/// </param>
/// <typeparam name="T">
/// The type of the value to get.
/// </typeparam>
/// <returns>
/// The value or <c>default(T)</c> if a field is not in the row.
/// </returns>
internal T GetByInternalName<T>(string internalName)
{
return this.GetByIndex<T>(this.Resolver.GetInternalNameIndex(internalName));
}
/// <summary>
/// When implemented in a derived class, joins the other row to the current row.
/// </summary>
/// <typeparam name="TOther">
/// The type of the other row's unique id.
/// </typeparam>
/// <param name="rowBuilder">
/// The row Builder.
/// </param>
/// <param name="other">
/// The other row.
/// </param>
/// <returns>
/// The joined row, or null when the rows cannot be joined.
/// </returns>
protected abstract Row CombineFrom<TOther>(IRowBuilder rowBuilder, RowImplementation<TOther> other);
/// <summary>
/// Gets a value by index.
/// </summary>
/// <param name="index">
/// The index.
/// </param>
/// <typeparam name="T">
/// The type of the value.
/// </typeparam>
/// <returns>
/// The <typeparamref name="T"/>.
/// </returns>
private T GetByIndex<T>(int? index)
{
var value = index == null || index.Value >= this.values.Length ? null : this.values[index.Value];
if (value == null || value is Error)
{
return default(T);
}
if (typeof(T) == typeof(object))
{
return (T)value;
}
try
{
return typeof(T).IsConstructedGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>)
? (T)Convert.ChangeType(value, typeof(T).GenericTypeArguments[0])
: (T)Convert.ChangeType(value, typeof(T));
}
catch
{
// Do nothing.
}
try
{
return (T)value;
}
catch
{
// Do nothing.
}
return default(T);
}
/// <summary>
/// The row implementation.
/// </summary>
/// <typeparam name="T">
/// The type of the unique id.
/// </typeparam>
[DebuggerDisplay("{" + nameof(RowImplementation<T>.ValuesAsString) + ",nq}")]
protected class RowImplementation<T> : Row
{
/// <summary>
/// Initializes a new instance of the <see cref="Row.RowImplementation{T}"/> class.
/// </summary>
/// <param name="resolver">
/// The field resolver.
/// </param>
/// <param name="id">
/// The unique id.
/// </param>
/// <param name="values">
/// The values.
/// </param>
internal RowImplementation(IRowFieldResolver resolver, T id, object[] values)
: base(resolver, values)
{
this.Id = id;
}
/// <summary>
/// Gets the unique id for the row.
/// </summary>
public override object UniqueId => this.Id;
/// <summary>
/// Gets the unique id.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Id { get; }
/// <summary>
/// Gets the string representation of the values.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string ValuesAsString => string.Join(", ", this.ToDictionary().Select(v => v.Key + ": " + (v.Value is string ? $"'{v.Value}'" : v.Value ?? "NULL")));
/// <summary>
/// The to string.
/// </summary>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public override string ToString() => this.ValuesAsString;
/// <summary>
/// Clones the row in the specified row builder.
/// </summary>
/// <param name="rowBuilder">
/// The builder to clone the row into.
/// </param>
/// <returns>
/// The cloned row.
/// </returns>
internal override Row Clone([NotNull] IRowBuilder rowBuilder)
{
return rowBuilder.CreateRow(this.Id, this.ToDictionary());
}
/// <summary>
/// Joins the current row with the other row.
/// </summary>
/// <param name="rowBuilder">
/// The row Builder.
/// </param>
/// <param name="row">
/// The row to join.
/// </param>
/// <returns>
/// The joined row, or null if <paramref name="row"/> is null and this is an inner join.
/// </returns>
internal override Row CombineWith(IRowBuilder rowBuilder, Row row)
{
return ((IRowImplementation)row).CombineFrom(rowBuilder, this);
}
/// <summary>
/// Joins the other row to the current row.
/// </summary>
/// <typeparam name="TOther">
/// The type of the other row's unique id.
/// </typeparam>
/// <param name="builder">
/// The builder.
/// </param>
/// <param name="other">
/// The other row.
/// </param>
/// <returns>
/// The joined row, or null when the rows cannot be joined.
/// </returns>
protected override Row CombineFrom<TOther>(IRowBuilder builder, RowImplementation<TOther> other)
{
return IdCombiner<T, TOther>.Combine(builder, this, other);
}
/// <summary>
/// The id combiner.
/// </summary>
/// <typeparam name="TFirst">
/// The type of the first unique id.
/// </typeparam>
/// <typeparam name="TSecond">
/// The type of the second unique id.
/// </typeparam>
private static class IdCombiner<TFirst, TSecond>
{
/// <summary>
/// The combine.
/// </summary>
public static readonly Func<IRowBuilder, RowImplementation<TFirst>, RowImplementation<TSecond>, Row> Combine = RowImplementation<T>.IdCombiner<TFirst, TSecond>.CreateCombine();
/// <summary>
/// Creates the function that combines two rows into the new <see cref="IRowBuilder"/> for the combination of types.
/// </summary>
/// <returns>
/// The combine function.
/// </returns>
private static Func<IRowBuilder, RowImplementation<TFirst>, RowImplementation<TSecond>, Row> CreateCombine()
{
var rowBuilder = Expression.Parameter(typeof(IRowBuilder), "rowBuilder");
var first = Expression.Parameter(typeof(RowImplementation<TFirst>), "first");
var second = Expression.Parameter(typeof(RowImplementation<TSecond>), "second");
var firstId = Expression.Property(first, typeof(RowImplementation<TFirst>).GetRuntimeProperty(nameof(RowImplementation<object>.Id)).GetMethod);
var secondId = Expression.Property(second, typeof(RowImplementation<TSecond>).GetRuntimeProperty(nameof(RowImplementation<object>.Id)).GetMethod);
var tuple = RowImplementation<T>.IdCombiner<TFirst, TSecond>.NewTuple(RowImplementation<T>.IdCombiner<TFirst, TSecond>.GetTupleArguments(firstId).Concat(RowImplementation<T>.IdCombiner<TFirst, TSecond>.GetTupleArguments(secondId)).ToList());
var createRow = typeof(IRowBuilder).GetGenericMethod(nameof(IRowBuilder.CreateRow), null, typeof(IEnumerable<KeyValuePair<string, object>>)).MakeGenericMethod(tuple.Type);
var toDictionary = typeof(Row).GetRuntimeMethod(nameof(Row.ToDictionary), new Type[0]);
var concat = typeof(Enumerable).GetGenericMethod(nameof(Enumerable.Concat), typeof(IEnumerable<>), typeof(IEnumerable<>)).MakeGenericMethod(typeof(KeyValuePair<string, object>));
var values = Expression.Call(
concat,
Expression.Convert(Expression.Call(first, toDictionary), typeof(IEnumerable<KeyValuePair<string, object>>)),
Expression.Convert(Expression.Call(second, toDictionary), typeof(IEnumerable<KeyValuePair<string, object>>)));
var lambda = Expression.Lambda<Func<IRowBuilder, RowImplementation<TFirst>, RowImplementation<TSecond>, Row>>(
Expression.Call(rowBuilder, createRow, tuple, values),
rowBuilder,
first,
second);
return lambda.Compile();
}
/// <summary>
/// Gets the generic type arguments from the parameter.
/// </summary>
/// <param name="parameter">
/// The parameter.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{T}"/>.
/// </returns>
private static IEnumerable<Expression> GetTupleArguments([NotNull] Expression parameter)
{
var type = parameter.Type;
if (type.IsConstructedGenericType && type.GetGenericTypeDefinition().Namespace == "System" && type.GetGenericTypeDefinition().Name.StartsWith("Tuple`"))
{
foreach (var runtimeProperty in type.GetRuntimeProperties().Where(p => p.GetMethod.IsPublic))
{
foreach (var argument in RowImplementation<T>.IdCombiner<TFirst, TSecond>.GetTupleArguments(Expression.Property(parameter, runtimeProperty)))
{
yield return argument;
}
}
}
else
{
yield return parameter;
}
}
/// <summary>
/// Creates a constructor call from the passed in expressions.
/// </summary>
/// <param name="expressions">
/// The expressions.
/// </param>
/// <returns>
/// The <see cref="Expression"/>.
/// </returns>
private static NewExpression NewTuple([NotNull] ICollection<Expression> expressions)
{
if (expressions.Count <= 7)
{
return Expression.New(
Type.GetType($"System.Tuple`{expressions.Count}").MakeGenericType(expressions.Select(e => e.Type).ToArray()).GetTypeInfo().DeclaredConstructors.First(),
expressions);
}
var arguments = expressions.Take(7).ToList();
arguments.Add(RowImplementation<T>.IdCombiner<TFirst, TSecond>.NewTuple(expressions.Skip(7).ToList()));
return Expression.New(
Type.GetType("System.Tuple`8").MakeGenericType(arguments.Select(a => a.Type).ToArray()).GetTypeInfo().DeclaredConstructors.First(),
arguments.ToArray());
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Security;
using AutoMapper;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Identity;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
using IUser = Umbraco.Core.Models.Membership.IUser;
using Task = System.Threading.Tasks.Task;
namespace Umbraco.Core.Security
{
public class BackOfficeUserStore : DisposableObject,
IUserStore<BackOfficeIdentityUser, int>,
IUserPasswordStore<BackOfficeIdentityUser, int>,
IUserEmailStore<BackOfficeIdentityUser, int>,
IUserLoginStore<BackOfficeIdentityUser, int>,
IUserRoleStore<BackOfficeIdentityUser, int>,
IUserSecurityStampStore<BackOfficeIdentityUser, int>,
IUserLockoutStore<BackOfficeIdentityUser, int>,
IUserTwoFactorStore<BackOfficeIdentityUser, int>
//TODO: This would require additional columns/tables for now people will need to implement this on their own
//IUserPhoneNumberStore<BackOfficeIdentityUser, int>,
//TODO: To do this we need to implement IQueryable - we'll have an IQuerable implementation soon with the UmbracoLinqPadDriver implementation
//IQueryableUserStore<BackOfficeIdentityUser, int>
{
private readonly IUserService _userService;
private readonly IEntityService _entityService;
private readonly IExternalLoginService _externalLoginService;
private bool _disposed = false;
public BackOfficeUserStore(IUserService userService, IEntityService entityService, IExternalLoginService externalLoginService, MembershipProviderBase usersMembershipProvider)
{
_userService = userService;
_entityService = entityService;
_externalLoginService = externalLoginService;
if (userService == null) throw new ArgumentNullException("userService");
if (usersMembershipProvider == null) throw new ArgumentNullException("usersMembershipProvider");
if (externalLoginService == null) throw new ArgumentNullException("externalLoginService");
_userService = userService;
_externalLoginService = externalLoginService;
if (usersMembershipProvider.PasswordFormat != MembershipPasswordFormat.Hashed)
{
throw new InvalidOperationException("Cannot use ASP.Net Identity with UmbracoMembersUserStore when the password format is not Hashed");
}
}
/// <summary>
/// Handles the disposal of resources. Derived from abstract class <see cref="DisposableObject"/> which handles common required locking logic.
/// </summary>
protected override void DisposeResources()
{
_disposed = true;
}
/// <summary>
/// Insert a new user
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task CreateAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
//the password must be 'something' it could be empty if authenticating
// with an external provider so we'll just generate one and prefix it, the
// prefix will help us determine if the password hasn't actually been specified yet.
//this will hash the guid with a salt so should be nicely random
var aspHasher = new PasswordHasher();
var emptyPasswordValue = Constants.Security.EmptyPasswordPrefix +
aspHasher.HashPassword(Guid.NewGuid().ToString("N"));
var userEntity = new User(user.Name, user.Email, user.UserName, emptyPasswordValue)
{
DefaultToLiveEditing = false,
Language = user.Culture ?? Configuration.GlobalSettings.DefaultUILanguage,
StartContentIds = user.StartContentIds ?? new int[] { },
StartMediaIds = user.StartMediaIds ?? new int[] { },
IsLockedOut = user.IsLockedOut,
};
UpdateMemberProperties(userEntity, user);
//TODO: We should deal with Roles --> User Groups here which we currently are not doing
_userService.Save(userEntity);
if (userEntity.Id == 0) throw new DataException("Could not create the user, check logs for details");
//re-assign id
user.Id = userEntity.Id;
return Task.FromResult(0);
}
/// <summary>
/// Update a user
/// </summary>
/// <param name="user"/>
/// <returns/>
public async Task UpdateAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
var asInt = user.Id.TryConvertTo<int>();
if (asInt == false)
{
throw new InvalidOperationException("The user id must be an integer to work with the Umbraco");
}
var found = _userService.GetUserById(asInt.Result);
if (found != null)
{
// we have to remember whether Logins property is dirty, since the UpdateMemberProperties will reset it.
var isLoginsPropertyDirty = user.IsPropertyDirty("Logins");
if (UpdateMemberProperties(found, user))
{
_userService.Save(found);
}
if (isLoginsPropertyDirty)
{
var logins = await GetLoginsAsync(user);
_externalLoginService.SaveUserLogins(found.Id, logins);
}
}
}
/// <summary>
/// Delete a user
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task DeleteAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
var asInt = user.Id.TryConvertTo<int>();
if (asInt == false)
{
throw new InvalidOperationException("The user id must be an integer to work with the Umbraco");
}
var found = _userService.GetUserById(asInt.Result);
if (found != null)
{
_userService.Delete(found);
}
_externalLoginService.DeleteUserLogins(asInt.Result);
return Task.FromResult(0);
}
/// <summary>
/// Finds a user
/// </summary>
/// <param name="userId"/>
/// <returns/>
public async Task<BackOfficeIdentityUser> FindByIdAsync(int userId)
{
ThrowIfDisposed();
var user = _userService.GetUserById(userId);
if (user == null)
{
return null;
}
return await Task.FromResult(AssignLoginsCallback(Mapper.Map<BackOfficeIdentityUser>(user)));
}
/// <summary>
/// Find a user by name
/// </summary>
/// <param name="userName"/>
/// <returns/>
public async Task<BackOfficeIdentityUser> FindByNameAsync(string userName)
{
ThrowIfDisposed();
var user = _userService.GetByUsername(userName);
if (user == null)
{
return null;
}
var result = AssignLoginsCallback(Mapper.Map<BackOfficeIdentityUser>(user));
return await Task.FromResult(result);
}
/// <summary>
/// Set the user password hash
/// </summary>
/// <param name="user"/><param name="passwordHash"/>
/// <returns/>
public Task SetPasswordHashAsync(BackOfficeIdentityUser user, string passwordHash)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (string.IsNullOrEmpty(passwordHash)) throw new ArgumentException("Value cannot be null or empty.", "passwordHash");
user.PasswordHash = passwordHash;
return Task.FromResult(0);
}
/// <summary>
/// Get the user password hash
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<string> GetPasswordHashAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.PasswordHash);
}
/// <summary>
/// Returns true if a user has a password set
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<bool> HasPasswordAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(string.IsNullOrEmpty(user.PasswordHash) == false);
}
/// <summary>
/// Set the user email
/// </summary>
/// <param name="user"/><param name="email"/>
/// <returns/>
public Task SetEmailAsync(BackOfficeIdentityUser user, string email)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (email.IsNullOrWhiteSpace()) throw new ArgumentNullException("email");
user.Email = email;
return Task.FromResult(0);
}
/// <summary>
/// Get the user email
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<string> GetEmailAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.Email);
}
/// <summary>
/// Returns true if the user email is confirmed
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<bool> GetEmailConfirmedAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.EmailConfirmed);
}
/// <summary>
/// Sets whether the user email is confirmed
/// </summary>
/// <param name="user"/><param name="confirmed"/>
/// <returns/>
public Task SetEmailConfirmedAsync(BackOfficeIdentityUser user, bool confirmed)
{
ThrowIfDisposed();
user.EmailConfirmed = confirmed;
return Task.FromResult(0);
}
/// <summary>
/// Returns the user associated with this email
/// </summary>
/// <param name="email"/>
/// <returns/>
public Task<BackOfficeIdentityUser> FindByEmailAsync(string email)
{
ThrowIfDisposed();
var user = _userService.GetByEmail(email);
var result = user == null
? null
: Mapper.Map<BackOfficeIdentityUser>(user);
return Task.FromResult(AssignLoginsCallback(result));
}
/// <summary>
/// Adds a user login with the specified provider and key
/// </summary>
/// <param name="user"/><param name="login"/>
/// <returns/>
public Task AddLoginAsync(BackOfficeIdentityUser user, UserLoginInfo login)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (login == null) throw new ArgumentNullException("login");
var logins = user.Logins;
var instance = new IdentityUserLogin(login.LoginProvider, login.ProviderKey, user.Id);
var userLogin = instance;
logins.Add(userLogin);
return Task.FromResult(0);
}
/// <summary>
/// Removes the user login with the specified combination if it exists
/// </summary>
/// <param name="user"/><param name="login"/>
/// <returns/>
public Task RemoveLoginAsync(BackOfficeIdentityUser user, UserLoginInfo login)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (login == null) throw new ArgumentNullException("login");
var provider = login.LoginProvider;
var key = login.ProviderKey;
var userLogin = user.Logins.SingleOrDefault((l => l.LoginProvider == provider && l.ProviderKey == key));
if (userLogin != null)
user.Logins.Remove(userLogin);
return Task.FromResult(0);
}
/// <summary>
/// Returns the linked accounts for this user
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<IList<UserLoginInfo>> GetLoginsAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult((IList<UserLoginInfo>)
user.Logins.Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey)).ToList());
}
/// <summary>
/// Returns the user associated with this login
/// </summary>
/// <returns/>
public Task<BackOfficeIdentityUser> FindAsync(UserLoginInfo login)
{
ThrowIfDisposed();
if (login == null) throw new ArgumentNullException("login");
//get all logins associated with the login id
var result = _externalLoginService.Find(login).ToArray();
if (result.Any())
{
//return the first user that matches the result
BackOfficeIdentityUser output = null;
foreach (var l in result)
{
var user = _userService.GetUserById(l.UserId);
if (user != null)
{
output = Mapper.Map<BackOfficeIdentityUser>(user);
break;
}
}
return Task.FromResult(AssignLoginsCallback(output));
}
return Task.FromResult<BackOfficeIdentityUser>(null);
}
/// <summary>
/// Adds a user to a role (user group)
/// </summary>
/// <param name="user"/><param name="roleName"/>
/// <returns/>
public Task AddToRoleAsync(BackOfficeIdentityUser user, string roleName)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (string.IsNullOrWhiteSpace(roleName)) throw new ArgumentException("Value cannot be null or whitespace.", "roleName");
var userRole = user.Roles.SingleOrDefault(r => r.RoleId == roleName);
if (userRole == null)
{
user.AddRole(roleName);
}
return Task.FromResult(0);
}
/// <summary>
/// Removes the role (user group) for the user
/// </summary>
/// <param name="user"/><param name="roleName"/>
/// <returns/>
public Task RemoveFromRoleAsync(BackOfficeIdentityUser user, string roleName)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (string.IsNullOrWhiteSpace(roleName)) throw new ArgumentException("Value cannot be null or whitespace.", "roleName");
var userRole = user.Roles.SingleOrDefault(r => r.RoleId == roleName);
if (userRole != null)
{
user.Roles.Remove(userRole);
}
return Task.FromResult(0);
}
/// <summary>
/// Returns the roles (user groups) for this user
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<IList<string>> GetRolesAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult((IList<string>)user.Roles.Select(x => x.RoleId).ToList());
}
/// <summary>
/// Returns true if a user is in the role
/// </summary>
/// <param name="user"/><param name="roleName"/>
/// <returns/>
public Task<bool> IsInRoleAsync(BackOfficeIdentityUser user, string roleName)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.Roles.Select(x => x.RoleId).InvariantContains(roleName));
}
/// <summary>
/// Set the security stamp for the user
/// </summary>
/// <param name="user"/><param name="stamp"/>
/// <returns/>
public Task SetSecurityStampAsync(BackOfficeIdentityUser user, string stamp)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
user.SecurityStamp = stamp;
return Task.FromResult(0);
}
/// <summary>
/// Get the user security stamp
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<string> GetSecurityStampAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
//the stamp cannot be null, so if it is currently null then we'll just return a hash of the password
return Task.FromResult(user.SecurityStamp.IsNullOrWhiteSpace()
? user.PasswordHash.GenerateHash()
: user.SecurityStamp);
}
private BackOfficeIdentityUser AssignLoginsCallback(BackOfficeIdentityUser user)
{
if (user != null)
{
user.SetLoginsCallback(new Lazy<IEnumerable<IIdentityUserLogin>>(() =>
_externalLoginService.GetAll(user.Id)));
}
return user;
}
/// <summary>
/// Sets whether two factor authentication is enabled for the user
/// </summary>
/// <param name="user"/><param name="enabled"/>
/// <returns/>
public virtual Task SetTwoFactorEnabledAsync(BackOfficeIdentityUser user, bool enabled)
{
user.TwoFactorEnabled = false;
return Task.FromResult(0);
}
/// <summary>
/// Returns whether two factor authentication is enabled for the user
/// </summary>
/// <param name="user"/>
/// <returns/>
public virtual Task<bool> GetTwoFactorEnabledAsync(BackOfficeIdentityUser user)
{
return Task.FromResult(false);
}
#region IUserLockoutStore
/// <summary>
/// Returns the DateTimeOffset that represents the end of a user's lockout, any time in the past should be considered not locked out.
/// </summary>
/// <param name="user"/>
/// <returns/>
/// <remarks>
/// Currently we do not suport a timed lock out, when they are locked out, an admin will have to reset the status
/// </remarks>
public Task<DateTimeOffset> GetLockoutEndDateAsync(BackOfficeIdentityUser user)
{
if (user == null) throw new ArgumentNullException("user");
return user.LockoutEndDateUtc.HasValue
? Task.FromResult(DateTimeOffset.MaxValue)
: Task.FromResult(DateTimeOffset.MinValue);
}
/// <summary>
/// Locks a user out until the specified end date (set to a past date, to unlock a user)
/// </summary>
/// <param name="user"/><param name="lockoutEnd"/>
/// <returns/>
/// <remarks>
/// Currently we do not suport a timed lock out, when they are locked out, an admin will have to reset the status
/// </remarks>
public Task SetLockoutEndDateAsync(BackOfficeIdentityUser user, DateTimeOffset lockoutEnd)
{
if (user == null) throw new ArgumentNullException("user");
user.LockoutEndDateUtc = lockoutEnd.UtcDateTime;
return Task.FromResult(0);
}
/// <summary>
/// Used to record when an attempt to access the user has failed
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<int> IncrementAccessFailedCountAsync(BackOfficeIdentityUser user)
{
if (user == null) throw new ArgumentNullException("user");
user.AccessFailedCount++;
return Task.FromResult(user.AccessFailedCount);
}
/// <summary>
/// Used to reset the access failed count, typically after the account is successfully accessed
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task ResetAccessFailedCountAsync(BackOfficeIdentityUser user)
{
if (user == null) throw new ArgumentNullException("user");
user.AccessFailedCount = 0;
return Task.FromResult(0);
}
/// <summary>
/// Returns the current number of failed access attempts. This number usually will be reset whenever the password is
/// verified or the account is locked out.
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<int> GetAccessFailedCountAsync(BackOfficeIdentityUser user)
{
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.AccessFailedCount);
}
/// <summary>
/// Returns true
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<bool> GetLockoutEnabledAsync(BackOfficeIdentityUser user)
{
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.LockoutEnabled);
}
/// <summary>
/// Doesn't actually perform any function, users can always be locked out
/// </summary>
/// <param name="user"/><param name="enabled"/>
/// <returns/>
public Task SetLockoutEnabledAsync(BackOfficeIdentityUser user, bool enabled)
{
if (user == null) throw new ArgumentNullException("user");
user.LockoutEnabled = enabled;
return Task.FromResult(0);
}
#endregion
private bool UpdateMemberProperties(IUser user, BackOfficeIdentityUser identityUser)
{
var anythingChanged = false;
//don't assign anything if nothing has changed as this will trigger the track changes of the model
if (identityUser.IsPropertyDirty("LastLoginDateUtc")
|| (user.LastLoginDate != default(DateTime) && identityUser.LastLoginDateUtc.HasValue == false)
|| identityUser.LastLoginDateUtc.HasValue && user.LastLoginDate.ToUniversalTime() != identityUser.LastLoginDateUtc.Value)
{
anythingChanged = true;
user.LastLoginDate = identityUser.LastLoginDateUtc.Value.ToLocalTime();
}
if (identityUser.IsPropertyDirty("EmailConfirmed")
|| (user.EmailConfirmedDate.HasValue && user.EmailConfirmedDate.Value != default(DateTime) && identityUser.EmailConfirmed == false)
|| ((user.EmailConfirmedDate.HasValue == false || user.EmailConfirmedDate.Value == default(DateTime)) && identityUser.EmailConfirmed))
{
anythingChanged = true;
user.EmailConfirmedDate = identityUser.EmailConfirmed ? (DateTime?)DateTime.Now : null;
}
if (identityUser.IsPropertyDirty("Name")
&& user.Name != identityUser.Name && identityUser.Name.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
user.Name = identityUser.Name;
}
if (identityUser.IsPropertyDirty("Email")
&& user.Email != identityUser.Email && identityUser.Email.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
user.Email = identityUser.Email;
}
if (identityUser.IsPropertyDirty("AccessFailedCount")
&& user.FailedPasswordAttempts != identityUser.AccessFailedCount)
{
anythingChanged = true;
user.FailedPasswordAttempts = identityUser.AccessFailedCount;
}
if (user.IsLockedOut != identityUser.IsLockedOut)
{
anythingChanged = true;
user.IsLockedOut = identityUser.IsLockedOut;
if (user.IsLockedOut)
{
//need to set the last lockout date
user.LastLockoutDate = DateTime.Now;
}
}
if (identityUser.IsPropertyDirty("UserName")
&& user.Username != identityUser.UserName && identityUser.UserName.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
user.Username = identityUser.UserName;
}
if (identityUser.IsPropertyDirty("PasswordHash")
&& user.RawPasswordValue != identityUser.PasswordHash && identityUser.PasswordHash.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
user.RawPasswordValue = identityUser.PasswordHash;
}
if (identityUser.IsPropertyDirty("Culture")
&& user.Language != identityUser.Culture && identityUser.Culture.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
user.Language = identityUser.Culture;
}
if (identityUser.IsPropertyDirty("StartMediaIds")
&& user.StartMediaIds.UnsortedSequenceEqual(identityUser.StartMediaIds) == false)
{
anythingChanged = true;
user.StartMediaIds = identityUser.StartMediaIds;
}
if (identityUser.IsPropertyDirty("StartContentIds")
&& user.StartContentIds.UnsortedSequenceEqual(identityUser.StartContentIds) == false)
{
anythingChanged = true;
user.StartContentIds = identityUser.StartContentIds;
}
if (user.SecurityStamp != identityUser.SecurityStamp)
{
anythingChanged = true;
user.SecurityStamp = identityUser.SecurityStamp;
}
//TODO: Fix this for Groups too
if (identityUser.IsPropertyDirty("Roles") || identityUser.IsPropertyDirty("Groups"))
{
var userGroupAliases = user.Groups.Select(x => x.Alias).ToArray();
var identityUserRoles = identityUser.Roles.Select(x => x.RoleId).ToArray();
var identityUserGroups = identityUser.Groups.Select(x => x.Alias).ToArray();
var combinedAliases = identityUserRoles.Union(identityUserGroups).ToArray();
if (userGroupAliases.ContainsAll(combinedAliases) == false
|| combinedAliases.ContainsAll(userGroupAliases) == false)
{
anythingChanged = true;
//clear out the current groups (need to ToArray since we are modifying the iterator)
user.ClearGroups();
//go lookup all these groups
var groups = _userService.GetUserGroupsByAlias(combinedAliases).Select(x => x.ToReadOnlyGroup()).ToArray();
//use all of the ones assigned and add them
foreach (var group in groups)
{
user.AddGroup(group);
}
//re-assign
identityUser.Groups = groups;
}
}
//we should re-set the calculated start nodes
identityUser.CalculatedMediaStartNodeIds = user.CalculateMediaStartNodeIds(_entityService);
identityUser.CalculatedContentStartNodeIds = user.CalculateContentStartNodeIds(_entityService);
//reset all changes
identityUser.ResetDirtyProperties(false);
return anythingChanged;
}
private void ThrowIfDisposed()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
}
}
}
| |
using System;
using System.Data;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Xunit;
namespace NReco.Data.Tests {
public class DbDataAdapterTests : IClassFixture<SqliteDbFixture> {
SqliteDbFixture SqliteDb;
DbDataAdapter DbAdapter;
public DbDataAdapterTests(SqliteDbFixture sqliteDb) {
SqliteDb = sqliteDb;
var cmdBuilder = new DbCommandBuilder(SqliteDb.DbFactory);
cmdBuilder.Views["contacts_view"] = new DbDataView(
@"SELECT @columns FROM contacts c
LEFT JOIN companies cc ON (cc.id=c.company_id)
@where[ WHERE {0}] @orderby[ ORDER BY {0}]"
) {
FieldMapping = new Dictionary<string,string>() {
{"id", "c.id"},
{"*", "c.*, cc.title as company_title"}
}
};
DbAdapter = new DbDataAdapter(sqliteDb.DbConnection, cmdBuilder );
}
[Fact]
public void Select() {
// count: table
Assert.Equal(5, DbAdapter.Select(new Query("contacts").Select(QField.Count) ).Single<int>() );
// count for schema-qualified query
Assert.Equal(5, DbAdapter.Select( new Query( new QTable( "main.contacts",null) ).Select(QField.Count) ).Single<int>() );
// count: data view
Assert.Equal(5, DbAdapter.Select(new Query("contacts_view").Select(QField.Count) ).Single<int>() );
var johnContactQuery = DbAdapter.Select(new Query("contacts", new QConditionNode((QField)"name",Conditions.Like,(QConst)"%john%") ) );
var johnDict = johnContactQuery.ToDictionary();
Assert.Equal("John Doe", johnDict["name"]);
Assert.Equal(4, johnDict.Count);
var johnModel = johnContactQuery.Single<ContactModel>();
Assert.Equal("John Doe", johnModel.name);
var contactsWithHighScoreQuery = DbAdapter.Select(
new Query("contacts_view", (QField)"score" > (QConst)4 ).OrderBy("name desc")
);
var contactsWithHighDicts = contactsWithHighScoreQuery.ToDictionaryList();
Assert.Equal(2, contactsWithHighDicts.Count );
var contactsWithHightRS = contactsWithHighScoreQuery.ToRecordSet();
Assert.Equal(2, contactsWithHightRS.Count );
Assert.Equal(5, contactsWithHightRS.Columns.Count );
Assert.Equal("Viola Garrett", contactsWithHightRS[0]["name"] );
// check in
var contactsWithFourAndFiveScore = DbAdapter.Select(
new Query("contacts_view", new QConditionNode( (QField)"score", Conditions.In, new QConst(new[] {4,5}) ) ).OrderBy("name desc")
);
Assert.Equal(4, contactsWithFourAndFiveScore.ToRecordSet().Count);
// select to annotated object
var companies = DbAdapter.Select(new Query("companies").OrderBy("id")).ToList<CompanyModelAnnotated>();
Assert.Equal(2, companies.Count);
Assert.Equal("Microsoft", companies[0].Name);
}
[Fact]
public async Task Select_Async() {
// count: table
Assert.Equal(5, await DbAdapter.Select(new Query("contacts").Select(QField.Count) ).SingleAsync<int>() );
var contactsWithHighScoreQuery = DbAdapter.Select(
new Query("contacts_view", (QField)"score" > (QConst)4 ).OrderBy("name desc")
);
var contactsWithHighDicts = await contactsWithHighScoreQuery.ToDictionaryListAsync();
Assert.Equal(2, contactsWithHighDicts.Count );
var contactsWithHightRS = await contactsWithHighScoreQuery.ToRecordSetAsync();
Assert.Equal(2, contactsWithHightRS.Count );
}
[Fact]
public void SelectRawSql() {
//no params
Assert.Equal(5, DbAdapter.Select("select count(*) from contacts").Single<int>() );
// simple param
Assert.Equal(5, DbAdapter.Select("select count(*) from contacts where id<{0}", 100).Single<int>() );
Assert.Equal(1, DbAdapter.Select("select count(*) from contacts where id>{0} and id<{1}", 1, 3).Single<int>() );
// custom db param
var customParam = new Microsoft.Data.Sqlite.SqliteParameter("test", "%John%");
Assert.Equal(1, DbAdapter.Select("select company_id from contacts where name like @test", customParam).Single<int>() );
}
[Fact]
public void Select_CustomMapper() {
var res = DbAdapter
.Select(new Query("contacts_view", (QField)"name" == (QConst)"Morris Scott") )
.SetMapper( (context)=> {
if (context.ObjectType==typeof(ContactModel)) {
var contact = (ContactModel)context.MapTo(context.ObjectType);
contact.Company = new CompanyModelAnnotated();
contact.Company.Id = Convert.ToInt32( context.DataReader["company_id"] );
contact.Company.Name = (string)context.DataReader["company_title"];
return contact;
}
// default handler
return context.MapTo(context.ObjectType);
})
.Single<ContactModel>();
Assert.NotNull(res.Company);
Assert.Equal(1, res.Company.Id.Value);
Assert.Equal("Microsoft", res.Company.Name);
}
[Fact]
public void InsertUpdateDelete_Dictionary() {
// insert
object recordId = null;
SqliteDb.OpenConnection( () => {
Assert.Equal(1,
DbAdapter.Insert("main.companies", new Dictionary<string,object>() {
{"title", "Test Inc"},
{"country", "Norway"},
{"logo_image", null}
}) );
recordId = DbAdapter.CommandBuilder.DbFactory.GetInsertId(DbAdapter.Connection);
} );
// update - schema qualified
Assert.Equal(1,
DbAdapter.Update( new Query( new QTable("main.companies", null), (QField)"id"==new QConst(recordId) ),
new Dictionary<string,object>() {
{"title", "Megacorp"}
}
) );
// update
Assert.Equal(1,
DbAdapter.Update( new Query("companies", (QField)"id"==new QConst(recordId) ),
new Dictionary<string,object>() {
{"title", "Megacorp Inc"}
}
) );
var norwayCompanyQ = new Query("companies", (QField)"country"==(QConst)"Norway" );
Assert.Equal("Megacorp Inc", DbAdapter.Select(norwayCompanyQ).ToDictionary()["title"]);
// cleanup
Assert.Equal(1, DbAdapter.Delete( norwayCompanyQ ) );
// delete - schema qualified (affects 0 records)
Assert.Equal(0, DbAdapter.Delete( new Query( new QTable("main.companies",null), (QField)"country"==(QConst)"bla" ) ) );
}
[Fact]
public async Task InsertUpdateDelete_DictionaryAsync() {
// insert
DbAdapter.Connection.Open();
Assert.Equal(1,
await DbAdapter.InsertAsync("companies", new Dictionary<string,object>() {
{"title", "Test Inc"},
{"country", "Norway"}
}).ConfigureAwait(false) );
object recordId = DbAdapter.CommandBuilder.DbFactory.GetInsertId(DbAdapter.Connection);
DbAdapter.Connection.Close();
// update
Assert.Equal(1,
await DbAdapter.UpdateAsync( new Query("companies", (QField)"id"==new QConst(recordId) ),
new Dictionary<string,object>() {
{"title", "Megacorp Inc"}
}
).ConfigureAwait(false) );
var norwayCompanyQ = new Query("companies", (QField)"country"==(QConst)"Norway" );
Assert.Equal("Megacorp Inc", DbAdapter.Select(norwayCompanyQ).ToDictionary()["title"]);
// cleanup
Assert.Equal(1, await DbAdapter.DeleteAsync( norwayCompanyQ ).ConfigureAwait(false) );
}
[Fact]
public void InsertUpdateDelete_RecordSet() {
var companyRS = DbAdapter.Select(new Query("companies")).ToRecordSet();
companyRS.SetPrimaryKey("id");
companyRS.Columns["id"].AutoIncrement = true;
var newCompany1Row = companyRS.Add();
newCompany1Row["title"] = "Test Inc";
newCompany1Row["country"] = "Ukraine";
var newCompany2Row = companyRS.Add();
newCompany2Row["title"] = "Cool Inc";
newCompany2Row["country"] = "France";
Assert.Equal(4, companyRS.Count );
Assert.Equal(2, DbAdapter.Update("companies", companyRS) );
Assert.True( newCompany1Row.Field<int>("id")>0 );
Assert.True( newCompany2Row.Field<int>("id")>0 );
Assert.Equal(RecordSet.RowState.Unchanged, newCompany1Row.State);
newCompany2Row["title"] = "Awesome Corp";
Assert.Equal(1, DbAdapter.Update("main.companies", companyRS));
Assert.Equal(RecordSet.RowState.Unchanged, newCompany2Row.State);
// cleanup
newCompany1Row.Delete();
newCompany2Row.Delete();
DbAdapter.Update("companies", companyRS);
Assert.Equal(2, companyRS.Count);
Assert.Equal(2, DbAdapter.Select(new Query("companies").Select(QField.Count) ).Single<int>() );
}
[Fact]
public async Task InsertUpdateDeleteAsync_RecordSet() {
var companyRS = await DbAdapter.Select(new Query("companies")).ToRecordSetAsync().ConfigureAwait(false);
Assert.Equal(2, companyRS.Count);
companyRS.SetPrimaryKey("id");
companyRS.Columns["id"].AutoIncrement = true;
var newCompany1Row = companyRS.Add();
newCompany1Row["title"] = "Test Inc";
newCompany1Row["country"] = "Ukraine";
Assert.Equal(1, DbAdapter.UpdateAsync("companies", companyRS).GetAwaiter().GetResult() );
Assert.NotNull(newCompany1Row["id"]);
Assert.Equal( RecordSet.RowState.Unchanged, newCompany1Row.State );
newCompany1Row["title"] = "Mega Corp";
var newCompany2Row = companyRS.Add();
newCompany2Row["title"] = "Cool Inc";
newCompany2Row["country"] = "France";
Assert.Equal(2, DbAdapter.UpdateAsync("companies", companyRS).GetAwaiter().GetResult() );
Assert.Equal(2, await DbAdapter.DeleteAsync(new Query("companies", (QField)"id">= new QConst(newCompany1Row["id"]) )) );
}
[Fact]
public void InsertUpdateDelete_PocoModel() {
// insert
var newCompany = new CompanyModelAnnotated();
newCompany.Id = 5000; // should be ignored
newCompany.Name = "Test Super Corp";
newCompany.registered = false; // should be ignored
newCompany.Logo = new byte[] { 1,2,3 }; // lets assume this is sample binary data
DbAdapter.Insert(newCompany);
Assert.True(newCompany.Id.HasValue);
Assert.NotEqual(5000, newCompany.Id.Value);
Assert.Equal("Test Super Corp", DbAdapter.Select(new Query("companies", (QField)"id"==(QConst)newCompany.Id.Value).Select("title") ).Single<string>() );
newCompany.Name = "Super Corp updated";
Assert.Equal(1, DbAdapter.Update( newCompany) );
Assert.Equal(newCompany.Name, DbAdapter.Select(new Query("companies", (QField)"id"==(QConst)newCompany.Id.Value).Select("title") ).Single<string>() );
Assert.Equal(1, DbAdapter.Delete( newCompany ) );
}
[Fact]
public async Task InsertUpdateDelete_PocoModelAsync() {
// insert
var newCompany = new CompanyModelAnnotated();
newCompany.Id = 5000; // should be ignored
newCompany.Name = "Test Super Corp";
newCompany.registered = false; // should be ignored
Assert.Equal(1, await DbAdapter.InsertAsync(newCompany).ConfigureAwait(false) );
Assert.True(newCompany.Id.HasValue);
Assert.NotEqual(5000, newCompany.Id.Value);
Assert.Equal("Test Super Corp", DbAdapter.Select(new Query("companies", (QField)"id"==(QConst)newCompany.Id.Value).Select("title") ).Single<string>() );
newCompany.Name = "Super Corp updated";
Assert.Equal(1, await DbAdapter.UpdateAsync( newCompany).ConfigureAwait(false) );
Assert.Equal(newCompany.Name, DbAdapter.Select(new Query("companies", (QField)"id"==(QConst)newCompany.Id.Value).Select("title") ).Single<string>() );
Assert.Equal(1, await DbAdapter.DeleteAsync( newCompany ).ConfigureAwait(false) );
}
public class ContactModel {
public int? id { get; set; }
public string name { get; set; }
public int? company_id { get; set; }
// property is used in custom POCO mapping handler test
public CompanyModelAnnotated Company { get; set; }
}
[Table("companies")]
public class CompanyModelAnnotated {
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
[Column("id")]
public int? Id { get; set; }
[Column("title")]
public string Name { get; set; }
[Column("logo_image")]
public byte[] Logo { get; set; }
[NotMapped]
public bool registered { get; set; }
}
}
}
| |
namespace android.view.animation
{
[global::MonoJavaBridge.JavaClass()]
public partial class GridLayoutAnimationController : android.view.animation.LayoutAnimationController
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static GridLayoutAnimationController()
{
InitJNI();
}
protected GridLayoutAnimationController(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass()]
public new partial class AnimationParameters : android.view.animation.LayoutAnimationController.AnimationParameters
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static AnimationParameters()
{
InitJNI();
}
protected AnimationParameters(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _AnimationParameters9998;
public AnimationParameters() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.GridLayoutAnimationController.AnimationParameters.staticClass, global::android.view.animation.GridLayoutAnimationController.AnimationParameters._AnimationParameters9998);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _column9999;
public int column
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _row10000;
public int row
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _columnsCount10001;
public int columnsCount
{
get
{
return default(int);
}
set
{
}
}
internal static global::MonoJavaBridge.FieldId _rowsCount10002;
public int rowsCount
{
get
{
return default(int);
}
set
{
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.animation.GridLayoutAnimationController.AnimationParameters.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/GridLayoutAnimationController$AnimationParameters"));
global::android.view.animation.GridLayoutAnimationController.AnimationParameters._AnimationParameters9998 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.AnimationParameters.staticClass, "<init>", "()V");
}
}
internal static global::MonoJavaBridge.MethodId _willOverlap10003;
public override bool willOverlap()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController._willOverlap10003);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._willOverlap10003);
}
internal static global::MonoJavaBridge.MethodId _getDelayForView10004;
protected override long getDelayForView(android.view.View arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallLongMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController._getDelayForView10004, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._getDelayForView10004, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getColumnDelay10005;
public virtual float getColumnDelay()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController._getColumnDelay10005);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._getColumnDelay10005);
}
internal static global::MonoJavaBridge.MethodId _setColumnDelay10006;
public virtual void setColumnDelay(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController._setColumnDelay10006, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._setColumnDelay10006, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getRowDelay10007;
public virtual float getRowDelay()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController._getRowDelay10007);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._getRowDelay10007);
}
internal static global::MonoJavaBridge.MethodId _setRowDelay10008;
public virtual void setRowDelay(float arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController._setRowDelay10008, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._setRowDelay10008, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getDirection10009;
public virtual int getDirection()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController._getDirection10009);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._getDirection10009);
}
internal static global::MonoJavaBridge.MethodId _setDirection10010;
public virtual void setDirection(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController._setDirection10010, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._setDirection10010, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getDirectionPriority10011;
public virtual int getDirectionPriority()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController._getDirectionPriority10011);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._getDirectionPriority10011);
}
internal static global::MonoJavaBridge.MethodId _setDirectionPriority10012;
public virtual void setDirectionPriority(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController._setDirectionPriority10012, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._setDirectionPriority10012, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _GridLayoutAnimationController10013;
public GridLayoutAnimationController(android.view.animation.Animation arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._GridLayoutAnimationController10013, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _GridLayoutAnimationController10014;
public GridLayoutAnimationController(android.view.animation.Animation arg0, float arg1, float arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._GridLayoutAnimationController10014, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _GridLayoutAnimationController10015;
public GridLayoutAnimationController(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.animation.GridLayoutAnimationController.staticClass, global::android.view.animation.GridLayoutAnimationController._GridLayoutAnimationController10015, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
public static int DIRECTION_LEFT_TO_RIGHT
{
get
{
return 0;
}
}
public static int DIRECTION_RIGHT_TO_LEFT
{
get
{
return 1;
}
}
public static int DIRECTION_TOP_TO_BOTTOM
{
get
{
return 0;
}
}
public static int DIRECTION_BOTTOM_TO_TOP
{
get
{
return 2;
}
}
public static int DIRECTION_HORIZONTAL_MASK
{
get
{
return 1;
}
}
public static int DIRECTION_VERTICAL_MASK
{
get
{
return 2;
}
}
public static int PRIORITY_NONE
{
get
{
return 0;
}
}
public static int PRIORITY_COLUMN
{
get
{
return 1;
}
}
public static int PRIORITY_ROW
{
get
{
return 2;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.animation.GridLayoutAnimationController.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/animation/GridLayoutAnimationController"));
global::android.view.animation.GridLayoutAnimationController._willOverlap10003 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "willOverlap", "()Z");
global::android.view.animation.GridLayoutAnimationController._getDelayForView10004 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "getDelayForView", "(Landroid/view/View;)J");
global::android.view.animation.GridLayoutAnimationController._getColumnDelay10005 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "getColumnDelay", "()F");
global::android.view.animation.GridLayoutAnimationController._setColumnDelay10006 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "setColumnDelay", "(F)V");
global::android.view.animation.GridLayoutAnimationController._getRowDelay10007 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "getRowDelay", "()F");
global::android.view.animation.GridLayoutAnimationController._setRowDelay10008 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "setRowDelay", "(F)V");
global::android.view.animation.GridLayoutAnimationController._getDirection10009 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "getDirection", "()I");
global::android.view.animation.GridLayoutAnimationController._setDirection10010 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "setDirection", "(I)V");
global::android.view.animation.GridLayoutAnimationController._getDirectionPriority10011 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "getDirectionPriority", "()I");
global::android.view.animation.GridLayoutAnimationController._setDirectionPriority10012 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "setDirectionPriority", "(I)V");
global::android.view.animation.GridLayoutAnimationController._GridLayoutAnimationController10013 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "<init>", "(Landroid/view/animation/Animation;)V");
global::android.view.animation.GridLayoutAnimationController._GridLayoutAnimationController10014 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "<init>", "(Landroid/view/animation/Animation;FF)V");
global::android.view.animation.GridLayoutAnimationController._GridLayoutAnimationController10015 = @__env.GetMethodIDNoThrow(global::android.view.animation.GridLayoutAnimationController.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Data
{
internal sealed class NameNode : ExpressionNode
{
internal char _open = '\0';
internal char _close = '\0';
internal string _name;
internal bool _found;
internal bool _type = false;
internal DataColumn _column;
internal NameNode(DataTable table, char[] text, int start, int pos) : base(table)
{
_name = ParseName(text, start, pos);
}
internal NameNode(DataTable table, string name) : base(table)
{
_name = name;
}
internal override bool IsSqlColumn
{
get
{
return _column.IsSqlType;
}
}
internal override void Bind(DataTable table, List<DataColumn> list)
{
BindTable(table);
if (table == null)
throw ExprException.UnboundName(_name);
try
{
_column = table.Columns[_name];
}
catch (Exception e)
{
_found = false;
if (!Common.ADP.IsCatchableExceptionType(e))
{
throw;
}
throw ExprException.UnboundName(_name);
}
if (_column == null)
throw ExprException.UnboundName(_name);
_name = _column.ColumnName;
_found = true;
// add column to the dependency list, do not add duplicate columns
Debug.Assert(_column != null, "Failed to bind column " + _name);
int i;
for (i = 0; i < list.Count; i++)
{
// walk the list, check if the current column already on the list
DataColumn dataColumn = list[i];
if (_column == dataColumn)
{
break;
}
}
if (i >= list.Count)
{
list.Add(_column);
}
}
internal override object Eval()
{
// can not eval column without ROW value;
throw ExprException.EvalNoContext();
}
internal override object Eval(DataRow row, DataRowVersion version)
{
if (!_found)
{
throw ExprException.UnboundName(_name);
}
if (row == null)
{
if (IsTableConstant()) // this column is TableConstant Aggregate Function
return _column.DataExpression.Evaluate();
else
{
throw ExprException.UnboundName(_name);
}
}
return _column[row.GetRecordFromVersion(version)];
}
internal override object Eval(int[] records)
{
throw ExprException.ComputeNotAggregate(ToString());
}
internal override bool IsConstant()
{
return false;
}
internal override bool IsTableConstant()
{
if (_column != null && _column.Computed)
{
return _column.DataExpression.IsTableAggregate();
}
return false;
}
internal override bool HasLocalAggregate()
{
if (_column != null && _column.Computed)
{
return _column.DataExpression.HasLocalAggregate();
}
return false;
}
internal override bool HasRemoteAggregate()
{
if (_column != null && _column.Computed)
{
return _column.DataExpression.HasRemoteAggregate();
}
return false;
}
internal override bool DependsOn(DataColumn column)
{
if (_column == column)
return true;
if (_column.Computed)
{
return _column.DataExpression.DependsOn(column);
}
return false;
}
internal override ExpressionNode Optimize()
{
return this;
}
/// <summary>
/// Parses given name and checks it validity
/// </summary>
internal static string ParseName(char[] text, int start, int pos)
{
char esc = '\0';
string charsToEscape = string.Empty;
int saveStart = start;
int savePos = pos;
if (text[start] == '`')
{
start = checked((start + 1));
pos = checked((pos - 1));
esc = '\\';
charsToEscape = "`";
}
else if (text[start] == '[')
{
start = checked((start + 1));
pos = checked((pos - 1));
esc = '\\';
charsToEscape = "]\\";
}
if (esc != '\0')
{
// scan the name in search for the ESC
int posEcho = start;
for (int i = start; i < pos; i++)
{
if (text[i] == esc)
{
if (i + 1 < pos && charsToEscape.IndexOf(text[i + 1]) >= 0)
{
i++;
}
}
text[posEcho] = text[i];
posEcho++;
}
pos = posEcho;
}
if (pos == start)
throw ExprException.InvalidName(new string(text, saveStart, savePos - saveStart));
return new string(text, start, pos - start);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Text;
using Microsoft.PowerShell.Commands;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
internal static class DefaultScalarTypes
{
internal static bool IsTypeInList(Collection<string> typeNames)
{
// NOTE: we do not use inheritance here, since we deal with
// value types or with types where inheritance is not a factor for the selection
string typeName = PSObjectHelper.PSObjectIsOfExactType(typeNames);
if (string.IsNullOrEmpty(typeName))
return false;
string originalTypeName = Deserializer.MaskDeserializationPrefix(typeName);
if (string.IsNullOrEmpty(originalTypeName))
return false;
// check if the type is derived from a System.Enum
// e.g. in C#
// enum Foo { Red, Black, Green}
if (PSObjectHelper.PSObjectIsEnum(typeNames))
return true;
return s_defaultScalarTypesHash.Contains(originalTypeName);
}
static DefaultScalarTypes()
{
s_defaultScalarTypesHash.Add("System.String");
s_defaultScalarTypesHash.Add("System.SByte");
s_defaultScalarTypesHash.Add("System.Byte");
s_defaultScalarTypesHash.Add("System.Int16");
s_defaultScalarTypesHash.Add("System.UInt16");
s_defaultScalarTypesHash.Add("System.Int32");
s_defaultScalarTypesHash.Add("System.UInt32");
s_defaultScalarTypesHash.Add("System.Int64");
s_defaultScalarTypesHash.Add("System.UInt64");
s_defaultScalarTypesHash.Add("System.Char");
s_defaultScalarTypesHash.Add("System.Single");
s_defaultScalarTypesHash.Add("System.Double");
s_defaultScalarTypesHash.Add("System.Boolean");
s_defaultScalarTypesHash.Add("System.Decimal");
s_defaultScalarTypesHash.Add("System.IntPtr");
s_defaultScalarTypesHash.Add("System.Security.SecureString");
s_defaultScalarTypesHash.Add("System.Numerics.BigInteger");
}
private static readonly HashSet<string> s_defaultScalarTypesHash = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Class to manage the selection of a desired view type and
/// manage state associated to the selected view.
/// </summary>
internal sealed class FormatViewManager
{
#region tracer
[TraceSource("FormatViewBinding", "Format view binding")]
private static PSTraceSource s_formatViewBindingTracer = PSTraceSource.GetTracer("FormatViewBinding", "Format view binding", false);
#endregion tracer
private static string PSObjectTypeName(PSObject so)
{
// if so is not null, its TypeNames will not be null
if (so != null)
{
var typeNames = so.InternalTypeNames;
if (typeNames.Count > 0)
{
return typeNames[0];
}
}
return string.Empty;
}
internal void Initialize(TerminatingErrorContext errorContext,
PSPropertyExpressionFactory expressionFactory,
TypeInfoDataBase db,
PSObject so,
FormatShape shape,
FormattingCommandLineParameters parameters)
{
ViewDefinition view = null;
const string findViewType = "FINDING VIEW TYPE: {0}";
const string findViewShapeType = "FINDING VIEW {0} TYPE: {1}";
const string findViewNameType = "FINDING VIEW NAME: {0} TYPE: {1}";
const string viewFound = "An applicable view has been found";
const string viewNotFound = "No applicable view has been found";
try
{
DisplayDataQuery.SetTracer(s_formatViewBindingTracer);
// shape not specified: we need to select one
var typeNames = so.InternalTypeNames;
if (shape == FormatShape.Undefined)
{
using (s_formatViewBindingTracer.TraceScope(findViewType, PSObjectTypeName(so)))
{
view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, null);
}
if (view != null)
{
// we got a matching view from the database
// use this and we are done
_viewGenerator = SelectViewGeneratorFromViewDefinition(
errorContext,
expressionFactory,
db,
view,
parameters);
s_formatViewBindingTracer.WriteLine(viewFound);
PrepareViewForRemoteObjects(ViewGenerator, so);
return;
}
s_formatViewBindingTracer.WriteLine(viewNotFound);
// we did not get any default view (and shape), we need to force one
// we just select properties out of the object itself, since they were not
// specified on the command line
_viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, null);
PrepareViewForRemoteObjects(ViewGenerator, so);
return;
}
// we have a predefined shape: did the user specify properties on the command line?
if (parameters != null && parameters.mshParameterList.Count > 0)
{
_viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters);
return;
}
// predefined shape: did the user specify the name of a view?
if (parameters != null && !string.IsNullOrEmpty(parameters.viewName))
{
using (s_formatViewBindingTracer.TraceScope(findViewNameType, parameters.viewName,
PSObjectTypeName(so)))
{
view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, parameters.viewName);
}
if (view != null)
{
_viewGenerator = SelectViewGeneratorFromViewDefinition(
errorContext,
expressionFactory,
db,
view,
parameters);
s_formatViewBindingTracer.WriteLine(viewFound);
return;
}
s_formatViewBindingTracer.WriteLine(viewNotFound);
// illegal input, we have to terminate
ProcessUnknownViewName(errorContext, parameters.viewName, so, db, shape);
}
// predefined shape: do we have a default view in format.ps1xml?
using (s_formatViewBindingTracer.TraceScope(findViewShapeType, shape, PSObjectTypeName(so)))
{
view = DisplayDataQuery.GetViewByShapeAndType(expressionFactory, db, shape, typeNames, null);
}
if (view != null)
{
_viewGenerator = SelectViewGeneratorFromViewDefinition(
errorContext,
expressionFactory,
db,
view,
parameters);
s_formatViewBindingTracer.WriteLine(viewFound);
PrepareViewForRemoteObjects(ViewGenerator, so);
return;
}
s_formatViewBindingTracer.WriteLine(viewNotFound);
// we just select properties out of the object itself
_viewGenerator = SelectViewGeneratorFromProperties(shape, so, errorContext, expressionFactory, db, parameters);
PrepareViewForRemoteObjects(ViewGenerator, so);
}
finally
{
DisplayDataQuery.ResetTracer();
}
}
/// <summary>
/// Prepares a given view for remote object processing ie., lets the view
/// display (or not) ComputerName property. This will query the object to
/// check if ComputerName property is present. If present, this will prepare
/// the view.
/// </summary>
/// <param name="viewGenerator"></param>
/// <param name="so"></param>
private static void PrepareViewForRemoteObjects(ViewGenerator viewGenerator, PSObject so)
{
if (PSObjectHelper.ShouldShowComputerNameProperty(so))
{
viewGenerator.PrepareForRemoteObjects(so);
}
}
/// <summary>
/// Helper method to process Unknown error message.
/// It helps is creating appropriate error message to
/// be displayed to the user.
/// </summary>
/// <param name="errorContext">Error context.</param>
/// <param name="viewName">Uses supplied view name.</param>
/// <param name="so">Source object.</param>
/// <param name="db">Types info database.</param>
/// <param name="formatShape">Requested format shape.</param>
private static void ProcessUnknownViewName(TerminatingErrorContext errorContext, string viewName, PSObject so, TypeInfoDataBase db, FormatShape formatShape)
{
string msg = null;
bool foundValidViews = false;
string formatTypeName = null;
string separator = ", ";
StringBuilder validViewFormats = new StringBuilder();
if (so != null && so.BaseObject != null &&
db != null && db.viewDefinitionsSection != null &&
db.viewDefinitionsSection.viewDefinitionList != null &&
db.viewDefinitionsSection.viewDefinitionList.Count > 0)
{
StringBuilder validViews = new StringBuilder();
string currentObjectTypeName = so.BaseObject.GetType().ToString();
Type formatType = null;
if (formatShape == FormatShape.Table)
{
formatType = typeof(TableControlBody);
formatTypeName = "Table";
}
else if (formatShape == FormatShape.List)
{
formatType = typeof(ListControlBody);
formatTypeName = "List";
}
else if (formatShape == FormatShape.Wide)
{
formatType = typeof(WideControlBody);
formatTypeName = "Wide";
}
else if (formatShape == FormatShape.Complex)
{
formatType = typeof(ComplexControlBody);
formatTypeName = "Custom";
}
if (formatType != null)
{
foreach (ViewDefinition currentViewDefinition in db.viewDefinitionsSection.viewDefinitionList)
{
if (currentViewDefinition.mainControl != null)
{
foreach (TypeOrGroupReference currentTypeOrGroupReference in currentViewDefinition.appliesTo.referenceList)
{
if (!string.IsNullOrEmpty(currentTypeOrGroupReference.name) &&
string.Equals(currentObjectTypeName, currentTypeOrGroupReference.name, StringComparison.OrdinalIgnoreCase))
{
if (currentViewDefinition.mainControl.GetType() == formatType)
{
validViews.Append(currentViewDefinition.name);
validViews.Append(separator);
}
else if (string.Equals(viewName, currentViewDefinition.name, StringComparison.OrdinalIgnoreCase))
{
string cmdletFormatName = null;
if (currentViewDefinition.mainControl is TableControlBody)
{
cmdletFormatName = "Format-Table";
}
else if (currentViewDefinition.mainControl is ListControlBody)
{
cmdletFormatName = "Format-List";
}
else if (currentViewDefinition.mainControl is WideControlBody)
{
cmdletFormatName = "Format-Wide";
}
else if (currentViewDefinition.mainControl is ComplexControlBody)
{
cmdletFormatName = "Format-Custom";
}
if (validViewFormats.Length == 0)
{
string suggestValidViewNamePrefix = StringUtil.Format(FormatAndOut_format_xxx.SuggestValidViewNamePrefix);
validViewFormats.Append(suggestValidViewNamePrefix);
}
else
{
validViewFormats.Append(", ");
}
validViewFormats.Append(cmdletFormatName);
}
}
}
}
}
}
if (validViews.Length > 0)
{
validViews.Remove(validViews.Length - separator.Length, separator.Length);
msg = StringUtil.Format(FormatAndOut_format_xxx.InvalidViewNameError, viewName, formatTypeName, validViews.ToString());
foundValidViews = true;
}
}
if (!foundValidViews)
{
StringBuilder unKnowViewFormatStringBuilder = new StringBuilder();
if (validViewFormats.Length > 0)
{
// unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameError, viewName));
unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameErrorSuffix, viewName, formatTypeName));
unKnowViewFormatStringBuilder.Append(validViewFormats.ToString());
}
else
{
unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.UnknownViewNameError, viewName));
unKnowViewFormatStringBuilder.Append(StringUtil.Format(FormatAndOut_format_xxx.NonExistingViewNameError, formatTypeName, so.BaseObject.GetType()));
}
msg = unKnowViewFormatStringBuilder.ToString(); ;
}
ErrorRecord errorRecord = new ErrorRecord(
new PipelineStoppedException(),
"FormatViewNotFound",
ErrorCategory.ObjectNotFound,
viewName);
errorRecord.ErrorDetails = new ErrorDetails(msg);
errorContext.ThrowTerminatingError(errorRecord);
}
internal ViewGenerator ViewGenerator
{
get
{
Diagnostics.Assert(_viewGenerator != null, "this.viewGenerator cannot be null");
return _viewGenerator;
}
}
private static ViewGenerator SelectViewGeneratorFromViewDefinition(
TerminatingErrorContext errorContext,
PSPropertyExpressionFactory expressionFactory,
TypeInfoDataBase db,
ViewDefinition view,
FormattingCommandLineParameters parameters)
{
ViewGenerator viewGenerator = null;
if (view.mainControl is TableControlBody)
{
viewGenerator = new TableViewGenerator();
}
else if (view.mainControl is ListControlBody)
{
viewGenerator = new ListViewGenerator();
}
else if (view.mainControl is WideControlBody)
{
viewGenerator = new WideViewGenerator();
}
else if (view.mainControl is ComplexControlBody)
{
viewGenerator = new ComplexViewGenerator();
}
Diagnostics.Assert(viewGenerator != null, "viewGenerator != null");
viewGenerator.Initialize(errorContext, expressionFactory, db, view, parameters);
return viewGenerator;
}
private static ViewGenerator SelectViewGeneratorFromProperties(FormatShape shape, PSObject so,
TerminatingErrorContext errorContext,
PSPropertyExpressionFactory expressionFactory,
TypeInfoDataBase db,
FormattingCommandLineParameters parameters)
{
// use some heuristics to determine the shape if none is specified
if (shape == FormatShape.Undefined && parameters == null)
{
// check first if we have a known shape for a type
var typeNames = so.InternalTypeNames;
shape = DisplayDataQuery.GetShapeFromType(expressionFactory, db, typeNames);
if (shape == FormatShape.Undefined)
{
// check if we can have a table:
// we want to get the # of properties we are going to display
List<PSPropertyExpression> expressionList = PSObjectHelper.GetDefaultPropertySet(so);
if (expressionList.Count == 0)
{
// we failed to get anything from a property set
// we just get the first properties out of the first object
foreach (MshResolvedExpressionParameterAssociation mrepa in AssociationManager.ExpandAll(so))
{
expressionList.Add(mrepa.ResolvedExpression);
}
}
// decide what shape we want for the given number of properties
shape = DisplayDataQuery.GetShapeFromPropertyCount(db, expressionList.Count);
}
}
ViewGenerator viewGenerator = null;
if (shape == FormatShape.Table)
{
viewGenerator = new TableViewGenerator();
}
else if (shape == FormatShape.List)
{
viewGenerator = new ListViewGenerator();
}
else if (shape == FormatShape.Wide)
{
viewGenerator = new WideViewGenerator();
}
else if (shape == FormatShape.Complex)
{
viewGenerator = new ComplexViewGenerator();
}
Diagnostics.Assert(viewGenerator != null, "viewGenerator != null");
viewGenerator.Initialize(errorContext, expressionFactory, so, db, parameters);
return viewGenerator;
}
/// <summary>
/// The view generator that produced data for a selected shape.
/// </summary>
private ViewGenerator _viewGenerator = null;
}
/// <summary>
/// Class to manage the selection of a desired view type
/// for out of band objects.
/// </summary>
internal static class OutOfBandFormatViewManager
{
internal static bool IsPropertyLessObject(PSObject so)
{
List<MshResolvedExpressionParameterAssociation> allProperties = AssociationManager.ExpandAll(so);
if (allProperties.Count == 0)
{
return true;
}
if (allProperties.Count == 3)
{
foreach (MshResolvedExpressionParameterAssociation property in allProperties)
{
if (!property.ResolvedExpression.ToString().Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) &&
!property.ResolvedExpression.ToString().Equals(RemotingConstants.ShowComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) &&
!property.ResolvedExpression.ToString().Equals(RemotingConstants.RunspaceIdNoteProperty, StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
return true;
}
if (allProperties.Count == 4)
{
foreach (MshResolvedExpressionParameterAssociation property in allProperties)
{
if (!property.ResolvedExpression.ToString().Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) &&
!property.ResolvedExpression.ToString().Equals(RemotingConstants.ShowComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) &&
!property.ResolvedExpression.ToString().Equals(RemotingConstants.RunspaceIdNoteProperty, StringComparison.OrdinalIgnoreCase)
&& !property.ResolvedExpression.ToString().Equals(RemotingConstants.SourceJobInstanceId, StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
return true;
}
if (allProperties.Count == 5)
{
foreach (MshResolvedExpressionParameterAssociation property in allProperties)
{
if (!property.ResolvedExpression.ToString().Equals(RemotingConstants.ComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) &&
!property.ResolvedExpression.ToString().Equals(RemotingConstants.ShowComputerNameNoteProperty, StringComparison.OrdinalIgnoreCase) &&
!property.ResolvedExpression.ToString().Equals(RemotingConstants.RunspaceIdNoteProperty, StringComparison.OrdinalIgnoreCase) &&
!property.ResolvedExpression.ToString().Equals(RemotingConstants.SourceJobInstanceId, StringComparison.OrdinalIgnoreCase) &&
!property.ResolvedExpression.ToString().Equals(RemotingConstants.SourceLength, StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
return true;
}
return false;
}
internal static FormatEntryData GenerateOutOfBandData(TerminatingErrorContext errorContext, PSPropertyExpressionFactory expressionFactory,
TypeInfoDataBase db, PSObject so, int enumerationLimit, bool useToStringFallback, out List<ErrorRecord> errors)
{
errors = null;
var typeNames = so.InternalTypeNames;
ViewDefinition view = DisplayDataQuery.GetOutOfBandView(expressionFactory, db, typeNames);
ViewGenerator outOfBandViewGenerator;
if (view != null)
{
// process an out of band view retrieved from the display database
if (view.mainControl is ComplexControlBody)
{
outOfBandViewGenerator = new ComplexViewGenerator();
}
else
{
outOfBandViewGenerator = new ListViewGenerator();
}
outOfBandViewGenerator.Initialize(errorContext, expressionFactory, db, view, null);
}
else
{
if (DefaultScalarTypes.IsTypeInList(typeNames) ||
IsPropertyLessObject(so))
{
// we force a ToString() on well known types
return GenerateOutOfBandObjectAsToString(so);
}
if (!useToStringFallback)
{
return null;
}
// we must check we have enough properties for a list view
if (new PSPropertyExpression("*").ResolveNames(so).Count <= 0)
{
return null;
}
// we do not have a view, we default to list view
// process an out of band view as a default
outOfBandViewGenerator = new ListViewGenerator();
outOfBandViewGenerator.Initialize(errorContext, expressionFactory, so, db, null);
}
FormatEntryData fed = outOfBandViewGenerator.GeneratePayload(so, enumerationLimit);
fed.outOfBand = true;
fed.SetStreamTypeFromPSObject(so);
errors = outOfBandViewGenerator.ErrorManager.DrainFailedResultList();
return fed;
}
internal static FormatEntryData GenerateOutOfBandObjectAsToString(PSObject so)
{
FormatEntryData fed = new FormatEntryData();
fed.outOfBand = true;
RawTextFormatEntry rawTextEntry = new RawTextFormatEntry();
rawTextEntry.text = so.ToString();
fed.formatEntryInfo = rawTextEntry;
return fed;
}
}
/// <summary>
/// Helper class to manage the logging of errors resulting from
/// evaluations of PSPropertyExpression instances
///
/// Depending on settings, it queues the failing PSPropertyExpressionResult
/// instances and generates a list of out-of-band FormatEntryData
/// objects to be sent to the output pipeline.
/// </summary>
internal sealed class FormatErrorManager
{
internal FormatErrorManager(FormatErrorPolicy formatErrorPolicy)
{
_formatErrorPolicy = formatErrorPolicy;
}
/// <summary>
/// Log a failed evaluation of an PSPropertyExpression.
/// </summary>
/// <param name="result">PSPropertyExpressionResult containing the failed evaluation data.</param>
/// <param name="sourceObject">Object used to evaluate the PSPropertyExpression.</param>
internal void LogPSPropertyExpressionFailedResult(PSPropertyExpressionResult result, object sourceObject)
{
if (!_formatErrorPolicy.ShowErrorsAsMessages)
return;
PSPropertyExpressionError error = new PSPropertyExpressionError();
error.result = result;
error.sourceObject = sourceObject;
_formattingErrorList.Add(error);
}
/// <summary>
/// Log a failed formatting operation.
/// </summary>
/// <param name="error">String format error object.</param>
internal void LogStringFormatError(StringFormatError error)
{
if (!_formatErrorPolicy.ShowErrorsAsMessages)
return;
_formattingErrorList.Add(error);
}
internal bool DisplayErrorStrings
{
get { return _formatErrorPolicy.ShowErrorsInFormattedOutput; }
}
internal bool DisplayFormatErrorString
{
get
{
// NOTE: we key off the same flag
return this.DisplayErrorStrings;
}
}
internal string ErrorString
{
get { return _formatErrorPolicy.errorStringInFormattedOutput; }
}
internal string FormatErrorString
{
get { return _formatErrorPolicy.formatErrorStringInFormattedOutput; }
}
/// <summary>
/// Provide a list of ErrorRecord entries
/// to be written to the error pipeline and clear the list of pending
/// errors.
/// </summary>
/// <returns>List of ErrorRecord objects.</returns>
internal List<ErrorRecord> DrainFailedResultList()
{
if (!_formatErrorPolicy.ShowErrorsAsMessages)
return null;
List<ErrorRecord> retVal = new List<ErrorRecord>();
foreach (FormattingError error in _formattingErrorList)
{
ErrorRecord errorRecord = GenerateErrorRecord(error);
if (errorRecord != null)
retVal.Add(errorRecord);
}
_formattingErrorList.Clear();
return retVal;
}
/// <summary>
/// Conversion between an error internal representation and ErrorRecord.
/// </summary>
/// <param name="error">Internal error object.</param>
/// <returns>Corresponding ErrorRecord instance.</returns>
private static ErrorRecord GenerateErrorRecord(FormattingError error)
{
ErrorRecord errorRecord = null;
string msg = null;
PSPropertyExpressionError psPropertyExpressionError = error as PSPropertyExpressionError;
if (psPropertyExpressionError != null)
{
errorRecord = new ErrorRecord(
psPropertyExpressionError.result.Exception,
"PSPropertyExpressionError",
ErrorCategory.InvalidArgument,
psPropertyExpressionError.sourceObject);
msg = StringUtil.Format(FormatAndOut_format_xxx.PSPropertyExpressionError,
psPropertyExpressionError.result.ResolvedExpression.ToString());
errorRecord.ErrorDetails = new ErrorDetails(msg);
}
StringFormatError formattingError = error as StringFormatError;
if (formattingError != null)
{
errorRecord = new ErrorRecord(
formattingError.exception,
"formattingError",
ErrorCategory.InvalidArgument,
formattingError.sourceObject);
msg = StringUtil.Format(FormatAndOut_format_xxx.FormattingError,
formattingError.formatString);
errorRecord.ErrorDetails = new ErrorDetails(msg);
}
return errorRecord;
}
private FormatErrorPolicy _formatErrorPolicy;
/// <summary>
/// Current list of failed PSPropertyExpression evaluations.
/// </summary>
private List<FormattingError> _formattingErrorList = new List<FormattingError>();
}
}
| |
using SimpleJson;
using System;
using System.Security.Cryptography;
using System.Text;
using UnityEngine;
namespace Pomelo.DotNetClient
{
public class Protocol
{
private MessageProtocol messageProtocol;
private ProtocolState state;
private Transporter transporter;
private HandShakeService handshake;
private HeartBeatService heartBeatService = null;
private PomeloClient pc;
private RSACryptoServiceProvider provider = new RSACryptoServiceProvider(512);
public Protocol(PomeloClient pc, System.Net.Sockets.Socket socket)
{
this.pc = pc;
this.transporter = new Transporter(socket, this.ProcessMessage);
this.transporter.onDisconnect = this.OnDisconnect;
this.handshake = new HandShakeService(this);
this.state = ProtocolState.start;
}
public PomeloClient GetPomeloClient()
{
return this.pc;
}
public void Start(JsonObject user, Action<JsonObject> callback)
{
this.transporter.Start();
this.handshake.Request(user, callback);
this.state = ProtocolState.handshaking;
}
// Send notify, do not need id
public void Send(string route, JsonObject msg)
{
this.Send(route, 0, msg);
}
// Send request, user request id
public void Send(string route, uint id, JsonObject msg)
{
if (this.state != ProtocolState.working)
{
return;
}
byte[] body = this.messageProtocol.Encode(route, id, msg);
this.Send(PackageType.PKG_DATA, body);
}
public string ToHexString(byte[] bytes) // 0xae00cf => "AE00CF "
{
string hexString = string.Empty;
if (bytes != null)
{
StringBuilder strB = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
strB.Append(bytes[i].ToString("x2"));
}
hexString = strB.ToString();
}
return hexString;
}
public void Send(PackageType type)
{
if (this.state == ProtocolState.closed)
{
return;
}
this.transporter.Send(PackageProtocol.Encode(type));
}
// Send system message, these message do not use messageProtocol
public void Send(PackageType type, JsonObject msg)
{
// This method only used to send system package
if (type == PackageType.PKG_DATA)
{
return;
}
byte[] body = Encoding.UTF8.GetBytes(msg.ToString());
this.Send(type, body);
}
// Send message use the transporter
public void Send(PackageType type, byte[] body)
{
if (this.state == ProtocolState.closed)
{
return;
}
byte[] pkg = PackageProtocol.Encode(type, body);
this.transporter.Send(pkg);
}
public RSACryptoServiceProvider GetRsaProvide()
{
return this.provider;
}
// Invoke by Transporter, process the message
public void ProcessMessage(byte[] bytes)
{
Package pkg = PackageProtocol.Decode(bytes);
Loom.DispatchToMainThread(() =>
{
// Ignore all the message except handshading at handshake stage
if (pkg.Type == PackageType.PKG_HANDSHAKE && this.state == ProtocolState.handshaking)
{
// Ignore all the message except handshading
JsonObject data = (JsonObject)SimpleJson.SimpleJson.DeserializeObject(Encoding.UTF8.GetString(pkg.Body));
this.ProcessHandshakeData(data);
this.state = ProtocolState.working;
}
else if (pkg.Type == PackageType.PKG_HEARTBEAT && this.state == ProtocolState.working)
{
this.heartBeatService.ResetTimeout();
}
else if (pkg.Type == PackageType.PKG_DATA && this.state == ProtocolState.working)
{
this.heartBeatService.ResetTimeout();
this.pc.ProcessMessage(this.messageProtocol.Decode(pkg.Body));
}
else if (pkg.Type == PackageType.PKG_KICK)
{
this.GetPomeloClient().Kick();
this.Close();
}
});
}
public void Close()
{
this.transporter.Close();
if (this.heartBeatService != null)
{
this.heartBeatService.Stop();
}
this.state = ProtocolState.closed;
}
private void ProcessHandshakeData(JsonObject msg)
{
// Handshake error
if (!msg.ContainsKey("code") || !msg.ContainsKey("sys") || Convert.ToInt32(msg["code"]) != 200)
{
throw new Exception("Handshake error! Please check your handshake config.");
}
// Set compress data
JsonObject sys = (JsonObject)msg["sys"];
JsonObject dict = new JsonObject();
if (sys.ContainsKey("useDict"))
{
if (sys.ContainsKey("dict"))
{
dict = (JsonObject)sys["dict"];
PlayerPrefs.SetString("PomeloDict", dict.ToString());
}
else
{
dict = SimpleJson.SimpleJson.DeserializeObject<JsonObject>(PlayerPrefs.GetString("PomeloDict"));
}
}
JsonObject protos = new JsonObject();
JsonObject serverProtos = new JsonObject();
JsonObject clientProtos = new JsonObject();
if (sys.ContainsKey("useProto"))
{
if (sys.ContainsKey("protos"))
{
protos = (JsonObject)sys["protos"];
serverProtos = (JsonObject)protos["server"];
clientProtos = (JsonObject)protos["client"];
PlayerPrefs.SetString("PomeloServerProtos", serverProtos.ToString());
PlayerPrefs.SetString("PomeloClientProtos", clientProtos.ToString());
}
else
{
serverProtos = SimpleJson.SimpleJson.DeserializeObject<JsonObject>(PlayerPrefs.GetString("PomeloServerProtos"));
clientProtos = SimpleJson.SimpleJson.DeserializeObject<JsonObject>(PlayerPrefs.GetString("PomeloClientProtos"));
}
}
this.messageProtocol = new MessageProtocol(dict, serverProtos, clientProtos);
// Init heartbeat service
int interval = 0;
if (sys.ContainsKey("heartbeat"))
{
interval = Convert.ToInt32(sys["heartbeat"]);
}
this.heartBeatService = new HeartBeatService(interval, this);
if (interval > 0)
{
this.heartBeatService.Start();
}
// send ack and change protocol state
this.handshake.Ack();
this.state = ProtocolState.working;
// Invoke handshake callback
JsonObject user = new JsonObject();
if (msg.ContainsKey("user"))
{
user = (JsonObject)msg["user"];
}
this.handshake.InvokeCallback(user);
}
// The socket disconnect
private void OnDisconnect()
{
this.pc.Disconnect();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Orders;
using Nop.Services.Catalog;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Events;
using Nop.Services.Localization;
using Nop.Services.Security;
using Nop.Services.Stores;
namespace Nop.Services.Orders
{
/// <summary>
/// Shopping cart service
/// </summary>
public partial class ShoppingCartService : IShoppingCartService
{
#region Fields
private readonly IRepository<ShoppingCartItem> _sciRepository;
private readonly IWorkContext _workContext;
private readonly IStoreContext _storeContext;
private readonly ICurrencyService _currencyService;
private readonly IProductService _productService;
private readonly ILocalizationService _localizationService;
private readonly IProductAttributeParser _productAttributeParser;
private readonly ICheckoutAttributeService _checkoutAttributeService;
private readonly ICheckoutAttributeParser _checkoutAttributeParser;
private readonly IPriceFormatter _priceFormatter;
private readonly ICustomerService _customerService;
private readonly ShoppingCartSettings _shoppingCartSettings;
private readonly IEventPublisher _eventPublisher;
private readonly IPermissionService _permissionService;
private readonly IAclService _aclService;
private readonly IStoreMappingService _storeMappingService;
private readonly IGenericAttributeService _genericAttributeService;
private readonly IProductAttributeService _productAttributeService;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="sciRepository">Shopping cart repository</param>
/// <param name="workContext">Work context</param>
/// <param name="storeContext">Store context</param>
/// <param name="currencyService">Currency service</param>
/// <param name="productService">Product settings</param>
/// <param name="localizationService">Localization service</param>
/// <param name="productAttributeParser">Product attribute parser</param>
/// <param name="checkoutAttributeService">Checkout attribute service</param>
/// <param name="checkoutAttributeParser">Checkout attribute parser</param>
/// <param name="priceFormatter">Price formatter</param>
/// <param name="customerService">Customer service</param>
/// <param name="shoppingCartSettings">Shopping cart settings</param>
/// <param name="eventPublisher">Event publisher</param>
/// <param name="permissionService">Permission service</param>
/// <param name="aclService">ACL service</param>
/// <param name="storeMappingService">Store mapping service</param>
/// <param name="genericAttributeService">Generic attribute service</param>
/// <param name="productAttributeService">Product attribute service</param>
public ShoppingCartService(IRepository<ShoppingCartItem> sciRepository,
IWorkContext workContext, IStoreContext storeContext,
ICurrencyService currencyService,
IProductService productService, ILocalizationService localizationService,
IProductAttributeParser productAttributeParser,
ICheckoutAttributeService checkoutAttributeService,
ICheckoutAttributeParser checkoutAttributeParser,
IPriceFormatter priceFormatter,
ICustomerService customerService,
ShoppingCartSettings shoppingCartSettings,
IEventPublisher eventPublisher,
IPermissionService permissionService,
IAclService aclService,
IStoreMappingService storeMappingService,
IGenericAttributeService genericAttributeService,
IProductAttributeService productAttributeService)
{
this._sciRepository = sciRepository;
this._workContext = workContext;
this._storeContext = storeContext;
this._currencyService = currencyService;
this._productService = productService;
this._localizationService = localizationService;
this._productAttributeParser = productAttributeParser;
this._checkoutAttributeService = checkoutAttributeService;
this._checkoutAttributeParser = checkoutAttributeParser;
this._priceFormatter = priceFormatter;
this._customerService = customerService;
this._shoppingCartSettings = shoppingCartSettings;
this._eventPublisher = eventPublisher;
this._permissionService = permissionService;
this._aclService = aclService;
this._storeMappingService = storeMappingService;
this._genericAttributeService = genericAttributeService;
this._productAttributeService = productAttributeService;
}
#endregion
#region Methods
/// <summary>
/// Delete shopping cart item
/// </summary>
/// <param name="shoppingCartItem">Shopping cart item</param>
/// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param>
/// <param name="ensureOnlyActiveCheckoutAttributes">A value indicating whether to ensure that only active checkout attributes are attached to the current customer</param>
public virtual void DeleteShoppingCartItem(ShoppingCartItem shoppingCartItem, bool resetCheckoutData = true,
bool ensureOnlyActiveCheckoutAttributes = false)
{
if (shoppingCartItem == null)
throw new ArgumentNullException("shoppingCartItem");
var customer = shoppingCartItem.Customer;
var storeId = shoppingCartItem.StoreId;
//reset checkout data
if (resetCheckoutData)
{
_customerService.ResetCheckoutData(shoppingCartItem.Customer, shoppingCartItem.StoreId);
}
//delete item
_sciRepository.Delete(shoppingCartItem);
//reset "HasShoppingCartItems" property used for performance optimization
customer.HasShoppingCartItems = customer.ShoppingCartItems.Count > 0;
_customerService.UpdateCustomer(customer);
//validate checkout attributes
if (ensureOnlyActiveCheckoutAttributes &&
//only for shopping cart items (ignore wishlist)
shoppingCartItem.ShoppingCartType == ShoppingCartType.ShoppingCart)
{
var cart = customer.ShoppingCartItems
.Where(x => x.ShoppingCartType == ShoppingCartType.ShoppingCart)
.LimitPerStore(storeId)
.ToList();
var checkoutAttributesXml = customer.GetAttribute<string>(SystemCustomerAttributeNames.CheckoutAttributes, _genericAttributeService, storeId);
checkoutAttributesXml = _checkoutAttributeParser.EnsureOnlyActiveAttributes(checkoutAttributesXml, cart);
_genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.CheckoutAttributes, checkoutAttributesXml, storeId);
}
//event notification
_eventPublisher.EntityDeleted(shoppingCartItem);
}
/// <summary>
/// Deletes expired shopping cart items
/// </summary>
/// <param name="olderThanUtc">Older than date and time</param>
/// <returns>Number of deleted items</returns>
public virtual int DeleteExpiredShoppingCartItems(DateTime olderThanUtc)
{
var query = from sci in _sciRepository.Table
where sci.UpdatedOnUtc < olderThanUtc
select sci;
var cartItems = query.ToList();
foreach (var cartItem in cartItems)
_sciRepository.Delete(cartItem);
return cartItems.Count;
}
/// <summary>
/// Validates required products (products which require some other products to be added to the cart)
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="product">Product</param>
/// <param name="storeId">Store identifier</param>
/// <param name="automaticallyAddRequiredProductsIfEnabled">Automatically add required products if enabled</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetRequiredProductWarnings(Customer customer,
ShoppingCartType shoppingCartType, Product product,
int storeId, bool automaticallyAddRequiredProductsIfEnabled)
{
if (customer == null)
throw new ArgumentNullException("customer");
if (product == null)
throw new ArgumentNullException("product");
var cart = customer.ShoppingCartItems
.Where(sci => sci.ShoppingCartType == shoppingCartType)
.LimitPerStore(storeId)
.ToList();
var warnings = new List<string>();
if (product.RequireOtherProducts)
{
var requiredProducts = new List<Product>();
foreach (var id in product.ParseRequiredProductIds())
{
var rp = _productService.GetProductById(id);
if (rp != null)
requiredProducts.Add(rp);
}
foreach (var rp in requiredProducts)
{
//ensure that product is in the cart
bool alreadyInTheCart = false;
foreach (var sci in cart)
{
if (sci.ProductId == rp.Id)
{
alreadyInTheCart = true;
break;
}
}
//not in the cart
if (!alreadyInTheCart)
{
if (product.AutomaticallyAddRequiredProducts)
{
//add to cart (if possible)
if (automaticallyAddRequiredProductsIfEnabled)
{
//pass 'false' for 'automaticallyAddRequiredProductsIfEnabled' to prevent circular references
var addToCartWarnings = AddToCart(customer: customer,
product: rp,
shoppingCartType: shoppingCartType,
storeId: storeId,
automaticallyAddRequiredProductsIfEnabled: false);
if (addToCartWarnings.Count > 0)
{
//a product wasn't atomatically added for some reasons
//don't display specific errors from 'addToCartWarnings' variable
//display only generic error
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.RequiredProductWarning"), rp.GetLocalized(x => x.Name)));
}
}
else
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.RequiredProductWarning"), rp.GetLocalized(x => x.Name)));
}
}
else
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.RequiredProductWarning"), rp.GetLocalized(x => x.Name)));
}
}
}
}
return warnings;
}
/// <summary>
/// Validates a product for standard properties
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="product">Product</param>
/// <param name="attributesXml">Attributes in XML format</param>
/// <param name="customerEnteredPrice">Customer entered price</param>
/// <param name="quantity">Quantity</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetStandardWarnings(Customer customer, ShoppingCartType shoppingCartType,
Product product, string attributesXml, decimal customerEnteredPrice,
int quantity)
{
if (customer == null)
throw new ArgumentNullException("customer");
if (product == null)
throw new ArgumentNullException("product");
var warnings = new List<string>();
//deleted
if (product.Deleted)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.ProductDeleted"));
return warnings;
}
//published
if (!product.Published)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.ProductUnpublished"));
}
//we can add only simple products
if (product.ProductType != ProductType.SimpleProduct)
{
warnings.Add("This is not simple product");
}
//ACL
if (!_aclService.Authorize(product, customer))
{
warnings.Add(_localizationService.GetResource("ShoppingCart.ProductUnpublished"));
}
//Store mapping
if (!_storeMappingService.Authorize(product, _storeContext.CurrentStore.Id))
{
warnings.Add(_localizationService.GetResource("ShoppingCart.ProductUnpublished"));
}
//disabled "add to cart" button
if (shoppingCartType == ShoppingCartType.ShoppingCart && product.DisableBuyButton)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.BuyingDisabled"));
}
//disabled "add to wishlist" button
if (shoppingCartType == ShoppingCartType.Wishlist && product.DisableWishlistButton)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.WishlistDisabled"));
}
//call for price
if (shoppingCartType == ShoppingCartType.ShoppingCart && product.CallForPrice)
{
warnings.Add(_localizationService.GetResource("Products.CallForPrice"));
}
//customer entered price
if (product.CustomerEntersPrice)
{
if (customerEnteredPrice < product.MinimumCustomerEnteredPrice ||
customerEnteredPrice > product.MaximumCustomerEnteredPrice)
{
decimal minimumCustomerEnteredPrice = _currencyService.ConvertFromPrimaryStoreCurrency(product.MinimumCustomerEnteredPrice, _workContext.WorkingCurrency);
decimal maximumCustomerEnteredPrice = _currencyService.ConvertFromPrimaryStoreCurrency(product.MaximumCustomerEnteredPrice, _workContext.WorkingCurrency);
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.CustomerEnteredPrice.RangeError"),
_priceFormatter.FormatPrice(minimumCustomerEnteredPrice, false, false),
_priceFormatter.FormatPrice(maximumCustomerEnteredPrice, false, false)));
}
}
//quantity validation
var hasQtyWarnings = false;
if (quantity < product.OrderMinimumQuantity)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MinimumQuantity"), product.OrderMinimumQuantity));
hasQtyWarnings = true;
}
if (quantity > product.OrderMaximumQuantity)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MaximumQuantity"), product.OrderMaximumQuantity));
hasQtyWarnings = true;
}
var allowedQuantities = product.ParseAllowedQuatities();
if (allowedQuantities.Length > 0 && !allowedQuantities.Contains(quantity))
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.AllowedQuantities"), string.Join(", ", allowedQuantities)));
}
var validateOutOfStock = shoppingCartType == ShoppingCartType.ShoppingCart || !_shoppingCartSettings.AllowOutOfStockItemsToBeAddedToWishlist;
if (validateOutOfStock && !hasQtyWarnings)
{
switch (product.ManageInventoryMethod)
{
case ManageInventoryMethod.DontManageStock:
{
//do nothing
}
break;
case ManageInventoryMethod.ManageStock:
{
if (product.BackorderMode == BackorderMode.NoBackorders)
{
int maximumQuantityCanBeAdded = product.GetTotalStockQuantity();
if (maximumQuantityCanBeAdded < quantity)
{
if (maximumQuantityCanBeAdded <= 0)
warnings.Add(_localizationService.GetResource("ShoppingCart.OutOfStock"));
else
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.QuantityExceedsStock"), maximumQuantityCanBeAdded));
}
}
}
break;
case ManageInventoryMethod.ManageStockByAttributes:
{
var combination = product
.ProductAttributeCombinations
.FirstOrDefault(x => _productAttributeParser.AreProductAttributesEqual(x.AttributesXml, attributesXml));
if (combination != null)
{
//combination exists
//let's check stock level
if (!combination.AllowOutOfStockOrders && combination.StockQuantity < quantity)
{
int maximumQuantityCanBeAdded = combination.StockQuantity;
if (maximumQuantityCanBeAdded <= 0)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.OutOfStock"));
}
else
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.QuantityExceedsStock"), maximumQuantityCanBeAdded));
}
}
}
else
{
//combination doesn't exist
if (product.AllowAddingOnlyExistingAttributeCombinations)
{
//maybe, is it better to display something like "No such product/combination" message?
warnings.Add(_localizationService.GetResource("ShoppingCart.OutOfStock"));
}
}
}
break;
default:
break;
}
}
//availability dates
bool availableStartDateError = false;
if (product.AvailableStartDateTimeUtc.HasValue)
{
DateTime now = DateTime.UtcNow;
DateTime availableStartDateTime = DateTime.SpecifyKind(product.AvailableStartDateTimeUtc.Value, DateTimeKind.Utc);
if (availableStartDateTime.CompareTo(now) > 0)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.NotAvailable"));
availableStartDateError = true;
}
}
if (product.AvailableEndDateTimeUtc.HasValue && !availableStartDateError)
{
DateTime now = DateTime.UtcNow;
DateTime availableEndDateTime = DateTime.SpecifyKind(product.AvailableEndDateTimeUtc.Value, DateTimeKind.Utc);
if (availableEndDateTime.CompareTo(now) < 0)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.NotAvailable"));
}
}
return warnings;
}
/// <summary>
/// Validates shopping cart item attributes
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="product">Product</param>
/// <param name="quantity">Quantity</param>
/// <param name="attributesXml">Attributes in XML format</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetShoppingCartItemAttributeWarnings(Customer customer,
ShoppingCartType shoppingCartType,
Product product,
int quantity = 1,
string attributesXml = "")
{
if (product == null)
throw new ArgumentNullException("product");
var warnings = new List<string>();
//ensure it's our attributes
var attributes1 = _productAttributeParser.ParseProductAttributeMappings(attributesXml);
foreach (var attribute in attributes1)
{
if (attribute.Product != null)
{
if (attribute.Product.Id != product.Id)
{
warnings.Add("Attribute error");
}
}
else
{
warnings.Add("Attribute error");
return warnings;
}
}
//validate required product attributes (whether they're chosen/selected/entered)
var attributes2 = _productAttributeService.GetProductAttributeMappingsByProductId(product.Id);
foreach (var a2 in attributes2)
{
if (a2.IsRequired)
{
bool found = false;
//selected product attributes
foreach (var a1 in attributes1)
{
if (a1.Id == a2.Id)
{
var attributeValuesStr = _productAttributeParser.ParseValues(attributesXml, a1.Id);
foreach (string str1 in attributeValuesStr)
{
if (!String.IsNullOrEmpty(str1.Trim()))
{
found = true;
break;
}
}
}
}
//if not found
if (!found)
{
var notFoundWarning = !string.IsNullOrEmpty(a2.TextPrompt) ?
a2.TextPrompt :
string.Format(_localizationService.GetResource("ShoppingCart.SelectAttribute"), a2.ProductAttribute.GetLocalized(a => a.Name));
warnings.Add(notFoundWarning);
}
}
if (a2.AttributeControlType == AttributeControlType.ReadonlyCheckboxes)
{
//customers cannot edit read-only attributes
var allowedReadOnlyValueIds = _productAttributeService.GetProductAttributeValues(a2.Id)
.Where(x => x.IsPreSelected)
.Select(x => x.Id)
.ToArray();
var selectedReadOnlyValueIds = _productAttributeParser.ParseProductAttributeValues(attributesXml)
.Where(x => x.ProductAttributeMappingId == a2.Id)
.Select(x => x.Id)
.ToArray();
if (!CommonHelper.ArraysEqual(allowedReadOnlyValueIds, selectedReadOnlyValueIds))
{
warnings.Add("You cannot change read-only values");
}
}
}
//validation rules
foreach (var pam in attributes2)
{
if (!pam.ValidationRulesAllowed())
continue;
//minimum length
if (pam.ValidationMinLength.HasValue)
{
if (pam.AttributeControlType == AttributeControlType.TextBox ||
pam.AttributeControlType == AttributeControlType.MultilineTextbox)
{
var valuesStr = _productAttributeParser.ParseValues(attributesXml, pam.Id);
var enteredText = valuesStr.FirstOrDefault();
int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;
if (pam.ValidationMinLength.Value > enteredTextLength)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.TextboxMinimumLength"), pam.ProductAttribute.GetLocalized(a => a.Name), pam.ValidationMinLength.Value));
}
}
}
//maximum length
if (pam.ValidationMaxLength.HasValue)
{
if (pam.AttributeControlType == AttributeControlType.TextBox ||
pam.AttributeControlType == AttributeControlType.MultilineTextbox)
{
var valuesStr = _productAttributeParser.ParseValues(attributesXml, pam.Id);
var enteredText = valuesStr.FirstOrDefault();
int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;
if (pam.ValidationMaxLength.Value < enteredTextLength)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.TextboxMaximumLength"), pam.ProductAttribute.GetLocalized(a => a.Name), pam.ValidationMaxLength.Value));
}
}
}
}
if (warnings.Count > 0)
return warnings;
//validate bundled products
var attributeValues = _productAttributeParser.ParseProductAttributeValues(attributesXml);
foreach (var attributeValue in attributeValues)
{
if (attributeValue.AttributeValueType == AttributeValueType.AssociatedToProduct)
{
//associated product (bundle)
var associatedProduct = _productService.GetProductById(attributeValue.AssociatedProductId);
if (associatedProduct != null)
{
var totalQty = quantity * attributeValue.Quantity;
var associatedProductWarnings = GetShoppingCartItemWarnings(customer,
shoppingCartType, associatedProduct, _storeContext.CurrentStore.Id,
"", decimal.Zero, null, null, totalQty, false);
foreach (var associatedProductWarning in associatedProductWarnings)
{
var attributeName = attributeValue.ProductAttributeMapping.ProductAttribute.GetLocalized(a => a.Name);
var attributeValueName = attributeValue.GetLocalized(a => a.Name);
warnings.Add(
string.Format(
_localizationService.GetResource("ShoppingCart.AssociatedAttributeWarning"), attributeName,
attributeValueName, associatedProductWarning));
}
}
else
{
warnings.Add(string.Format("Associated product cannot be loaded - {0}",
attributeValue.AssociatedProductId));
}
}
}
return warnings;
}
/// <summary>
/// Validates shopping cart item (gift card)
/// </summary>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="product">Product</param>
/// <param name="attributesXml">Attributes in XML format</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetShoppingCartItemGiftCardWarnings(ShoppingCartType shoppingCartType,
Product product, string attributesXml)
{
if (product == null)
throw new ArgumentNullException("product");
var warnings = new List<string>();
//gift cards
if (product.IsGiftCard)
{
string giftCardRecipientName;
string giftCardRecipientEmail;
string giftCardSenderName;
string giftCardSenderEmail;
string giftCardMessage;
_productAttributeParser.GetGiftCardAttribute(attributesXml,
out giftCardRecipientName, out giftCardRecipientEmail,
out giftCardSenderName, out giftCardSenderEmail, out giftCardMessage);
if (String.IsNullOrEmpty(giftCardRecipientName))
warnings.Add(_localizationService.GetResource("ShoppingCart.RecipientNameError"));
if (product.GiftCardType == GiftCardType.Virtual)
{
//validate for virtual gift cards only
if (String.IsNullOrEmpty(giftCardRecipientEmail) || !CommonHelper.IsValidEmail(giftCardRecipientEmail))
warnings.Add(_localizationService.GetResource("ShoppingCart.RecipientEmailError"));
}
if (String.IsNullOrEmpty(giftCardSenderName))
warnings.Add(_localizationService.GetResource("ShoppingCart.SenderNameError"));
if (product.GiftCardType == GiftCardType.Virtual)
{
//validate for virtual gift cards only
if (String.IsNullOrEmpty(giftCardSenderEmail) || !CommonHelper.IsValidEmail(giftCardSenderEmail))
warnings.Add(_localizationService.GetResource("ShoppingCart.SenderEmailError"));
}
}
return warnings;
}
/// <summary>
/// Validates shopping cart item for rental products
/// </summary>
/// <param name="product">Product</param>
/// <param name="rentalStartDate">Rental start date</param>
/// <param name="rentalEndDate">Rental end date</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetRentalProductWarnings(Product product,
DateTime? rentalStartDate = null, DateTime? rentalEndDate = null)
{
if (product == null)
throw new ArgumentNullException("product");
var warnings = new List<string>();
if (!product.IsRental)
return warnings;
if (!rentalStartDate.HasValue)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.Rental.EnterStartDate"));
return warnings;
}
if (!rentalEndDate.HasValue)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.Rental.EnterEndDate"));
return warnings;
}
if (rentalStartDate.Value.CompareTo(rentalEndDate.Value) > 0)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.Rental.StartDateLessEndDate"));
return warnings;
}
//compare with current time?
return warnings;
}
/// <summary>
/// Validates shopping cart item
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="product">Product</param>
/// <param name="storeId">Store identifier</param>
/// <param name="attributesXml">Attributes in XML format</param>
/// <param name="customerEnteredPrice">Customer entered price</param>
/// <param name="rentalStartDate">Rental start date</param>
/// <param name="rentalEndDate">Rental end date</param>
/// <param name="quantity">Quantity</param>
/// <param name="automaticallyAddRequiredProductsIfEnabled">Automatically add required products if enabled</param>
/// <param name="getStandardWarnings">A value indicating whether we should validate a product for standard properties</param>
/// <param name="getAttributesWarnings">A value indicating whether we should validate product attributes</param>
/// <param name="getGiftCardWarnings">A value indicating whether we should validate gift card properties</param>
/// <param name="getRequiredProductWarnings">A value indicating whether we should validate required products (products which require other products to be added to the cart)</param>
/// <param name="getRentalWarnings">A value indicating whether we should validate rental properties</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetShoppingCartItemWarnings(Customer customer, ShoppingCartType shoppingCartType,
Product product, int storeId,
string attributesXml, decimal customerEnteredPrice,
DateTime? rentalStartDate = null, DateTime? rentalEndDate = null,
int quantity = 1, bool automaticallyAddRequiredProductsIfEnabled = true,
bool getStandardWarnings = true, bool getAttributesWarnings = true,
bool getGiftCardWarnings = true, bool getRequiredProductWarnings = true,
bool getRentalWarnings = true)
{
if (product == null)
throw new ArgumentNullException("product");
var warnings = new List<string>();
//standard properties
if (getStandardWarnings)
warnings.AddRange(GetStandardWarnings(customer, shoppingCartType, product, attributesXml, customerEnteredPrice, quantity));
//selected attributes
if (getAttributesWarnings)
warnings.AddRange(GetShoppingCartItemAttributeWarnings(customer, shoppingCartType, product, quantity, attributesXml));
//gift cards
if (getGiftCardWarnings)
warnings.AddRange(GetShoppingCartItemGiftCardWarnings(shoppingCartType, product, attributesXml));
//required products
if (getRequiredProductWarnings)
warnings.AddRange(GetRequiredProductWarnings(customer, shoppingCartType, product, storeId, automaticallyAddRequiredProductsIfEnabled));
//rental products
if (getRentalWarnings)
warnings.AddRange(GetRentalProductWarnings(product, rentalStartDate, rentalEndDate));
return warnings;
}
/// <summary>
/// Validates whether this shopping cart is valid
/// </summary>
/// <param name="shoppingCart">Shopping cart</param>
/// <param name="checkoutAttributesXml">Checkout attributes in XML format</param>
/// <param name="validateCheckoutAttributes">A value indicating whether to validate checkout attributes</param>
/// <returns>Warnings</returns>
public virtual IList<string> GetShoppingCartWarnings(IList<ShoppingCartItem> shoppingCart,
string checkoutAttributesXml, bool validateCheckoutAttributes)
{
var warnings = new List<string>();
bool hasStandartProducts = false;
bool hasRecurringProducts = false;
foreach (var sci in shoppingCart)
{
var product = sci.Product;
if (product == null)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.CannotLoadProduct"), sci.ProductId));
return warnings;
}
if (product.IsRecurring)
hasRecurringProducts = true;
else
hasStandartProducts = true;
}
//don't mix standard and recurring products
if (hasStandartProducts && hasRecurringProducts)
warnings.Add(_localizationService.GetResource("ShoppingCart.CannotMixStandardAndAutoshipProducts"));
//recurring cart validation
if (hasRecurringProducts)
{
int cycleLength;
RecurringProductCyclePeriod cyclePeriod;
int totalCycles;
string cyclesError = shoppingCart.GetRecurringCycleInfo(_localizationService,
out cycleLength, out cyclePeriod, out totalCycles);
if (!string.IsNullOrEmpty(cyclesError))
{
warnings.Add(cyclesError);
return warnings;
}
}
//validate checkout attributes
if (validateCheckoutAttributes)
{
//selected attributes
var attributes1 = _checkoutAttributeParser.ParseCheckoutAttributes(checkoutAttributesXml);
//existing checkout attributes
var attributes2 = _checkoutAttributeService.GetAllCheckoutAttributes(_storeContext.CurrentStore.Id, !shoppingCart.RequiresShipping());
foreach (var a2 in attributes2)
{
if (a2.IsRequired)
{
bool found = false;
//selected checkout attributes
foreach (var a1 in attributes1)
{
if (a1.Id == a2.Id)
{
var attributeValuesStr = _checkoutAttributeParser.ParseValues(checkoutAttributesXml, a1.Id);
foreach (string str1 in attributeValuesStr)
if (!String.IsNullOrEmpty(str1.Trim()))
{
found = true;
break;
}
}
}
//if not found
if (!found)
{
if (!string.IsNullOrEmpty(a2.GetLocalized(a => a.TextPrompt)))
warnings.Add(a2.GetLocalized(a => a.TextPrompt));
else
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.SelectAttribute"), a2.GetLocalized(a => a.Name)));
}
}
}
//now validation rules
//minimum length
foreach (var ca in attributes2)
{
if (ca.ValidationMinLength.HasValue)
{
if (ca.AttributeControlType == AttributeControlType.TextBox ||
ca.AttributeControlType == AttributeControlType.MultilineTextbox)
{
var valuesStr = _checkoutAttributeParser.ParseValues(checkoutAttributesXml, ca.Id);
var enteredText = valuesStr.FirstOrDefault();
int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;
if (ca.ValidationMinLength.Value > enteredTextLength)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.TextboxMinimumLength"), ca.GetLocalized(a => a.Name), ca.ValidationMinLength.Value));
}
}
}
//maximum length
if (ca.ValidationMaxLength.HasValue)
{
if (ca.AttributeControlType == AttributeControlType.TextBox ||
ca.AttributeControlType == AttributeControlType.MultilineTextbox)
{
var valuesStr = _checkoutAttributeParser.ParseValues(checkoutAttributesXml, ca.Id);
var enteredText = valuesStr.FirstOrDefault();
int enteredTextLength = String.IsNullOrEmpty(enteredText) ? 0 : enteredText.Length;
if (ca.ValidationMaxLength.Value < enteredTextLength)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.TextboxMaximumLength"), ca.GetLocalized(a => a.Name), ca.ValidationMaxLength.Value));
}
}
}
}
}
return warnings;
}
/// <summary>
/// Finds a shopping cart item in the cart
/// </summary>
/// <param name="shoppingCart">Shopping cart</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="product">Product</param>
/// <param name="attributesXml">Attributes in XML format</param>
/// <param name="customerEnteredPrice">Price entered by a customer</param>
/// <param name="rentalStartDate">Rental start date</param>
/// <param name="rentalEndDate">Rental end date</param>
/// <returns>Found shopping cart item</returns>
public virtual ShoppingCartItem FindShoppingCartItemInTheCart(IList<ShoppingCartItem> shoppingCart,
ShoppingCartType shoppingCartType,
Product product,
string attributesXml = "",
decimal customerEnteredPrice = decimal.Zero,
DateTime? rentalStartDate = null,
DateTime? rentalEndDate = null)
{
if (shoppingCart == null)
throw new ArgumentNullException("shoppingCart");
if (product == null)
throw new ArgumentNullException("product");
foreach (var sci in shoppingCart.Where(a => a.ShoppingCartType == shoppingCartType))
{
if (sci.ProductId == product.Id)
{
//attributes
bool attributesEqual = _productAttributeParser.AreProductAttributesEqual(sci.AttributesXml, attributesXml);
//gift cards
bool giftCardInfoSame = true;
if (sci.Product.IsGiftCard)
{
string giftCardRecipientName1;
string giftCardRecipientEmail1;
string giftCardSenderName1;
string giftCardSenderEmail1;
string giftCardMessage1;
_productAttributeParser.GetGiftCardAttribute(attributesXml,
out giftCardRecipientName1, out giftCardRecipientEmail1,
out giftCardSenderName1, out giftCardSenderEmail1, out giftCardMessage1);
string giftCardRecipientName2;
string giftCardRecipientEmail2;
string giftCardSenderName2;
string giftCardSenderEmail2;
string giftCardMessage2;
_productAttributeParser.GetGiftCardAttribute(sci.AttributesXml,
out giftCardRecipientName2, out giftCardRecipientEmail2,
out giftCardSenderName2, out giftCardSenderEmail2, out giftCardMessage2);
if (giftCardRecipientName1.ToLowerInvariant() != giftCardRecipientName2.ToLowerInvariant() ||
giftCardSenderName1.ToLowerInvariant() != giftCardSenderName2.ToLowerInvariant())
giftCardInfoSame = false;
}
//price is the same (for products which require customers to enter a price)
bool customerEnteredPricesEqual = true;
if (sci.Product.CustomerEntersPrice)
customerEnteredPricesEqual = Math.Round(sci.CustomerEnteredPrice, 2) == Math.Round(customerEnteredPrice, 2);
//rental products
bool rentalInfoEqual = true;
if (sci.Product.IsRental)
{
rentalInfoEqual = sci.RentalStartDateUtc == rentalStartDate && sci.RentalEndDateUtc == rentalEndDate;
}
//found?
if (attributesEqual && giftCardInfoSame && customerEnteredPricesEqual && rentalInfoEqual)
return sci;
}
}
return null;
}
/// <summary>
/// Add a product to shopping cart
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="product">Product</param>
/// <param name="shoppingCartType">Shopping cart type</param>
/// <param name="storeId">Store identifier</param>
/// <param name="attributesXml">Attributes in XML format</param>
/// <param name="customerEnteredPrice">The price enter by a customer</param>
/// <param name="rentalStartDate">Rental start date</param>
/// <param name="rentalEndDate">Rental end date</param>
/// <param name="quantity">Quantity</param>
/// <param name="automaticallyAddRequiredProductsIfEnabled">Automatically add required products if enabled</param>
/// <returns>Warnings</returns>
public virtual IList<string> AddToCart(Customer customer, Product product,
ShoppingCartType shoppingCartType, int storeId, string attributesXml = null,
decimal customerEnteredPrice = decimal.Zero,
DateTime? rentalStartDate = null, DateTime? rentalEndDate = null,
int quantity = 1, bool automaticallyAddRequiredProductsIfEnabled = true)
{
if (customer == null)
throw new ArgumentNullException("customer");
if (product == null)
throw new ArgumentNullException("product");
var warnings = new List<string>();
if (shoppingCartType == ShoppingCartType.ShoppingCart && !_permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart, customer))
{
warnings.Add("Shopping cart is disabled");
return warnings;
}
if (shoppingCartType == ShoppingCartType.Wishlist && !_permissionService.Authorize(StandardPermissionProvider.EnableWishlist, customer))
{
warnings.Add("Wishlist is disabled");
return warnings;
}
if (customer.IsSearchEngineAccount())
{
warnings.Add("Search engine can't add to cart");
return warnings;
}
if (quantity <= 0)
{
warnings.Add(_localizationService.GetResource("ShoppingCart.QuantityShouldPositive"));
return warnings;
}
//reset checkout info
_customerService.ResetCheckoutData(customer, storeId);
var cart = customer.ShoppingCartItems
.Where(sci => sci.ShoppingCartType == shoppingCartType)
.LimitPerStore(storeId)
.ToList();
var shoppingCartItem = FindShoppingCartItemInTheCart(cart,
shoppingCartType, product, attributesXml, customerEnteredPrice,
rentalStartDate, rentalEndDate);
if (shoppingCartItem != null)
{
//update existing shopping cart item
int newQuantity = shoppingCartItem.Quantity + quantity;
warnings.AddRange(GetShoppingCartItemWarnings(customer, shoppingCartType, product,
storeId, attributesXml,
customerEnteredPrice, rentalStartDate, rentalEndDate,
newQuantity, automaticallyAddRequiredProductsIfEnabled));
if (warnings.Count == 0)
{
shoppingCartItem.AttributesXml = attributesXml;
shoppingCartItem.Quantity = newQuantity;
shoppingCartItem.UpdatedOnUtc = DateTime.UtcNow;
_customerService.UpdateCustomer(customer);
//event notification
_eventPublisher.EntityUpdated(shoppingCartItem);
}
}
else
{
//new shopping cart item
warnings.AddRange(GetShoppingCartItemWarnings(customer, shoppingCartType, product,
storeId, attributesXml, customerEnteredPrice,
rentalStartDate, rentalEndDate,
quantity, automaticallyAddRequiredProductsIfEnabled));
if (warnings.Count == 0)
{
//maximum items validation
switch (shoppingCartType)
{
case ShoppingCartType.ShoppingCart:
{
if (cart.Count >= _shoppingCartSettings.MaximumShoppingCartItems)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MaximumShoppingCartItems"), _shoppingCartSettings.MaximumShoppingCartItems));
return warnings;
}
}
break;
case ShoppingCartType.Wishlist:
{
if (cart.Count >= _shoppingCartSettings.MaximumWishlistItems)
{
warnings.Add(string.Format(_localizationService.GetResource("ShoppingCart.MaximumWishlistItems"), _shoppingCartSettings.MaximumWishlistItems));
return warnings;
}
}
break;
default:
break;
}
DateTime now = DateTime.UtcNow;
shoppingCartItem = new ShoppingCartItem
{
ShoppingCartType = shoppingCartType,
StoreId = storeId,
Product = product,
AttributesXml = attributesXml,
CustomerEnteredPrice = customerEnteredPrice,
Quantity = quantity,
RentalStartDateUtc = rentalStartDate,
RentalEndDateUtc = rentalEndDate,
CreatedOnUtc = now,
UpdatedOnUtc = now
};
customer.ShoppingCartItems.Add(shoppingCartItem);
_customerService.UpdateCustomer(customer);
//updated "HasShoppingCartItems" property used for performance optimization
customer.HasShoppingCartItems = customer.ShoppingCartItems.Count > 0;
_customerService.UpdateCustomer(customer);
//event notification
_eventPublisher.EntityInserted(shoppingCartItem);
}
}
return warnings;
}
/// <summary>
/// Updates the shopping cart item
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="shoppingCartItemId">Shopping cart item identifier</param>
/// <param name="attributesXml">Attributes in XML format</param>
/// <param name="customerEnteredPrice">New customer entered price</param>
/// <param name="rentalStartDate">Rental start date</param>
/// <param name="rentalEndDate">Rental end date</param>
/// <param name="quantity">New shopping cart item quantity</param>
/// <param name="resetCheckoutData">A value indicating whether to reset checkout data</param>
/// <returns>Warnings</returns>
public virtual IList<string> UpdateShoppingCartItem(Customer customer,
int shoppingCartItemId, string attributesXml,
decimal customerEnteredPrice,
DateTime? rentalStartDate = null, DateTime? rentalEndDate = null,
int quantity = 1, bool resetCheckoutData = true)
{
if (customer == null)
throw new ArgumentNullException("customer");
var warnings = new List<string>();
var shoppingCartItem = customer.ShoppingCartItems.FirstOrDefault(sci => sci.Id == shoppingCartItemId);
if (shoppingCartItem != null)
{
if (resetCheckoutData)
{
//reset checkout data
_customerService.ResetCheckoutData(customer, shoppingCartItem.StoreId);
}
if (quantity > 0)
{
//check warnings
warnings.AddRange(GetShoppingCartItemWarnings(customer, shoppingCartItem.ShoppingCartType,
shoppingCartItem.Product, shoppingCartItem.StoreId,
attributesXml, customerEnteredPrice,
rentalStartDate, rentalEndDate, quantity, false));
if (warnings.Count == 0)
{
//if everything is OK, then update a shopping cart item
shoppingCartItem.Quantity = quantity;
shoppingCartItem.AttributesXml = attributesXml;
shoppingCartItem.CustomerEnteredPrice = customerEnteredPrice;
shoppingCartItem.RentalStartDateUtc = rentalStartDate;
shoppingCartItem.RentalEndDateUtc = rentalEndDate;
shoppingCartItem.UpdatedOnUtc = DateTime.UtcNow;
_customerService.UpdateCustomer(customer);
//event notification
_eventPublisher.EntityUpdated(shoppingCartItem);
}
}
else
{
//delete a shopping cart item
DeleteShoppingCartItem(shoppingCartItem, resetCheckoutData, true);
}
}
return warnings;
}
/// <summary>
/// Migrate shopping cart
/// </summary>
/// <param name="fromCustomer">From customer</param>
/// <param name="toCustomer">To customer</param>
/// <param name="includeCouponCodes">A value indicating whether to coupon codes (discount and gift card) should be also re-applied</param>
public virtual void MigrateShoppingCart(Customer fromCustomer, Customer toCustomer, bool includeCouponCodes)
{
if (fromCustomer == null)
throw new ArgumentNullException("fromCustomer");
if (toCustomer == null)
throw new ArgumentNullException("toCustomer");
if (fromCustomer.Id == toCustomer.Id)
return; //the same customer
//shopping cart items
var fromCart = fromCustomer.ShoppingCartItems.ToList();
for (int i = 0; i < fromCart.Count; i++)
{
var sci = fromCart[i];
AddToCart(toCustomer, sci.Product, sci.ShoppingCartType, sci.StoreId,
sci.AttributesXml, sci.CustomerEnteredPrice,
sci.RentalStartDateUtc, sci.RentalEndDateUtc, sci.Quantity, false);
}
for (int i = 0; i < fromCart.Count; i++)
{
var sci = fromCart[i];
DeleteShoppingCartItem(sci);
}
//migrate gift card and discount coupon codes
if (includeCouponCodes)
{
//discount
var discountCouponCode = fromCustomer.GetAttribute<string>(SystemCustomerAttributeNames.DiscountCouponCode);
if (!String.IsNullOrEmpty(discountCouponCode))
_genericAttributeService.SaveAttribute(toCustomer, SystemCustomerAttributeNames.DiscountCouponCode, discountCouponCode);
//gift card
foreach (var gcCode in fromCustomer.ParseAppliedGiftCardCouponCodes())
toCustomer.ApplyGiftCardCouponCode(gcCode);
//save customer
_customerService.UpdateCustomer(toCustomer);
}
}
#endregion
}
}
| |
using System;
using System.Linq;
using SwinGameSDK;
using System.Collections.Generic;
using Arcadia.Emulator;
using System.IO;
using System.Diagnostics;
namespace Arcadia
{
public class GameMain
{
public static void Main()
{
Loader load = new Loader();
load.Start();
}
}
//Any magic numbers in this code are just guesses. your guess is as good as mine :')
public class Loader
{
private string _version;
private FontManager _manager;
private Marquee _topMarquee;
private DateTime _currentTime;
private List<Emu> _emulators;
private Bitmap _gameLogoBitmap;
private Bitmap _gameBack;
private int _selectedEmulator;
private bool _shouldUpdateData = true;
//Amount of items to skip in the game listing
private int _skip = 0;
public void Start()
{
//Initialize the log for Arcadia
Log.Initialize();
//Start up the window for Arcadia - if it's release version we want it to be full screen
#if RELEASE
SwinGame.OpenGraphicsWindow("Arcadia",
(int)System.Windows.SystemParameters.PrimaryScreenWidth,
(int)System.Windows.SystemParameters.PrimaryScreenHeight);
SwinGame.ToggleFullScreen();
#else
SwinGame.OpenGraphicsWindow("Arcadia", 1366, 768);
#endif
if (SwinGame.ScreenHeight() < 768 || SwinGame.ScreenWidth() < 1366)
{
Log.Write("Screen resolution too small...");
Environment.Exit(0);
}
//Get the version of the build to show on the marquee
_version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
//Initialize the font manager
_manager = new FontManager();
//Initialize the current time
_currentTime = DateTime.Now;
//Get the square to display the games on
var LogoPadding = 50;
_gameBack = SwinGame.LoadBitmap("back.png");
//Add 40 to the max size just to ensure some empty space before the list
Globals.LogoMaxSize = (SwinGame.ScreenHeight() - _gameBack.Height - 30) - LogoPadding - 40;
//Generate the emulators for the player to select
_emulators = Emu.GenerateEmulators();
//Initalize and update the marquee at the bottom of the window
_topMarquee = new Marquee("", _manager.GetFont("PressStart2P", 8), SwinGame.ScreenHeight() - 10);
UpdateMarquee();
RenderLoop(LogoPadding);
}
public void RenderLoop(int LogoPadding)
{
//Render loop while the user hasn't clicked the X button
while (!SwinGame.WindowCloseRequested())
{
//Process any key/joystick/mouse events
SwinGame.ProcessEvents();
//If the user presses escape exit the program
if (SwinGame.KeyDown(KeyCode.vk_ESCAPE))
Environment.Exit(0);
//Clear the screen with the defined background
SwinGame.ClearScreen(Globals.Background);
//Update the marquee if the second changes (we do this so it doesn't need to re-update every second)
if (_currentTime.Second != DateTime.Now.Second)
{
_currentTime = DateTime.Now;
UpdateMarquee();
}
var gameBackLoc = new Point2D()
{
X = (SwinGame.ScreenWidth() / 2) - (_gameBack.Width / 2),
Y = SwinGame.ScreenHeight() - _gameBack.Height - 50
};
SwinGame.DrawBitmap(_gameBack, gameBackLoc);
//Poor man's iterator while still having foreach
int i = 0;
//Go through each game in the selected emulator
foreach (Game game in _emulators[_selectedEmulator].Games.Skip(_skip).Take(12))
{
//Get the size of the text of the game
int TextWidth = SwinGame.TextWidth(_manager.GetFont("Geometria", 24), game.Name);
int TextHeight = SwinGame.TextHeight(_manager.GetFont("Geometria", 24), game.Name);
//Draw the text in the middle of the game rectangle. The rectangle has +30 pixels on the sides for the drop shadow so we compensate for that.
Point2D RenderLocation = new Point2D()
{
X = gameBackLoc.X + ((_gameBack.Width + 30) / 2) - (TextWidth / 2),
Y = gameBackLoc.Y + ((i * 35) + 20)
};
//Show the image and highlight the text if the game is selected
if (i == (_emulators[_selectedEmulator].SelectedGame - _skip))
{
//Only load bitmap into memory if the game changes
if (_shouldUpdateData)
{
_shouldUpdateData = false;
//Load the logo to memory if it exists
if (File.Exists(Path.Combine(game.DataDirectory, "logo.png")))
{
_gameLogoBitmap = SwinGame.LoadBitmap(Path.Combine(game.DataDirectory, "logo.png"));
}
else
{
_gameLogoBitmap = null;
}
}
//If we haven't loaded a bitmap, show a textual logo of the games name
if (_gameLogoBitmap == null)
{
//Ensure that the game's name fits on screen
string TruncatedName = game.Name.Substring(0, Math.Min(game.Name.Length, 16));
if (TruncatedName != game.Name)
TruncatedName += "...";
//Render the game logo on screen
int LogoTextWidth = SwinGame.TextWidth(_manager.GetFont("PressStart2P", 60), TruncatedName);
int LogoTextHeight = SwinGame.TextHeight(_manager.GetFont("PressStart2P", 60), TruncatedName);
SwinGame.DrawText(TruncatedName,
Globals.TextColor,
_manager.GetFont("PressStart2P", 60),
new Point2D()
{
X = (SwinGame.ScreenWidth() / 2) - (LogoTextWidth / 2),
Y = LogoPadding + (Globals.LogoMaxSize / 2) - (LogoTextHeight / 2)
});
}
else
{
//Draw the offical game logo to screen
SwinGame.DrawBitmap(_gameLogoBitmap,
new Point2D()
{
X = (SwinGame.ScreenWidth() / 2) - (_gameLogoBitmap.Width / 2),
Y = LogoPadding + (Globals.LogoMaxSize / 2) - (_gameLogoBitmap.Height / 2)
});
}
//Draw a rectangle around the selected item
SwinGame.FillRectangle(Globals.Marquee, RenderLocation.X - 4, RenderLocation.Y - 4, TextWidth + 8, TextHeight + 8);
//If the user presses enter, launch the game with the specified parameters.
if (SwinGame.KeyTyped(KeyCode.vk_RETURN))
{
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
WorkingDirectory = _emulators[_selectedEmulator].Location,
FileName = _emulators[_selectedEmulator].LaunchExecutable
}
};
proc.StartInfo.Arguments = _emulators[_selectedEmulator].LaunchArguments;
proc.StartInfo.Arguments = proc.StartInfo.Arguments.Replace("{Filename}", Path.GetFileName(_emulators[_selectedEmulator].Games[_emulators[_selectedEmulator].SelectedGame].Location)).Replace(
"{Fullpath}", Path.GetFullPath(_emulators[_selectedEmulator].Games[_emulators[_selectedEmulator].SelectedGame].Location));
proc.Start();
}
}
//Draw the games into the list
SwinGame.DrawText(game.Name, Globals.TextColor, _manager.GetFont("Geometria", 24), RenderLocation);
i += 1;
}
//Draws the scrollbar track on the side
SwinGame.FillRectangle(Globals.ScrollBarTrack, _gameBack.Width + gameBackLoc.X - 30, gameBackLoc.Y + 7,
10, _gameBack.Height - 28);
//If we have more than 12 games, we need to show the track to show how far the user has scrolled
if (_emulators[_selectedEmulator].Games.Count > 12)
{
//Get the amount of games that are exceeding the specified game
int amtOfExtraGames = _emulators[_selectedEmulator].Games.Count - 12;
//Get the ratio size that the scroll thumb should be
int ratio = 100 - (amtOfExtraGames * 10);
//Get the thumb height based off the ratio
int ThumbHeight = ((_gameBack.Height - 28) * ratio) / 100;
//Get the interval height. The 26 was just random guessing
int IntervalHeight = (_gameBack.Height - ThumbHeight - 28) / amtOfExtraGames;
//Draw the thumb at the location the user is at
SwinGame.FillRectangle(Globals.ScrollBarThumb, _gameBack.Width + gameBackLoc.X - 30, gameBackLoc.Y + 7 + (_skip * IntervalHeight),
10, ThumbHeight);
}
//Draw the emulators down the bottom
DrawEmulatorText();
//If the user scrolls through the game index
if (SwinGame.KeyTyped(KeyCode.vk_UP))
{
//Ensure that the logo gets updated
_shouldUpdateData = true;
//Decrement the index (ensure it doesn't go below 0)
_emulators[_selectedEmulator].SelectedGame = Math.Max(0, _emulators[_selectedEmulator].SelectedGame - 1);
//If the user needs to scroll, decrease the skip amount by 1
if (_emulators[_selectedEmulator].SelectedGame - _skip < 6 && _skip > 0)
{
_skip -= 1;
}
}
else if (SwinGame.KeyTyped(KeyCode.vk_DOWN))
{
//Ensure that the logo gets updated
_shouldUpdateData = true;
//Decrement the index (ensure it doesn't go above the amount of games)
_emulators[_selectedEmulator].SelectedGame = Math.Min(_emulators[_selectedEmulator].SelectedGame + 1,
_emulators[_selectedEmulator].Games.Count - 1);
//If the user needs to scroll, decrease the skip amount by 1
if (_emulators[_selectedEmulator].SelectedGame > 6 && _skip + 12 < _emulators[_selectedEmulator].Games.Count)
{
_skip += 1;
}
}
//If the user scrolls through the emulator index
if (SwinGame.KeyTyped(KeyCode.vk_LEFT))
{
//Ensure that the logo gets updated
_shouldUpdateData = true;
_selectedEmulator = Math.Max(0, _selectedEmulator - 1);
FixSkip();
}
else if (SwinGame.KeyTyped(KeyCode.vk_RIGHT))
{
_shouldUpdateData = true;
_selectedEmulator = Math.Min(_selectedEmulator + 1, _emulators.Count - 1);
FixSkip();
}
//Draw the marquee and the background for the marquee
SwinGame.FillRectangle(Globals.Marquee, 0, SwinGame.ScreenHeight() - 12, SwinGame.ScreenWidth(), 12);
_topMarquee.Draw();
//Draw Arcadia to Screen
SwinGame.RefreshScreen(60);
}
}
/// <summary>
/// Fix the amount of games to skip if the user changes emulators
/// </summary>
public void FixSkip()
{
_skip = 0;
if (_emulators[_selectedEmulator].SelectedGame > 6)
{
_skip = _emulators[_selectedEmulator].SelectedGame - 6;
}
if (_skip + 12 > Math.Max(_emulators[_selectedEmulator].Games.Count, 12))
{
_skip = _emulators[_selectedEmulator].Games.Count - 12;
}
}
/// <summary>
/// Draws the selected emulator at the bottom, along with the rest on the side
/// </summary>
public void DrawEmulatorText()
{
//Gets the width & height of the main emulator text
int EmulatorWidth = SwinGame.TextWidth(_manager.GetFont("Geometria", 24), _emulators[_selectedEmulator].EmulatorName);
int EmulatorHeight = SwinGame.TextHeight(_manager.GetFont("Geometria", 24), _emulators[_selectedEmulator].EmulatorName);
//Gets the x position of the main emulator text
int EmulatorX = ((SwinGame.ScreenWidth() + 30) / 2) - (EmulatorWidth / 2);
//Draws the main emulator text to screen
SwinGame.DrawText(_emulators[_selectedEmulator].EmulatorName, Globals.TextColor, _manager.GetFont("Geometria", 24),
new Point2D()
{
X = EmulatorX,
Y = SwinGame.ScreenHeight() - 12 - EmulatorHeight - 8
});
//The accumulatedWidth is the width of all the current items drawn
int AccumulatedWidth = EmulatorX;
//Goes through each emulator from the main emulator backwards
for (int n = _selectedEmulator - 1; n >= 0; n--)
{
//Draws each emulator text to screen
int SmallEmulatorWidth = SwinGame.TextWidth(_manager.GetFont("Geometria", 14), _emulators[n].EmulatorName) + 10;
int SmallEmulatorHeight = SwinGame.TextHeight(_manager.GetFont("Geometria", 14), _emulators[n].EmulatorName);
SwinGame.DrawText(_emulators[n].EmulatorName, Globals.TextColor, _manager.GetFont("Geometria", 14),
new Point2D()
{
X = AccumulatedWidth - SmallEmulatorWidth,
Y = SwinGame.ScreenHeight() - 12 - SmallEmulatorHeight - 8
});
AccumulatedWidth -= SmallEmulatorWidth;
}
//Goes through each emulator from the main emulator forwards
AccumulatedWidth = EmulatorX + EmulatorWidth;
for (int n = _selectedEmulator + 1; n < _emulators.Count; n++)
{
//Draws each emulator text to screen
int SmallEmulatorWidth = SwinGame.TextWidth(_manager.GetFont("Geometria", 14), _emulators[n].EmulatorName) + 10;
int SmallEmulatorHeight = SwinGame.TextHeight(_manager.GetFont("Geometria", 14), _emulators[n].EmulatorName);
SwinGame.DrawText(_emulators[n].EmulatorName, Globals.TextColor, _manager.GetFont("Geometria", 14),
new Point2D()
{
X = AccumulatedWidth + 10,
Y = SwinGame.ScreenHeight() - 12 - SmallEmulatorHeight - 8
});
AccumulatedWidth += SmallEmulatorWidth;
}
}
public void UpdateMarquee()
{
_topMarquee.UpdateText($"Arcadia v{_version} [{_currentTime.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.
namespace System.Drawing.Design {
using System.Configuration.Assemblies;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.ComponentModel;
using System.Diagnostics;
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using Microsoft.Win32;
using System.Drawing;
using System.IO;
using System.Text;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Versioning;
using DpiHelper = System.Windows.Forms.DpiHelper;
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem"]/*' />
/// <devdoc>
/// <para> Provides a base implementation of a toolbox item.</para>
/// </devdoc>
[Serializable]
public class ToolboxItem : ISerializable {
private static TraceSwitch ToolboxItemPersist = new TraceSwitch("ToolboxPersisting", "ToolboxItem: write data");
private static object EventComponentsCreated = new object();
private static object EventComponentsCreating = new object();
private static bool isScalingInitialized = false;
private const int ICON_DIMENSION = 16;
private static int iconWidth = ICON_DIMENSION;
private static int iconHeight = ICON_DIMENSION;
private bool locked;
private LockableDictionary properties;
private ToolboxComponentsCreatedEventHandler componentsCreatedEvent;
private ToolboxComponentsCreatingEventHandler componentsCreatingEvent;
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ToolboxItem"]/*' />
/// <devdoc>
/// Initializes a new instance of the ToolboxItem class.
/// </devdoc>
public ToolboxItem() {
if (!isScalingInitialized) {
if (DpiHelper.IsScalingRequired) {
iconWidth = DpiHelper.LogicalToDeviceUnitsX(ICON_DIMENSION);
iconHeight = DpiHelper.LogicalToDeviceUnitsY(ICON_DIMENSION);
}
isScalingInitialized = true;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ToolboxItem1"]/*' />
/// <devdoc>
/// Initializes a new instance of the ToolboxItem class using the specified type.
/// </devdoc>
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
public ToolboxItem(Type toolType) : this() {
Initialize(toolType);
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ToolboxItem2"]/*' />
/// <devdoc>
/// Initializes a new instance of the <see cref='System.Drawing.Design.ToolboxItem'/>
/// class using the specified serialization information.
/// </devdoc>
#pragma warning disable CA2229 // We don't care about serialization constructors.
private ToolboxItem(SerializationInfo info, StreamingContext context) : this()
#pragma warning restore CA2229
{
Deserialize(info, context);
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.AssemblyName"]/*' />
/// <devdoc>
/// The assembly name for this toolbox item. The assembly name describes the assembly
/// information needed to load the toolbox item's type.
/// </devdoc>
public AssemblyName AssemblyName {
get {
return (AssemblyName)Properties["AssemblyName"];
}
set {
Properties["AssemblyName"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.AssemblyName"]/*' />
/// <devdoc>
/// The assembly name for this toolbox item. The assembly name describes the assembly
/// information needed to load the toolbox item's type.
/// </devdoc>
public AssemblyName[] DependentAssemblies {
get {
AssemblyName[] names = (AssemblyName[]) Properties["DependentAssemblies"];
if (names != null) {
return (AssemblyName[]) names.Clone();
}
return null;
}
set {
Properties["DependentAssemblies"] = value.Clone();
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Bitmap"]/*' />
/// <devdoc>
/// Gets or sets the bitmap that will be used on the toolbox for this item.
/// Use this property on the design surface as this bitmap is scaled according to the current the DPI setting.
/// </devdoc>
public Bitmap Bitmap {
get {
return (Bitmap)Properties["Bitmap"];
}
set {
Properties["Bitmap"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.OriginalBitmap"]/*' />
/// <devdoc>
/// Gets or sets the original bitmap that will be used on the toolbox for this item.
/// This bitmap should be 16x16 pixel and should be used in the Visual Studio toolbox, not on the design surface.
/// </devdoc>
public Bitmap OriginalBitmap {
get {
return (Bitmap)Properties["OriginalBitmap"];
}
set {
Properties["OriginalBitmap"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Company"]/*' />
/// <devdoc>
/// Gets or sets the company name for this <see cref='System.Drawing.Design.ToolboxItem'/>.
/// This defaults to the companyname attribute retrieved from type.Assembly, if set.
/// </devdoc>
public string Company {
get {
return (string)Properties["Company"];
}
set {
Properties["Company"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ComponentType"]/*' />
/// <devdoc>
/// The Component Type is ".Net Component" -- unless otherwise specified by a derived toolboxitem
/// </devdoc>
public virtual string ComponentType {
get {
return SR.Format(SR.DotNET_ComponentType);
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Description"]/*' />
/// <devdoc>
/// Description is a free-form, multiline capable text description that will be displayed in the tooltip
/// for the toolboxItem. It defaults to the path of the assembly that contains the item, but can be overridden.
/// </devdoc>
public string Description {
get {
return (string)Properties["Description"];
}
set {
Properties["Description"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.DisplayName"]/*' />
/// <devdoc>
/// Gets or sets the display name for this <see cref='System.Drawing.Design.ToolboxItem'/>.
/// </devdoc>
public string DisplayName {
get {
return (string)Properties["DisplayName"];
}
set {
Properties["DisplayName"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Filter"]/*' />
/// <devdoc>
/// Gets or sets the filter for this toolbox item. The filter is a collection of
/// ToolboxItemFilterAttribute objects.
/// </devdoc>
public ICollection Filter {
get {
return (ICollection)Properties["Filter"];
}
set {
Properties["Filter"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.IsTransient"]/*' />
/// <devdoc>
/// If true, it indicates that this toolbox item should not be stored in
/// any toolbox database when an application that is providing a toolbox
/// closes down. This property defaults to false.
/// </devdoc>
public bool IsTransient {
[SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")]
get {
return (bool)Properties["IsTransient"];
}
set {
Properties["IsTransient"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Locked"]/*' />
/// <devdoc>
/// Determines if this toolbox item is locked. Once locked, a toolbox item will
/// not accept any changes to its properties.
/// </devdoc>
public virtual bool Locked {
get {
return locked;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Properties"]/*' />
/// <devdoc>
/// The properties dictionary is a set of name/value pairs. The keys are property
/// names and the values are property values. This dictionary becomes read-only
/// after the toolbox item has been locked.
///
/// Values in the properties dictionary are validated through ValidateProperty
/// and default values are obtained from GetDefalutProperty.
/// </devdoc>
public IDictionary Properties {
get {
if (properties == null) {
properties = new LockableDictionary(this, 8 /* # of properties we have */);
}
return properties;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.TypeName"]/*' />
/// <devdoc>
/// Gets or sets the fully qualified name of the type this toolbox item will create.
/// </devdoc>
public string TypeName {
get {
return (string)Properties["TypeName"];
}
set {
Properties["TypeName"] = value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.DisplayName"]/*' />
/// <devdoc>
/// Gets the version for this toolboxitem. It defaults to AssemblyName.Version unless
/// overridden in a derived toolboxitem. This can be overridden to return an empty string
/// to suppress its display in the toolbox tooltip.
/// </devdoc>
public virtual string Version {
get {
if (this.AssemblyName != null) {
return this.AssemblyName.Version.ToString();
}
return String.Empty;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ComponentsCreated"]/*' />
/// <devdoc>
/// <para>Occurs when components are created.</para>
/// </devdoc>
public event ToolboxComponentsCreatedEventHandler ComponentsCreated {
add {
componentsCreatedEvent += value;
}
remove {
componentsCreatedEvent -= value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ComponentsCreating"]/*' />
/// <devdoc>
/// <para>Occurs before components are created.</para>
/// </devdoc>
public event ToolboxComponentsCreatingEventHandler ComponentsCreating {
add {
componentsCreatingEvent += value;
}
remove {
componentsCreatingEvent -= value;
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CheckUnlocked"]/*' />
/// <devdoc>
/// This method checks that the toolbox item is currently unlocked (read-write) and
/// throws an appropriate exception if it isn't.
/// </devdoc>
protected void CheckUnlocked() {
if (Locked) throw new InvalidOperationException(SR.Format(SR.ToolboxItemLocked));
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponents"]/*' />
/// <devdoc>
/// Creates objects from the type contained in this toolbox item.
/// </devdoc>
public IComponent[] CreateComponents() {
return CreateComponents(null);
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponents1"]/*' />
/// <devdoc>
/// Creates objects from the type contained in this toolbox item. If designerHost is non-null
/// this will also add them to the designer.
/// </devdoc>
public IComponent[] CreateComponents(IDesignerHost host) {
OnComponentsCreating(new ToolboxComponentsCreatingEventArgs(host));
IComponent[] comps = CreateComponentsCore(host, new Hashtable());
if (comps != null && comps.Length > 0) {
OnComponentsCreated(new ToolboxComponentsCreatedEventArgs(comps));
}
return comps;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponents2"]/*' />
/// <devdoc>
/// Creates objects from the type contained in this toolbox item. If designerHost is non-null
/// this will also add them to the designer.
/// </devdoc>
public IComponent[] CreateComponents(IDesignerHost host, IDictionary defaultValues) {
OnComponentsCreating(new ToolboxComponentsCreatingEventArgs(host));
IComponent[] comps = CreateComponentsCore(host, defaultValues);
if (comps != null && comps.Length > 0) {
OnComponentsCreated(new ToolboxComponentsCreatedEventArgs(comps));
}
return comps;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponentsCore"]/*' />
/// <devdoc>
/// Creates objects from the type contained in this toolbox item. If designerHost is non-null
/// this will also add them to the designer.
/// </devdoc>
protected virtual IComponent[] CreateComponentsCore(IDesignerHost host) {
ArrayList comps = new ArrayList();
Type createType = GetType(host, AssemblyName, TypeName, true);
if (createType != null) {
if (host != null) {
comps.Add(host.CreateComponent(createType));
}
else if (typeof(IComponent).IsAssignableFrom(createType)) {
comps.Add(TypeDescriptor.CreateInstance(null, createType, null, null));
}
}
IComponent[] temp = new IComponent[comps.Count];
comps.CopyTo(temp, 0);
return temp;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.CreateComponentsCore1"]/*' />
/// <devdoc>
/// Creates objects from the type contained in this toolbox item. If designerHost is non-null
/// this will also add them to the designer.
/// </devdoc>
protected virtual IComponent[] CreateComponentsCore(IDesignerHost host, IDictionary defaultValues) {
IComponent[] components = CreateComponentsCore(host);
if (host != null) {
for (int i = 0; i < components.Length; i++) {
IComponentInitializer init = host.GetDesigner(components[i]) as IComponentInitializer;
if (init != null) {
bool removeComponent = true;
try {
init.InitializeNewComponent(defaultValues);
removeComponent = false;
}
finally
{
if (removeComponent) {
for (int index = 0; index < components.Length; index++) {
host.DestroyComponent(components[index]);
}
}
}
}
}
}
return components;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Deserialize"]/*' />
/// <devdoc>
/// <para>Loads the state of this <see cref='System.Drawing.Design.ToolboxItem'/>
/// from the stream.</para>
/// </devdoc>
protected virtual void Deserialize(SerializationInfo info, StreamingContext context) {
// Do this in a couple of passes -- first pass, try to pull
// out our dictionary of property names. We need to do this
// for backwards compatibilty because if we throw everything
// into the property dictionary we'll duplicate stuff people
// have serialized by hand.
string[] propertyNames = null;
foreach (SerializationEntry entry in info) {
if (entry.Name.Equals("PropertyNames")) {
propertyNames = entry.Value as string[];
break;
}
}
if (propertyNames == null) {
// For backwards compat, here are the default property
// names we use
propertyNames = new string[] {
"AssemblyName",
"Bitmap",
"DisplayName",
"Filter",
"IsTransient",
"TypeName"
};
}
foreach (SerializationEntry entry in info) {
// Check to see if this name is in our
// propertyNames array.
foreach(string validName in propertyNames) {
if (validName.Equals(entry.Name)) {
Properties[entry.Name] = entry.Value;
break;
}
}
}
// Always do "Locked" last (otherwise we can't do the others!)
bool isLocked = info.GetBoolean("Locked");
if (isLocked) {
Lock();
}
}
/// <devdoc>
/// Check if two AssemblyName instances are equivalent
/// </devdoc>
private static bool AreAssemblyNamesEqual(AssemblyName name1, AssemblyName name2) {
return name1 == name2 ||
(name1 != null && name2 != null && name1.FullName == name2.FullName);
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Equals"]/*' />
/// <internalonly/>
public override bool Equals(object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj.GetType() == this.GetType())) {
return false;
}
ToolboxItem otherItem = (ToolboxItem)obj;
return TypeName == otherItem.TypeName &&
AreAssemblyNamesEqual(AssemblyName, otherItem.AssemblyName) &&
DisplayName == otherItem.DisplayName;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.GetHashCode"]/*' />
/// <internalonly/>
public override int GetHashCode() {
string typeName = TypeName;
int hash = (typeName != null) ? typeName.GetHashCode() : 0;
return unchecked(hash ^ DisplayName.GetHashCode());
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.FilterPropertyValue"]/*' />
/// <devdoc>
/// Filters a property value before returning it. This allows a property to always clone values,
/// or to provide a default value when none exists.
/// </devdoc>
protected virtual object FilterPropertyValue(string propertyName, object value) {
switch (propertyName) {
case "AssemblyName":
if (value != null) value = ((AssemblyName)value).Clone();
break;
case "DisplayName":
case "TypeName":
if (value == null) value = string.Empty;
break;
case "Filter":
if (value == null) value = new ToolboxItemFilterAttribute[0];
break;
case "IsTransient":
if (value == null) value = false;
break;
}
return value;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.GetType1"]/*' />
/// <devdoc>
/// Allows access to the type associated with the toolbox item.
/// The designer host is used to access an implementation of ITypeResolutionService.
/// However, the loaded type is not added to the list of references in the designer host.
/// </devdoc>
public Type GetType(IDesignerHost host) {
return GetType(host, AssemblyName, TypeName, false);
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.GetType"]/*' />
/// <devdoc>
/// This utility function can be used to load a type given a name. AssemblyName and
/// designer host can be null, but if they are present they will be used to help
/// locate the type. If reference is true, the given assembly name will be added
/// to the designer host's set of references.
/// </devdoc>
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")]
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
protected virtual Type GetType(IDesignerHost host, AssemblyName assemblyName, string typeName, bool reference) {
ITypeResolutionService ts = null;
Type type = null;
if (typeName == null) {
throw new ArgumentNullException("typeName");
}
if (host != null) {
ts = (ITypeResolutionService)host.GetService(typeof(ITypeResolutionService));
}
if (ts != null) {
if (reference) {
if (assemblyName != null) {
ts.ReferenceAssembly(assemblyName);
type = ts.GetType(typeName);
}
else {
// Just try loading the type. If we succeed, then use this as the
// reference.
type = ts.GetType(typeName);
if (type == null) {
type = Type.GetType(typeName);
}
if (type != null) {
ts.ReferenceAssembly(type.Assembly.GetName());
}
}
}
else {
if (assemblyName != null) {
Assembly a = ts.GetAssembly(assemblyName);
if (a != null) {
type = a.GetType(typeName);
}
}
if (type == null) {
type = ts.GetType(typeName);
}
}
}
else {
if (!String.IsNullOrEmpty(typeName)) {
if (assemblyName != null) {
Assembly a = null;
try {
a = Assembly.Load(assemblyName);
}
catch (FileNotFoundException) {
}
catch (BadImageFormatException) {
}
catch (IOException) {
}
if (a == null && assemblyName.CodeBase != null && assemblyName.CodeBase.Length > 0) {
try {
a = Assembly.LoadFrom(assemblyName.CodeBase);
}
catch (FileNotFoundException) {
}
catch (BadImageFormatException) {
}
catch (IOException) {
}
}
if (a != null) {
type = a.GetType(typeName);
}
}
if (type == null) {
type = Type.GetType(typeName, false);
}
}
}
return type;
}
/// <devdoc>
/// Given an assemblyname and type, this method searches referenced assemblies from t.Assembly
/// looking for a similar name.
/// </devdoc>
private AssemblyName GetNonRetargetedAssemblyName(Type type, AssemblyName policiedAssemblyName) {
if (type == null || policiedAssemblyName == null)
return null;
//if looking for myself, just return it. (not a reference)
if (type.Assembly.FullName == policiedAssemblyName.FullName) {
return policiedAssemblyName;
}
//first search for an exact match -- we prefer this over a partial match.
foreach (AssemblyName name in type.Assembly.GetReferencedAssemblies()) {
if (name.FullName == policiedAssemblyName.FullName)
return name;
}
//next search for a partial match -- we just compare the Name portions (ignore version and publickey)
foreach (AssemblyName name in type.Assembly.GetReferencedAssemblies()) {
if (name.Name == policiedAssemblyName.Name)
return name;
}
//finally, the most expensive -- its possible that retargeting policy is on an assembly whose name changes
// an example of this is the device System.Windows.Forms.Datagrid.dll
// in this case, we need to try to load each device assemblyname through policy to see if it results
// in assemblyname.
foreach (AssemblyName name in type.Assembly.GetReferencedAssemblies()) {
Assembly a = null;
try {
a = Assembly.Load(name);
if (a != null && a.FullName == policiedAssemblyName.FullName)
return name;
}
catch {
//ignore all exceptions and just fall through if it fails (it shouldn't, but who knows).
}
}
return null;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Initialize"]/*' />
/// <devdoc>
/// Initializes a toolbox item with a given type. A locked toolbox item cannot be initialized.
/// </devdoc>
[ResourceExposure(ResourceScope.Process | ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Process | ResourceScope.Machine)]
public virtual void Initialize(Type type) {
CheckUnlocked();
if (type != null) {
TypeName = type.FullName;
AssemblyName assemblyName = type.Assembly.GetName(true);
if (type.Assembly.GlobalAssemblyCache) {
assemblyName.CodeBase = null;
}
Dictionary<string, AssemblyName> parents = new Dictionary<string, AssemblyName>();
Type parentType = type;
while (parentType != null) {
AssemblyName policiedname = parentType.Assembly.GetName(true);
AssemblyName aname = GetNonRetargetedAssemblyName(type, policiedname);
if (aname != null && !parents.ContainsKey(aname.FullName)) {
parents[aname.FullName] = aname;
}
parentType = parentType.BaseType;
}
AssemblyName[] parentAssemblies = new AssemblyName[parents.Count];
int i = 0;
foreach(AssemblyName an in parents.Values) {
parentAssemblies[i++] = an;
}
this.DependentAssemblies = parentAssemblies;
AssemblyName = assemblyName;
DisplayName = type.Name;
//if the Type is a reflectonly type, these values must be set through a config object or manually
//after construction.
if (!type.Assembly.ReflectionOnly) {
object[] companyattrs = type.Assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true);
if (companyattrs != null && companyattrs.Length > 0) {
AssemblyCompanyAttribute company = companyattrs[0] as AssemblyCompanyAttribute;
if (company != null && company.Company != null) {
Company = company.Company;
}
}
//set the description based off the description attribute of the given type.
DescriptionAttribute descattr = (DescriptionAttribute)TypeDescriptor.GetAttributes(type)[typeof(DescriptionAttribute)];
if (descattr != null) {
this.Description = descattr.Description;
}
ToolboxBitmapAttribute attr = (ToolboxBitmapAttribute)TypeDescriptor.GetAttributes(type)[typeof(ToolboxBitmapAttribute)];
if (attr != null) {
Bitmap itemBitmap = attr.GetImage(type, false) as Bitmap;
if (itemBitmap != null) {
// Original bitmap is used when adding the item to the Visual Studio toolbox
// if running on a machine with HDPI scaling enabled.
OriginalBitmap = attr.GetOriginalBitmap();
if ((itemBitmap.Width != iconWidth || itemBitmap.Height != iconHeight)) {
itemBitmap = new Bitmap(itemBitmap, new Size(iconWidth, iconHeight));
}
}
Bitmap = itemBitmap;
}
bool filterContainsType = false;
ArrayList array = new ArrayList();
foreach (Attribute a in TypeDescriptor.GetAttributes(type)) {
ToolboxItemFilterAttribute ta = a as ToolboxItemFilterAttribute;
if (ta != null) {
if (ta.FilterString.Equals(TypeName)) {
filterContainsType = true;
}
array.Add(ta);
}
}
if (!filterContainsType) {
array.Add(new ToolboxItemFilterAttribute(TypeName));
}
Filter = (ToolboxItemFilterAttribute[])array.ToArray(typeof(ToolboxItemFilterAttribute));
}
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Lock"]/*' />
/// <devdoc>
/// Locks this toolbox item. Locking a toolbox item makes it read-only and
/// prevents any changes to its properties.
/// </devdoc>
public virtual void Lock() {
locked = true;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.OnComponentsCreated"]/*' />
/// <devdoc>
/// <para>Raises the OnComponentsCreated event. This
/// will be called when this <see cref='System.Drawing.Design.ToolboxItem'/> creates a component.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] //full trust anyway
protected virtual void OnComponentsCreated(ToolboxComponentsCreatedEventArgs args) {
if (componentsCreatedEvent != null) {
componentsCreatedEvent(this, args);
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.OnComponentsCreating"]/*' />
/// <devdoc>
/// <para>Raises the OnCreateComponentsInvoked event. This
/// will be called before this <see cref='System.Drawing.Design.ToolboxItem'/> creates a component.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers")] //full trust anyway
protected virtual void OnComponentsCreating(ToolboxComponentsCreatingEventArgs args) {
if (componentsCreatingEvent != null) {
componentsCreatingEvent(this, args);
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.Serialize"]/*' />
/// <devdoc>
/// <para>Saves the state of this <see cref='System.Drawing.Design.ToolboxItem'/> to
/// the specified serialization info.</para>
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes")]
protected virtual void Serialize(SerializationInfo info, StreamingContext context) {
if (ToolboxItemPersist.TraceVerbose) {
Debug.WriteLine("Persisting: " + GetType().Name);
Debug.WriteLine("\tDisplay Name: " + DisplayName);
}
info.AddValue("Locked", Locked);
ArrayList propertyNames = new ArrayList(Properties.Count);
foreach (DictionaryEntry de in Properties) {
propertyNames.Add(de.Key);
info.AddValue((string)de.Key, de.Value);
}
info.AddValue("PropertyNames", (string[])propertyNames.ToArray(typeof(string)));
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ToString"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override string ToString() {
return this.DisplayName;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ValidatePropertyType"]/*' />
/// <devdoc>
/// Called as a helper to ValidatePropertyValue to validate that an object
/// is of a given type.
/// </devdoc>
protected void ValidatePropertyType(string propertyName, object value, Type expectedType, bool allowNull) {
if (value == null) {
if (!allowNull) {
throw new ArgumentNullException("value");
}
}
else {
if (!expectedType.IsInstanceOfType(value)) {
throw new ArgumentException(SR.Format(SR.ToolboxItemInvalidPropertyType, propertyName, expectedType.FullName), "value");
}
}
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ValidatePropertyValue"]/*' />
/// <devdoc>
/// This is called whenever a value is set in the property dictionary. It gives you a chance
/// to change the value of an object before comitting it, our reject it by throwing an
/// exception.
/// </devdoc>
protected virtual object ValidatePropertyValue(string propertyName, object value) {
switch (propertyName) {
case "AssemblyName":
ValidatePropertyType(propertyName, value, typeof(AssemblyName), true);
break;
case "Bitmap":
ValidatePropertyType(propertyName, value, typeof(Bitmap), true);
break;
case "OriginalBitmap":
ValidatePropertyType(propertyName, value, typeof(Bitmap), true);
break;
case "Company":
case "Description":
case "DisplayName":
case "TypeName":
ValidatePropertyType(propertyName, value, typeof(string), true);
if (value == null) value = string.Empty;
break;
case "Filter":
ValidatePropertyType(propertyName, value, typeof(ICollection), true);
int filterCount = 0;
ICollection col = (ICollection)value;
if (col != null) {
foreach (object f in col) {
if (f is ToolboxItemFilterAttribute) {
filterCount++;
}
}
}
ToolboxItemFilterAttribute[] filter = new ToolboxItemFilterAttribute[filterCount];
if (col != null) {
filterCount = 0;
foreach (object f in col) {
ToolboxItemFilterAttribute tfa = f as ToolboxItemFilterAttribute;
if (tfa != null) {
filter[filterCount++] = tfa;
}
}
}
value = filter;
break;
case "IsTransient":
ValidatePropertyType(propertyName, value, typeof(bool), false);
break;
}
return value;
}
/// <include file='doc\ToolboxItem.uex' path='docs/doc[@for="ToolboxItem.ISerializable.GetObjectData"]/*' />
/// <internalonly/>
// SECREVIEW NOTE: we do not put the linkdemand that should be here, because the one on the type is a superset of this one
[SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
IntSecurity.UnmanagedCode.Demand();
Serialize(info, context);
}
/// <devdoc>
/// This is a simple IDictionary that supports locking so
/// changing values are not allowed after the toolbox
/// item has been locked.
/// </devdoc>
private class LockableDictionary : Hashtable
{
private ToolboxItem _item;
internal LockableDictionary(ToolboxItem item, int capacity) : base(capacity)
{
_item = item;
}
public override bool IsFixedSize
{
get
{
return _item.Locked;
}
}
public override bool IsReadOnly
{
get
{
return _item.Locked;
}
}
public override object this[object key]
{
get
{
string propertyName = GetPropertyName(key);
object value = base[propertyName];
return _item.FilterPropertyValue(propertyName, value);
}
set
{
string propertyName = GetPropertyName(key);
value = _item.ValidatePropertyValue(propertyName, value);
CheckSerializable(value);
_item.CheckUnlocked();
base[propertyName] = value;
}
}
public override void Add(object key, object value)
{
string propertyName = GetPropertyName(key);
value = _item.ValidatePropertyValue(propertyName, value);
CheckSerializable(value);
_item.CheckUnlocked();
base.Add(propertyName, value);
}
private void CheckSerializable(object value) {
if (value != null && !value.GetType().IsSerializable) {
throw new ArgumentException(SR.Format(SR.ToolboxItemValueNotSerializable, value.GetType().FullName));
}
}
public override void Clear()
{
_item.CheckUnlocked();
base.Clear();
}
private string GetPropertyName(object key) {
if (key == null) {
throw new ArgumentNullException("key");
}
string propertyName = key as string;
if (propertyName == null || propertyName.Length == 0) {
throw new ArgumentException(SR.Format(SR.ToolboxItemInvalidKey), "key");
}
return propertyName;
}
public override void Remove(object key)
{
_item.CheckUnlocked();
base.Remove(key);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Numerics.Hashing;
namespace System.Drawing
{
/// <summary>
/// Represents an ordered pair of x and y coordinates that
/// define a point in a two-dimensional plane.
/// </summary>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public struct Point : IEquatable<Point>
{
/// <summary>
/// Creates a new instance of the <see cref='System.Drawing.Point'/> class
/// with member data left uninitialized.
/// </summary>
public static readonly Point Empty = new Point();
private int x; // Do not rename (binary serialization)
private int y; // Do not rename (binary serialization)
/// <summary>
/// Initializes a new instance of the <see cref='System.Drawing.Point'/> class
/// with the specified coordinates.
/// </summary>
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.Drawing.Point'/> class
/// from a <see cref='System.Drawing.Size'/> .
/// </para>
/// </summary>
public Point(Size sz)
{
x = sz.Width;
y = sz.Height;
}
/// <summary>
/// Initializes a new instance of the Point class using
/// coordinates specified by an integer value.
/// </summary>
public Point(int dw)
{
x = LowInt16(dw);
y = HighInt16(dw);
}
/// <summary>
/// <para>
/// Gets a value indicating whether this <see cref='System.Drawing.Point'/> is empty.
/// </para>
/// </summary>
[Browsable(false)]
public bool IsEmpty => x == 0 && y == 0;
/// <summary>
/// Gets the x-coordinate of this <see cref='System.Drawing.Point'/>.
/// </summary>
public int X
{
get { return x; }
set { x = value; }
}
/// <summary>
/// <para>
/// Gets the y-coordinate of this <see cref='System.Drawing.Point'/>.
/// </para>
/// </summary>
public int Y
{
get { return y; }
set { y = value; }
}
/// <summary>
/// <para>
/// Creates a <see cref='System.Drawing.PointF'/> with the coordinates of the specified
/// <see cref='System.Drawing.Point'/>
/// </para>
/// </summary>
public static implicit operator PointF(Point p) => new PointF(p.X, p.Y);
/// <summary>
/// <para>
/// Creates a <see cref='System.Drawing.Size'/> with the coordinates of the specified <see cref='System.Drawing.Point'/> .
/// </para>
/// </summary>
public static explicit operator Size(Point p) => new Size(p.X, p.Y);
/// <summary>
/// <para>
/// Translates a <see cref='System.Drawing.Point'/> by a given <see cref='System.Drawing.Size'/> .
/// </para>
/// </summary>
public static Point operator +(Point pt, Size sz) => Add(pt, sz);
/// <summary>
/// <para>
/// Translates a <see cref='System.Drawing.Point'/> by the negative of a given <see cref='System.Drawing.Size'/> .
/// </para>
/// </summary>
public static Point operator -(Point pt, Size sz) => Subtract(pt, sz);
/// <summary>
/// <para>
/// Compares two <see cref='System.Drawing.Point'/> objects. The result specifies
/// whether the values of the <see cref='System.Drawing.Point.X'/> and <see cref='System.Drawing.Point.Y'/> properties of the two <see cref='System.Drawing.Point'/>
/// objects are equal.
/// </para>
/// </summary>
public static bool operator ==(Point left, Point right) => left.X == right.X && left.Y == right.Y;
/// <summary>
/// <para>
/// Compares two <see cref='System.Drawing.Point'/> objects. The result specifies whether the values
/// of the <see cref='System.Drawing.Point.X'/> or <see cref='System.Drawing.Point.Y'/> properties of the two
/// <see cref='System.Drawing.Point'/>
/// objects are unequal.
/// </para>
/// </summary>
public static bool operator !=(Point left, Point right) => !(left == right);
/// <summary>
/// <para>
/// Translates a <see cref='System.Drawing.Point'/> by a given <see cref='System.Drawing.Size'/> .
/// </para>
/// </summary>
public static Point Add(Point pt, Size sz) => new Point(unchecked(pt.X + sz.Width), unchecked(pt.Y + sz.Height));
/// <summary>
/// <para>
/// Translates a <see cref='System.Drawing.Point'/> by the negative of a given <see cref='System.Drawing.Size'/> .
/// </para>
/// </summary>
public static Point Subtract(Point pt, Size sz) => new Point(unchecked(pt.X - sz.Width), unchecked(pt.Y - sz.Height));
/// <summary>
/// Converts a PointF to a Point by performing a ceiling operation on
/// all the coordinates.
/// </summary>
public static Point Ceiling(PointF value) => new Point(unchecked((int)Math.Ceiling(value.X)), unchecked((int)Math.Ceiling(value.Y)));
/// <summary>
/// Converts a PointF to a Point by performing a truncate operation on
/// all the coordinates.
/// </summary>
public static Point Truncate(PointF value) => new Point(unchecked((int)value.X), unchecked((int)value.Y));
/// <summary>
/// Converts a PointF to a Point by performing a round operation on
/// all the coordinates.
/// </summary>
public static Point Round(PointF value) => new Point(unchecked((int)Math.Round(value.X)), unchecked((int)Math.Round(value.Y)));
/// <summary>
/// <para>
/// Specifies whether this <see cref='System.Drawing.Point'/> contains
/// the same coordinates as the specified <see cref='System.Object'/>.
/// </para>
/// </summary>
public override bool Equals(object obj) => obj is Point && Equals((Point)obj);
public bool Equals(Point other) => this == other;
/// <summary>
/// <para>
/// Returns a hash code.
/// </para>
/// </summary>
public override int GetHashCode() => HashHelpers.Combine(X, Y);
/// <summary>
/// Translates this <see cref='System.Drawing.Point'/> by the specified amount.
/// </summary>
public void Offset(int dx, int dy)
{
unchecked
{
X += dx;
Y += dy;
}
}
/// <summary>
/// Translates this <see cref='System.Drawing.Point'/> by the specified amount.
/// </summary>
public void Offset(Point p) => Offset(p.X, p.Y);
/// <summary>
/// <para>
/// Converts this <see cref='System.Drawing.Point'/>
/// to a human readable
/// string.
/// </para>
/// </summary>
public override string ToString() => "{X=" + X.ToString() + ",Y=" + Y.ToString() + "}";
private static short HighInt16(int n) => unchecked((short)((n >> 16) & 0xffff));
private static short LowInt16(int n) => unchecked((short)(n & 0xffff));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Net.Mail;
using System.Text;
namespace System.Net.Http.Headers
{
internal static class HeaderUtilities
{
private const string qualityName = "q";
internal const string ConnectionClose = "close";
internal static readonly TransferCodingHeaderValue TransferEncodingChunked =
new TransferCodingHeaderValue("chunked");
internal static readonly NameValueWithParametersHeaderValue ExpectContinue =
new NameValueWithParametersHeaderValue("100-continue");
internal const string BytesUnit = "bytes";
// Validator
internal static readonly Action<HttpHeaderValueCollection<string>, string> TokenValidator = ValidateToken;
private static readonly char[] s_hexUpperChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
internal static void SetQuality(ObjectCollection<NameValueHeaderValue> parameters, double? value)
{
Debug.Assert(parameters != null);
NameValueHeaderValue qualityParameter = NameValueHeaderValue.Find(parameters, qualityName);
if (value.HasValue)
{
// Note that even if we check the value here, we can't prevent a user from adding an invalid quality
// value using Parameters.Add(). Even if we would prevent the user from adding an invalid value
// using Parameters.Add() he could always add invalid values using HttpHeaders.AddWithoutValidation().
// So this check is really for convenience to show users that they're trying to add an invalid
// value.
if ((value < 0) || (value > 1))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
string qualityString = ((double)value).ToString("0.0##", NumberFormatInfo.InvariantInfo);
if (qualityParameter != null)
{
qualityParameter.Value = qualityString;
}
else
{
parameters.Add(new NameValueHeaderValue(qualityName, qualityString));
}
}
else
{
// Remove quality parameter
if (qualityParameter != null)
{
parameters.Remove(qualityParameter);
}
}
}
// Encode a string using RFC 5987 encoding.
// encoding'lang'PercentEncodedSpecials
internal static string Encode5987(string input)
{
string output;
IsInputEncoded5987(input, out output);
return output;
}
internal static bool IsInputEncoded5987(string input, out string output)
{
// Encode a string using RFC 5987 encoding.
// encoding'lang'PercentEncodedSpecials
bool wasEncoded = false;
StringBuilder builder = StringBuilderCache.Acquire();
builder.Append("utf-8\'\'");
foreach (char c in input)
{
// attr-char = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
// ; token except ( "*" / "'" / "%" )
if (c > 0x7F) // Encodes as multiple utf-8 bytes
{
byte[] bytes = Encoding.UTF8.GetBytes(c.ToString());
foreach (byte b in bytes)
{
AddHexEscaped((char)b, builder);
wasEncoded = true;
}
}
else if (!HttpRuleParser.IsTokenChar(c) || c == '*' || c == '\'' || c == '%')
{
// ASCII - Only one encoded byte.
AddHexEscaped(c, builder);
wasEncoded = true;
}
else
{
builder.Append(c);
}
}
output = StringBuilderCache.GetStringAndRelease(builder);
return wasEncoded;
}
/// <summary>Transforms an ASCII character into its hexadecimal representation, adding the characters to a StringBuilder.</summary>
private static void AddHexEscaped(char c, StringBuilder destination)
{
Debug.Assert(destination != null);
Debug.Assert(c <= 0xFF);
destination.Append('%');
destination.Append(s_hexUpperChars[(c & 0xf0) >> 4]);
destination.Append(s_hexUpperChars[c & 0xf]);
}
internal static double? GetQuality(ObjectCollection<NameValueHeaderValue> parameters)
{
Debug.Assert(parameters != null);
NameValueHeaderValue qualityParameter = NameValueHeaderValue.Find(parameters, qualityName);
if (qualityParameter != null)
{
// Note that the RFC requires decimal '.' regardless of the culture. I.e. using ',' as decimal
// separator is considered invalid (even if the current culture would allow it).
double qualityValue = 0;
if (double.TryParse(qualityParameter.Value, NumberStyles.AllowDecimalPoint,
NumberFormatInfo.InvariantInfo, out qualityValue))
{
return qualityValue;
}
// If the stored value is an invalid quality value, just return null and log a warning.
if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_invalid_quality, qualityParameter.Value));
}
return null;
}
internal static void CheckValidToken(string value, string parameterName)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
if (HttpRuleParser.GetTokenLength(value, 0) != value.Length)
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
internal static void CheckValidComment(string value, string parameterName)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
int length = 0;
if ((HttpRuleParser.GetCommentLength(value, 0, out length) != HttpParseResult.Parsed) ||
(length != value.Length)) // no trailing spaces allowed
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
internal static void CheckValidQuotedString(string value, string parameterName)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(SR.net_http_argument_empty_string, parameterName);
}
int length = 0;
if ((HttpRuleParser.GetQuotedStringLength(value, 0, out length) != HttpParseResult.Parsed) ||
(length != value.Length)) // no trailing spaces allowed
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
internal static bool AreEqualCollections<T>(ObjectCollection<T> x, ObjectCollection<T> y) where T : class
{
return AreEqualCollections(x, y, null);
}
internal static bool AreEqualCollections<T>(ObjectCollection<T> x, ObjectCollection<T> y, IEqualityComparer<T> comparer) where T : class
{
if (x == null)
{
return (y == null) || (y.Count == 0);
}
if (y == null)
{
return (x.Count == 0);
}
if (x.Count != y.Count)
{
return false;
}
if (x.Count == 0)
{
return true;
}
// We have two unordered lists. So comparison is an O(n*m) operation which is expensive. Usually
// headers have 1-2 parameters (if any), so this comparison shouldn't be too expensive.
bool[] alreadyFound = new bool[x.Count];
int i = 0;
foreach (var xItem in x)
{
Debug.Assert(xItem != null);
i = 0;
bool found = false;
foreach (var yItem in y)
{
if (!alreadyFound[i])
{
if (((comparer == null) && xItem.Equals(yItem)) ||
((comparer != null) && comparer.Equals(xItem, yItem)))
{
alreadyFound[i] = true;
found = true;
break;
}
}
i++;
}
if (!found)
{
return false;
}
}
// Since we never re-use a "found" value in 'y', we expect 'alreadyFound' to have all fields set to 'true'.
// Otherwise the two collections can't be equal and we should not get here.
Debug.Assert(Contract.ForAll(alreadyFound, value => { return value; }),
"Expected all values in 'alreadyFound' to be true since collections are considered equal.");
return true;
}
internal static int GetNextNonEmptyOrWhitespaceIndex(string input, int startIndex, bool skipEmptyValues,
out bool separatorFound)
{
Debug.Assert(input != null);
Debug.Assert(startIndex <= input.Length); // it's OK if index == value.Length.
separatorFound = false;
int current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex);
if ((current == input.Length) || (input[current] != ','))
{
return current;
}
// If we have a separator, skip the separator and all following whitespace. If we support
// empty values, continue until the current character is neither a separator nor a whitespace.
separatorFound = true;
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
if (skipEmptyValues)
{
while ((current < input.Length) && (input[current] == ','))
{
current++; // skip delimiter.
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
}
return current;
}
internal static DateTimeOffset? GetDateTimeOffsetValue(HeaderDescriptor descriptor, HttpHeaders store)
{
Debug.Assert(store != null);
object storedValue = store.GetParsedValues(descriptor);
if (storedValue != null)
{
return (DateTimeOffset)storedValue;
}
return null;
}
internal static TimeSpan? GetTimeSpanValue(HeaderDescriptor descriptor, HttpHeaders store)
{
Debug.Assert(store != null);
object storedValue = store.GetParsedValues(descriptor);
if (storedValue != null)
{
return (TimeSpan)storedValue;
}
return null;
}
internal static bool TryParseInt32(string value, out int result) =>
TryParseInt32(value, 0, value.Length, out result);
internal static bool TryParseInt32(string value, int offset, int length, out int result) // TODO #21281: Replace with int.TryParse(Span<char>) once it's available
{
if (offset < 0 || length < 0 || offset > value.Length - length)
{
result = 0;
return false;
}
int tmpResult = 0;
int pos = offset, endPos = offset + length;
while (pos < endPos)
{
char c = value[pos++];
int digit = c - '0';
if ((uint)digit > 9 || // invalid digit
tmpResult > int.MaxValue / 10 || // will overflow when shifting digits
(tmpResult == int.MaxValue / 10 && digit > 7)) // will overflow when adding in digit
{
result = 0;
return false;
}
tmpResult = (tmpResult * 10) + digit;
}
result = tmpResult;
return true;
}
internal static bool TryParseInt64(string value, int offset, int length, out long result) // TODO #21281: Replace with int.TryParse(Span<char>) once it's available
{
if (offset < 0 || length < 0 || offset > value.Length - length)
{
result = 0;
return false;
}
long tmpResult = 0;
int pos = offset, endPos = offset + length;
while (pos < endPos)
{
char c = value[pos++];
int digit = c - '0';
if ((uint)digit > 9 || // invalid digit
tmpResult > long.MaxValue / 10 || // will overflow when shifting digits
(tmpResult == long.MaxValue / 10 && digit > 7)) // will overflow when adding in digit
{
result = 0;
return false;
}
tmpResult = (tmpResult * 10) + digit;
}
result = tmpResult;
return true;
}
internal static string DumpHeaders(params HttpHeaders[] headers)
{
// Return all headers as string similar to:
// {
// HeaderName1: Value1
// HeaderName1: Value2
// HeaderName2: Value1
// ...
// }
StringBuilder sb = new StringBuilder();
sb.Append("{\r\n");
for (int i = 0; i < headers.Length; i++)
{
if (headers[i] != null)
{
foreach (var header in headers[i])
{
foreach (var headerValue in header.Value)
{
sb.Append(" ");
sb.Append(header.Key);
sb.Append(": ");
sb.Append(headerValue);
sb.Append("\r\n");
}
}
}
}
sb.Append('}');
return sb.ToString();
}
internal static bool IsValidEmailAddress(string value)
{
try
{
#if uap
new MailAddress(value);
#else
MailAddressParser.ParseAddress(value);
#endif
return true;
}
catch (FormatException e)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, SR.Format(SR.net_http_log_headers_wrong_email_format, value, e.Message));
}
return false;
}
private static void ValidateToken(HttpHeaderValueCollection<string> collection, string value)
{
CheckValidToken(value, "item");
}
}
}
| |
/*----------------------------------------------------------------
// Copyright (C) 2007 Fengart
//----------------------------------------------------------------*/
using System;
namespace MonkeyOthello.Engines.V2.AI
{
public class StaSolve : BaseSolve
{
private bool foundInBook;
private Evalation evalation;
public bool FoundInBook
{
get { return foundInBook; }
}
public int SearchDepth
{
get { return searchDepth; }
set { searchDepth = value; }
}
public int Nodes
{
get { return nodes; }
}
public int BestMove
{
get { return bestMove; }
}
public StaSolve()
: base()
{
searchDepth = 8;
foundInBook = false;
evalation = new Evalation();
nodes = 0;
}
private int FastestFirstSolve(ChessType[] board, int alpha, int beta, ChessType color, int depth, int empties, int discdiff, int prevmove)
{
lock (this)
{
int i, j;
int score = -Constants.HighestScore-1;
ChessType oppcolor = 2 - color;
int sqnum;
int eval;
int flipped;
int moves, mobility;
int best_value, best_index;
Empties em, old_em;
Empties[] move_ptr = new Empties[Constants.MaxEmpties];
int holepar;
int[] goodness = new int[Constants.MaxEmpties];
bool fFoundPv = false;
//
// nodes++;
if (depth == 0)
{
nodes++;
//return evalation.StaEval2(board, color, oppcolor, empties,EmHead);
return QuiescenceSolve(board, alpha, beta, color, 2, empties, discdiff, prevmove);
}
moves = 0;
for (old_em = EmHead, em = old_em.Succ; em != null; old_em = em, em = em.Succ)
{
sqnum = em.Square;
flipped = RuleUtils.DoFlips(board, sqnum, color, oppcolor);
if (flipped > 0)
{
//
board[sqnum] = color;
old_em.Succ = em.Succ;
//
mobility = count_mobility(board, oppcolor);
//
RuleUtils.UndoFlips(board, flipped, oppcolor);
old_em.Succ = em;
board[sqnum] = ChessType.EMPTY;
move_ptr[moves] = em;
goodness[moves] = -mobility;
moves++;
}
}
if (moves != 0)
{
for (i = 0; i < moves; i++)
{
//
best_value = goodness[i];
best_index = i;
for (j = i + 1; j < moves; j++)
if (goodness[j] > best_value)
{
best_value = goodness[j];
best_index = j;
}
em = move_ptr[best_index];
move_ptr[best_index] = move_ptr[i];
goodness[best_index] = goodness[i];
//
sqnum = em.Square;
holepar = em.HoleId;
j = RuleUtils.DoFlips(board, sqnum, color, oppcolor);
board[sqnum] = color;
em.Pred.Succ = em.Succ;
if (em.Succ != null)
em.Succ.Pred = em.Pred;
nodes++;
//
if (fFoundPv)
{
//
eval = -FastestFirstSolve(board, -alpha - 1, -alpha, oppcolor, depth - 1, empties - 1, -discdiff - 2 * j - 1, sqnum);
if ((eval > alpha) && (eval < beta))
{
eval = -FastestFirstSolve(board, -beta, -eval, oppcolor, depth - 1, empties - 1, -discdiff - 2 * j - 1, sqnum);
//eval = -FastestFirstMidSolve(board, -beta, -alpha, oppcolor, depth - 1, empties - 1, -discdiff - 2 * j - 1, sqnum);
}
}
else
{
eval = -FastestFirstSolve(board, -beta, -alpha, oppcolor, depth - 1, empties - 1, -discdiff - 2 * j - 1, sqnum);
}
//
RuleUtils.UndoFlips(board, j, oppcolor);
board[sqnum] = ChessType.EMPTY;
em.Pred.Succ = em;
if (em.Succ != null)
em.Succ.Pred = em;
if (eval > score)
{
score = eval;
if (eval > alpha)
{
if (eval >= beta)
{
//
return score;
}
alpha = eval;
fFoundPv = true;
}
}
}
}
else
{
if (prevmove == 0)//
{
if (discdiff > 0)//
return Constants.HighestScore;
if (discdiff < 0)//
return -Constants.HighestScore;
return 0;//
}
else /* I pass: */
score = -FastestFirstSolve(board, -beta, -alpha, oppcolor, depth, empties, -discdiff, 0);
}
return score;
}
}
private int QuiescenceSolve(ChessType[] board, int alpha, int beta, ChessType color, int depth, int empties, int discdiff, int prevmove)
{
lock (this)
{
int i, j;
int score1;
int score2 = -Constants.HighestScore;
ChessType oppcolor = 2 - color;
int sqnum;
int eval;
int flipped;
int moves, mobility;
int best_value, best_index;
Empties em, old_em;
Empties[] move_ptr = new Empties[Constants.MaxEmpties];
int holepar;
int[] goodness = new int[Constants.MaxEmpties];
////
//nodes++;
score1 = evalation.StaEval2(board, color, oppcolor, empties, EmHead);
if (score1 >= beta || score1>=4000 || depth == 0) return score1;
else if (score1 > alpha)
alpha = score1;
moves = 0;
for (old_em = EmHead, em = old_em.Succ; em != null; old_em = em, em = em.Succ)
{
sqnum = em.Square;
flipped = RuleUtils.DoFlips(board, sqnum, color, oppcolor);
if (flipped > 0)
{
//
board[sqnum] = color;
old_em.Succ = em.Succ;
//
mobility = count_mobility(board, oppcolor);
//
RuleUtils.UndoFlips(board, flipped, oppcolor);
old_em.Succ = em;
board[sqnum] = ChessType.EMPTY;
move_ptr[moves] = em;
goodness[moves] = -mobility;
moves++;
}
}
if (moves != 0)
{
for (i = 0; i < moves; i++)
{
best_value = goodness[i];
best_index = i;
for (j = i + 1; j < moves; j++)
if (goodness[j] > best_value)
{
best_value = goodness[j];
best_index = j;
}
em = move_ptr[best_index];
move_ptr[best_index] = move_ptr[i];
goodness[best_index] = goodness[i];
sqnum = em.Square;
holepar = em.HoleId;
j = RuleUtils.DoFlips(board, sqnum, color, oppcolor);
board[sqnum] = color;
em.Pred.Succ = em.Succ;
if (em.Succ != null)
em.Succ.Pred = em.Pred;
//
nodes++;
//
eval = -evalation.StaEval2(board, oppcolor, color, empties - 1, EmHead);
// -QuiescenceSolve(board, -beta, -alpha, oppcolor, depth - 1, empties - 1, -discdiff - j - j - 1, sqnum);
RuleUtils.UndoFlips(board, j, oppcolor);
board[sqnum] = ChessType.EMPTY;
em.Pred.Succ = em;
if (em.Succ != null)
em.Succ.Pred = em;
if (eval > score2)
{
score2 = eval;
if (eval > alpha)
{
if (eval >= beta)
{
//
return score2;
}
alpha = eval;
}
}
}
}
else
{
if (prevmove == 0)//
{
if (discdiff > 0)
return Constants.HighestScore;
if (discdiff < 0)
return -Constants.HighestScore;
return 0;
}
else /* I pass: */
{
nodes++;
score2 = -QuiescenceSolve(board, -beta, -alpha, oppcolor, depth, empties, -discdiff, 0);
return score2;
}
}
return (2*score1 + score2) /3;
}
}
private int RootStaSolve(ChessType[] board, int alpha, int beta, ChessType color, int depth, int empties, int discdiff, int prevmove)
{
lock (this)
{
int i, j;
int score = -Constants.HighestScore - 1;
ChessType oppcolor = 2 - color;
int sqnum;
int eval;
int flipped;
int moves, mobility;
int best_value, best_index;
Empties em, old_em;
Empties[] move_ptr = new Empties[Constants.MaxEmpties];
int holepar;
int[] goodness = new int[Constants.MaxEmpties];
//
bool fFoundPv = false;
moves = 0;
for (old_em = EmHead, em = old_em.Succ; em != null; old_em = em, em = em.Succ)
{
sqnum = em.Square;
flipped = RuleUtils.DoFlips(board, sqnum, color, oppcolor);
if (flipped > 0)
{
//
board[sqnum] = color;
old_em.Succ = em.Succ;
//
mobility = -count_mobility(board, oppcolor);
//mobility = -FastestFirstSolve(board, -beta, -alpha, oppcolor, 4, empties - 1, -discdiff - 2 * flipped - 1, sqnum);
//
RuleUtils.UndoFlips(board, flipped, oppcolor);
old_em.Succ = em;
board[sqnum] = ChessType.EMPTY;
move_ptr[moves] = em;
goodness[moves] = mobility;
moves++;
}
}
if (moves != 0)
{
for (i = 0; i < moves; i++)
{
//
best_value = goodness[i];
best_index = i;
for (j = i + 1; j < moves; j++)
if (goodness[j] > best_value)
{
best_value = goodness[j];
best_index = j;
}
em = move_ptr[best_index];
move_ptr[best_index] = move_ptr[i];
goodness[best_index] = goodness[i];
//
sqnum = em.Square;
holepar = em.HoleId;
j = RuleUtils.DoFlips(board, sqnum, color, oppcolor);
board[sqnum] = color;
em.Pred.Succ = em.Succ;
if (em.Succ != null)
em.Succ.Pred = em.Pred;
nodes++;
//
if (fFoundPv)
{
eval = -FastestFirstSolve(board, -alpha - 1, -alpha, oppcolor, depth - 1, empties - 1, -discdiff - 2 * j - 1, sqnum);
if ((eval > alpha) && (eval < beta))
{
eval = -FastestFirstSolve(board, -beta, -eval, oppcolor, depth - 1, empties - 1, -discdiff - 2 * j - 1, sqnum);
//eval = -FastestFirstMidSolve(board, -beta, -alpha, oppcolor, depth - 1, empties - 1, -discdiff - 2 * j - 1, sqnum);
}
}
else
{
eval = -FastestFirstSolve(board, -beta, -alpha, oppcolor, depth - 1, empties - 1, -discdiff - 2 * j - 1, sqnum);
}
//
RuleUtils.UndoFlips(board, j, oppcolor);
board[sqnum] = ChessType.EMPTY;
em.Pred.Succ = em;
if (em.Succ != null)
em.Succ.Pred = em;
if (eval > score)
{
score = eval;
//
bestMove = sqnum;
if (eval > alpha)
{
if (eval >= beta)
{
//
return score;
}
alpha = eval;
fFoundPv = true;
}
}
}
}
else
{ /* I pass: */
score = -FastestFirstSolve(board, -beta, -alpha, oppcolor, depth, empties, -discdiff, 0);
//
if (depth == searchDepth)
{
bestMove = MVPASS;
}
}
return score;
}
}
public double Solve(ChessType[] board, int alpha, int beta, ChessType color, int empties, int discdiff, int prevmove)
{
double eval ;
nodes = 0;
foundInBook = false;
eval = RootStaSolve(board, alpha, beta, color, searchDepth, empties, discdiff, prevmove);
//eval = MPCMidSolve(board, alpha, beta, color, searchDepth, empties, discdiff, prevmove);
eval /= 100;
return (eval > 64 ? 64 : eval);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Xunit;
namespace Microsoft.EntityFrameworkCore.Metadata
{
public class MySqlBuilderExtensionsTest
{
[Fact]
public void Can_set_column_name()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasColumnName("Eman");
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasColumnName("MyNameIs");
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name");
Assert.Equal("Name", property.Name);
Assert.Equal("MyNameIs", property.Relational().ColumnName);
Assert.Equal("MyNameIs", property.MySql().ColumnName);
}
[Fact]
public void Can_set_column_type()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasColumnType("nvarchar(42)");
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasColumnType("nvarchar(DA)");
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name");
Assert.Equal("nvarchar(DA)", property.Relational().ColumnType);
Assert.Equal("nvarchar(DA)", property.MySql().ColumnType);
}
[Fact]
public void Can_set_column_default_expression()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasDefaultValueSql("VanillaCoke");
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name");
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasDefaultValueSql("CherryCoke");
Assert.Equal("CherryCoke", property.Relational().DefaultValueSql);
Assert.Equal("CherryCoke", property.MySql().DefaultValueSql);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
}
[Fact]
public void Setting_column_default_expression_does_not_modify_explicitly_set_value_generated()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.ValueGeneratedNever()
.HasDefaultValueSql("VanillaCoke");
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name");
Assert.Equal(ValueGenerated.Never, property.ValueGenerated);
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasDefaultValueSql("CherryCoke");
Assert.Equal("CherryCoke", property.Relational().DefaultValueSql);
Assert.Equal("CherryCoke", property.MySql().DefaultValueSql);
Assert.Equal(ValueGenerated.Never, property.ValueGenerated);
}
[Fact]
public void Can_create_named_sequence_decimal_with_specific_facets()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence<decimal>("Snook")
.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
ValidateNamedSpecificSequence<decimal>(modelBuilder.Model.Relational().FindSequence("Snook"));
ValidateNamedSpecificSequence<decimal>(modelBuilder.Model.MySql().FindSequence("Snook"));
}
[Fact]
public void Can_create_named_sequence_decimal_with_specific_facets_non_generic()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence(typeof(decimal), "Snook")
.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
ValidateNamedSpecificSequence<decimal>(modelBuilder.Model.Relational().FindSequence("Snook"));
ValidateNamedSpecificSequence<decimal>(modelBuilder.Model.MySql().FindSequence("Snook"));
}
[Fact]
public void Can_create_named_sequence_decimal_with_specific_facets_using_nested_closure()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence<decimal>(
"Snook", b =>
{
b.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
});
ValidateNamedSpecificSequence<decimal>(modelBuilder.Model.Relational().FindSequence("Snook"));
ValidateNamedSpecificSequence<decimal>(modelBuilder.Model.MySql().FindSequence("Snook"));
}
[Fact]
public void Can_create_named_sequence_decimal_with_specific_facets_using_nested_closure_non_generic()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence(
typeof(decimal), "Snook", b =>
{
b.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
});
ValidateNamedSpecificSequence<decimal>(modelBuilder.Model.Relational().FindSequence("Snook"));
ValidateNamedSpecificSequence<decimal>(modelBuilder.Model.MySql().FindSequence("Snook"));
}
[Fact]
public void Can_set_column_computed_expression()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasComputedColumnSql("VanillaCoke");
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name");
Assert.Equal(ValueGenerated.OnAddOrUpdate, property.ValueGenerated);
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasComputedColumnSql("CherryCoke");
Assert.Equal("CherryCoke", property.Relational().ComputedColumnSql);
Assert.Equal("CherryCoke", property.MySql().ComputedColumnSql);
Assert.Equal(ValueGenerated.OnAddOrUpdate, property.ValueGenerated);
}
[Fact]
public void Setting_column_column_computed_expression_does_not_modify_explicitly_set_value_generated()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.ValueGeneratedNever()
.HasComputedColumnSql("VanillaCoke");
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Name");
Assert.Equal(ValueGenerated.Never, property.ValueGenerated);
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasComputedColumnSql("CherryCoke");
Assert.Equal("CherryCoke", property.Relational().ComputedColumnSql);
Assert.Equal("CherryCoke", property.MySql().ComputedColumnSql);
Assert.Equal(ValueGenerated.Never, property.ValueGenerated);
}
[Fact]
public void Can_set_column_default_value()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Offset)
.HasDefaultValue(new DateTimeOffset(1973, 9, 3, 0, 10, 0, new TimeSpan(1, 0, 0)));
modelBuilder
.Entity<Customer>()
.Property(e => e.Offset)
.HasDefaultValue(new DateTimeOffset(2006, 9, 19, 19, 0, 0, new TimeSpan(-8, 0, 0)));
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Offset");
Assert.Equal(new DateTimeOffset(2006, 9, 19, 19, 0, 0, new TimeSpan(-8, 0, 0)), property.Relational().DefaultValue);
Assert.Equal(new DateTimeOffset(2006, 9, 19, 19, 0, 0, new TimeSpan(-8, 0, 0)), property.MySql().DefaultValue);
}
[Fact]
public void Setting_column_default_value_does_not_modify_explicitly_set_value_generated()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Offset)
.ValueGeneratedOnAddOrUpdate()
.HasDefaultValue(new DateTimeOffset(1973, 9, 3, 0, 10, 0, new TimeSpan(1, 0, 0)));
modelBuilder
.Entity<Customer>()
.Property(e => e.Offset)
.HasDefaultValue(new DateTimeOffset(2006, 9, 19, 19, 0, 0, new TimeSpan(-8, 0, 0)));
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty("Offset");
Assert.Equal(new DateTimeOffset(2006, 9, 19, 19, 0, 0, new TimeSpan(-8, 0, 0)), property.Relational().DefaultValue);
Assert.Equal(new DateTimeOffset(2006, 9, 19, 19, 0, 0, new TimeSpan(-8, 0, 0)), property.MySql().DefaultValue);
Assert.Equal(ValueGenerated.OnAddOrUpdate, property.ValueGenerated);
}
[Fact]
public void Setting_column_default_value_overrides_default_sql_and_computed_column_sql()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.HasComputedColumnSql("0")
.HasDefaultValueSql("1")
.HasDefaultValue(2);
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty(nameof(Customer.Id));
Assert.Equal(2, property.MySql().DefaultValue);
Assert.Null(property.MySql().DefaultValueSql);
Assert.Null(property.MySql().ComputedColumnSql);
}
[Fact]
public void Setting_column_default_sql_overrides_default_value_and_computed_column_sql()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.HasComputedColumnSql("0")
.HasDefaultValue(2)
.HasDefaultValueSql("1");
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty(nameof(Customer.Id));
Assert.Equal("1", property.MySql().DefaultValueSql);
Assert.Null(property.MySql().DefaultValue);
Assert.Null(property.MySql().ComputedColumnSql);
}
[Fact]
public void Setting_computed_column_sql_overrides_default_value_and_column_default_sql()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.HasDefaultValueSql("1")
.HasDefaultValue(2)
.HasComputedColumnSql("0");
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty(nameof(Customer.Id));
Assert.Equal("0", property.MySql().ComputedColumnSql);
Assert.Null(property.MySql().DefaultValueSql);
Assert.Null(property.MySql().DefaultValue);
}
[Fact]
public void Setting_MySql_default_sql_is_higher_priority_than_relational_default_values()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.HasDefaultValueSql("1")
.HasComputedColumnSql("0")
.HasDefaultValue(2);
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty(nameof(Customer.Id));
Assert.Null(property.Relational().DefaultValueSql);
Assert.Null(property.MySql().DefaultValueSql);
Assert.Equal(2, property.Relational().DefaultValue);
Assert.Equal(2, property.MySql().DefaultValue);
Assert.Null(property.Relational().ComputedColumnSql);
Assert.Null(property.MySql().ComputedColumnSql);
}
[Fact]
public void Setting_MySql_default_value_is_higher_priority_than_relational_default_values()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.HasDefaultValue(2)
.HasDefaultValueSql("1")
.HasComputedColumnSql("0");
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty(nameof(Customer.Id));
Assert.Null(property.Relational().DefaultValue);
Assert.Null(property.MySql().DefaultValue);
Assert.Null(property.Relational().DefaultValueSql);
Assert.Null(property.MySql().DefaultValueSql);
Assert.Equal("0", property.Relational().ComputedColumnSql);
Assert.Equal("0", property.MySql().ComputedColumnSql);
}
[Fact]
public void Setting_MySql_computed_column_sql_is_higher_priority_than_relational_default_values()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.HasComputedColumnSql("0")
.HasDefaultValue(2)
.HasDefaultValueSql("1");
var property = modelBuilder.Model.FindEntityType(typeof(Customer)).FindProperty(nameof(Customer.Id));
Assert.Null(property.Relational().ComputedColumnSql);
Assert.Null(property.MySql().ComputedColumnSql);
Assert.Null(property.Relational().DefaultValue);
Assert.Null(property.MySql().DefaultValue);
Assert.Equal("1", property.Relational().DefaultValueSql);
Assert.Equal("1", property.MySql().DefaultValueSql);
}
[Fact]
public void Setting_column_default_value_does_not_set_identity_column()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.HasDefaultValue(1);
var model = modelBuilder.Model;
var property = model.FindEntityType(typeof(Customer)).FindProperty(nameof(Customer.Id));
Assert.Null(property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
}
[Fact]
public void Setting_column_default_value_sql_does_not_set_identity_column()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.HasDefaultValueSql("1");
var model = modelBuilder.Model;
var property = model.FindEntityType(typeof(Customer)).FindProperty(nameof(Customer.Id));
Assert.Null(property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
}
[Fact]
public void Setting_MySql_identity_column_is_higher_priority_than_relational_default_values()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.UseMySqlIdentityColumn()
.HasDefaultValue(1)
.HasDefaultValueSql("1")
.HasComputedColumnSql("0");
var model = modelBuilder.Model;
var property = model.FindEntityType(typeof(Customer)).FindProperty(nameof(Customer.Id));
Assert.Equal(MySqlValueGenerationStrategy.IdentityColumn, property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
Assert.Null(property.Relational().DefaultValue);
Assert.Null(property.MySql().DefaultValue);
Assert.Null(property.Relational().DefaultValueSql);
Assert.Null(property.MySql().DefaultValueSql);
Assert.Equal("0", property.Relational().ComputedColumnSql);
Assert.Null(property.MySql().ComputedColumnSql);
}
[Fact]
public void Can_set_key_name()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.HasKey(e => e.Id)
.HasName("KeyLimePie")
.HasName("LemonSupreme");
var key = modelBuilder.Model.FindEntityType(typeof(Customer)).FindPrimaryKey();
Assert.Equal("LemonSupreme", key.Relational().Name);
}
[Fact]
public void Can_set_foreign_key_name_for_one_to_many()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>().HasMany(e => e.Orders).WithOne(e => e.Customer)
.HasConstraintName("LemonSupreme")
.HasConstraintName("ChocolateLimes");
var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order)).GetForeignKeys().Single(fk => fk.PrincipalEntityType.ClrType == typeof(Customer));
Assert.Equal("ChocolateLimes", foreignKey.Relational().Name);
modelBuilder
.Entity<Customer>().HasMany(e => e.Orders).WithOne(e => e.Customer)
.HasConstraintName(null);
Assert.Equal("FK_Order_Customer_CustomerId", foreignKey.Relational().Name);
}
[Fact]
public void Can_set_foreign_key_name_for_one_to_many_with_FK_specified()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>().HasMany(e => e.Orders).WithOne(e => e.Customer)
.HasForeignKey(e => e.CustomerId)
.HasConstraintName("LemonSupreme")
.HasConstraintName("ChocolateLimes");
var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order)).GetForeignKeys().Single(fk => fk.PrincipalEntityType.ClrType == typeof(Customer));
Assert.Equal("ChocolateLimes", foreignKey.Relational().Name);
}
[Fact]
public void Can_set_foreign_key_name_for_many_to_one()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Order>().HasOne(e => e.Customer).WithMany(e => e.Orders)
.HasConstraintName("LemonSupreme")
.HasConstraintName("ChocolateLimes");
var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order)).GetForeignKeys().Single(fk => fk.PrincipalEntityType.ClrType == typeof(Customer));
Assert.Equal("ChocolateLimes", foreignKey.Relational().Name);
modelBuilder
.Entity<Order>().HasOne(e => e.Customer).WithMany(e => e.Orders)
.HasConstraintName(null);
Assert.Equal("FK_Order_Customer_CustomerId", foreignKey.Relational().Name);
}
[Fact]
public void Can_set_foreign_key_name_for_many_to_one_with_FK_specified()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Order>().HasOne(e => e.Customer).WithMany(e => e.Orders)
.HasForeignKey(e => e.CustomerId)
.HasConstraintName("LemonSupreme")
.HasConstraintName("ChocolateLimes");
var foreignKey = modelBuilder.Model.FindEntityType(typeof(Order)).GetForeignKeys().Single(fk => fk.PrincipalEntityType.ClrType == typeof(Customer));
Assert.Equal("ChocolateLimes", foreignKey.Relational().Name);
}
[Fact]
public void Can_set_foreign_key_name_for_one_to_one()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Order>().HasOne(e => e.Details).WithOne(e => e.Order)
.HasPrincipalKey<Order>(e => e.OrderId)
.HasConstraintName("LemonSupreme")
.HasConstraintName("ChocolateLimes");
var foreignKey = modelBuilder.Model.FindEntityType(typeof(OrderDetails)).GetForeignKeys().Single();
Assert.Equal("ChocolateLimes", foreignKey.Relational().Name);
modelBuilder
.Entity<Order>().HasOne(e => e.Details).WithOne(e => e.Order)
.HasConstraintName(null);
Assert.Equal("FK_OrderDetails_Order_OrderId", foreignKey.Relational().Name);
}
[Fact]
public void Can_set_foreign_key_name_for_one_to_one_with_FK_specified()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Order>().HasOne(e => e.Details).WithOne(e => e.Order)
.HasForeignKey<OrderDetails>(e => e.Id)
.HasConstraintName("LemonSupreme")
.HasConstraintName("ChocolateLimes");
var foreignKey = modelBuilder.Model.FindEntityType(typeof(OrderDetails)).GetForeignKeys().Single();
Assert.Equal("ChocolateLimes", foreignKey.Relational().Name);
}
[Fact]
public void Can_set_index_name()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.HasIndex(e => e.Id)
.HasName("Eeeendeeex")
.HasName("Dexter");
var index = modelBuilder.Model.FindEntityType(typeof(Customer)).GetIndexes().Single();
Assert.Equal("Dexter", index.Relational().Name);
}
[Fact]
public void Can_set_index_filter()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.HasIndex(e => e.Id)
.HasFilter("Generic expression")
.HasFilter("MySql-specific expression");
var index = modelBuilder.Model.FindEntityType(typeof(Customer)).GetIndexes().Single();
Assert.Equal("MySql-specific expression", index.Relational().Filter);
}
[Fact]
public void Can_set_table_name()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.ToTable("Customizer")
.ToTable("Custardizer");
var entityType = modelBuilder.Model.FindEntityType(typeof(Customer));
Assert.Equal("Customer", entityType.DisplayName());
Assert.Equal("Custardizer", entityType.Relational().TableName);
Assert.Equal("Custardizer", entityType.MySql().TableName);
}
[Fact]
public void Can_set_table_name_non_generic()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity(typeof(Customer))
.ToTable("Customizer")
.ToTable("Custardizer");
var entityType = modelBuilder.Model.FindEntityType(typeof(Customer));
Assert.Equal("Customer", entityType.DisplayName());
Assert.Equal("Custardizer", entityType.Relational().TableName);
Assert.Equal("Custardizer", entityType.MySql().TableName);
}
[Fact]
public void Can_set_table_and_schema_name()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.ToTable("Customizer", "db0")
.ToTable("Custardizer", "dbOh");
var entityType = modelBuilder.Model.FindEntityType(typeof(Customer));
Assert.Equal("Customer", entityType.DisplayName());
Assert.Equal("Custardizer", entityType.Relational().TableName);
Assert.Equal("Custardizer", entityType.MySql().TableName);
Assert.Equal("dbOh", entityType.Relational().Schema);
Assert.Equal("dbOh", entityType.MySql().Schema);
}
[Fact]
public void Can_set_table_and_schema_name_non_generic()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity(typeof(Customer))
.ToTable("Customizer", "db0")
.ToTable("Custardizer", "dbOh");
var entityType = modelBuilder.Model.FindEntityType(typeof(Customer));
Assert.Equal("Customer", entityType.DisplayName());
Assert.Equal("Custardizer", entityType.Relational().TableName);
Assert.Equal("Custardizer", entityType.MySql().TableName);
Assert.Equal("dbOh", entityType.Relational().Schema);
Assert.Equal("dbOh", entityType.MySql().Schema);
}
[Fact]
public void Can_set_MemoryOptimized()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.ForMySqlIsMemoryOptimized();
var entityType = modelBuilder.Model.FindEntityType(typeof(Customer));
Assert.True(entityType.MySql().IsMemoryOptimized);
modelBuilder
.Entity<Customer>()
.ForMySqlIsMemoryOptimized(false);
Assert.False(entityType.MySql().IsMemoryOptimized);
}
[Fact]
public void Can_set_MemoryOptimized_non_generic()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity(typeof(Customer))
.ForMySqlIsMemoryOptimized();
var entityType = modelBuilder.Model.FindEntityType(typeof(Customer));
Assert.True(entityType.MySql().IsMemoryOptimized);
modelBuilder
.Entity(typeof(Customer))
.ForMySqlIsMemoryOptimized(false);
Assert.False(entityType.MySql().IsMemoryOptimized);
}
[Fact]
public void Can_set_index_clustering()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.HasIndex(e => e.Id)
.ForMySqlIsClustered();
var index = modelBuilder.Model.FindEntityType(typeof(Customer)).GetIndexes().Single();
Assert.True(index.MySql().IsClustered.Value);
}
[Fact]
public void Can_set_key_clustering()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.HasKey(e => e.Id)
.ForMySqlIsClustered();
var key = modelBuilder.Model.FindEntityType(typeof(Customer)).FindPrimaryKey();
Assert.True(key.MySql().IsClustered.Value);
}
[Fact]
public void Can_set_index_include()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.ForMySqlHasIndex(e => e.Name)
.ForMySqlInclude(e => e.Offset);
var index = modelBuilder.Model.FindEntityType(typeof(Customer)).GetIndexes().Single();
Assert.NotNull(index.MySql().IncludeProperties);
Assert.Collection(index.MySql().IncludeProperties,
c => Assert.Equal(nameof(Customer.Offset), c));
}
[Fact]
public void Can_set_index_include_after_unique_using_generic_builder()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.ForMySqlHasIndex(e => e.Name)
.IsUnique()
.ForMySqlInclude(e => e.Offset);
var index = modelBuilder.Model.FindEntityType(typeof(Customer)).GetIndexes().Single();
Assert.True(index.IsUnique);
Assert.NotNull(index.MySql().IncludeProperties);
Assert.Collection(index.MySql().IncludeProperties,
c => Assert.Equal(nameof(Customer.Offset), c));
}
[Fact]
public void Can_set_index_include_after_annotation_using_generic_builder()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.ForMySqlHasIndex(e => e.Name)
.HasAnnotation("Test:ShouldBeTrue", true)
.ForMySqlInclude(e => e.Offset);
var index = modelBuilder.Model.FindEntityType(typeof(Customer)).GetIndexes().Single();
var annotation = index.FindAnnotation("Test:ShouldBeTrue");
Assert.NotNull(annotation);
Assert.True(annotation.Value as bool?);
Assert.NotNull(index.MySql().IncludeProperties);
Assert.Collection(index.MySql().IncludeProperties,
c => Assert.Equal(nameof(Customer.Offset), c));
}
[Fact]
public void Can_set_index_include_non_generic()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.HasIndex(e => e.Name)
.ForMySqlInclude(nameof(Customer.Offset));
var index = modelBuilder.Model.FindEntityType(typeof(Customer)).GetIndexes().Single();
Assert.NotNull(index.MySql().IncludeProperties);
Assert.Collection(index.MySql().IncludeProperties,
c => Assert.Equal(nameof(Customer.Offset), c));
}
[Fact]
public void Can_set_sequences_for_model()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder.ForMySqlUseSequenceHiLo();
var relationalExtensions = modelBuilder.Model.Relational();
var mySqlExtensions = modelBuilder.Model.MySql();
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, mySqlExtensions.ValueGenerationStrategy);
Assert.Equal(MySqlModelAnnotations.DefaultHiLoSequenceName, mySqlExtensions.HiLoSequenceName);
Assert.Null(mySqlExtensions.HiLoSequenceSchema);
Assert.NotNull(relationalExtensions.FindSequence(MySqlModelAnnotations.DefaultHiLoSequenceName));
Assert.NotNull(mySqlExtensions.FindSequence(MySqlModelAnnotations.DefaultHiLoSequenceName));
}
[Fact]
public void Can_set_sequences_with_name_for_model()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder.ForMySqlUseSequenceHiLo("Snook");
var relationalExtensions = modelBuilder.Model.Relational();
var mySqlExtensions = modelBuilder.Model.MySql();
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, mySqlExtensions.ValueGenerationStrategy);
Assert.Equal("Snook", mySqlExtensions.HiLoSequenceName);
Assert.Null(mySqlExtensions.HiLoSequenceSchema);
Assert.NotNull(relationalExtensions.FindSequence("Snook"));
var sequence = mySqlExtensions.FindSequence("Snook");
Assert.Equal("Snook", sequence.Name);
Assert.Null(sequence.Schema);
Assert.Equal(10, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.ClrType);
}
[Fact]
public void Can_set_sequences_with_schema_and_name_for_model()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder.ForMySqlUseSequenceHiLo("Snook", "Tasty");
var relationalExtensions = modelBuilder.Model.Relational();
var mySqlExtensions = modelBuilder.Model.MySql();
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, mySqlExtensions.ValueGenerationStrategy);
Assert.Equal("Snook", mySqlExtensions.HiLoSequenceName);
Assert.Equal("Tasty", mySqlExtensions.HiLoSequenceSchema);
Assert.NotNull(relationalExtensions.FindSequence("Snook", "Tasty"));
var sequence = mySqlExtensions.FindSequence("Snook", "Tasty");
Assert.Equal("Snook", sequence.Name);
Assert.Equal("Tasty", sequence.Schema);
Assert.Equal(10, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.ClrType);
}
[Fact]
public void Can_set_use_of_existing_relational_sequence_for_model()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence<int>("Snook", "Tasty")
.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
modelBuilder.ForMySqlUseSequenceHiLo("Snook", "Tasty");
var relationalExtensions = modelBuilder.Model.Relational();
var mySqlExtensions = modelBuilder.Model.MySql();
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, mySqlExtensions.ValueGenerationStrategy);
Assert.Equal("Snook", mySqlExtensions.HiLoSequenceName);
Assert.Equal("Tasty", mySqlExtensions.HiLoSequenceSchema);
ValidateSchemaNamedSpecificSequence(relationalExtensions.FindSequence("Snook", "Tasty"));
ValidateSchemaNamedSpecificSequence(mySqlExtensions.FindSequence("Snook", "Tasty"));
}
[Fact]
public void Can_set_use_of_existing_SQL_sequence_for_model()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence<int>("Snook", "Tasty")
.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
modelBuilder.ForMySqlUseSequenceHiLo("Snook", "Tasty");
var relationalExtensions = modelBuilder.Model.Relational();
var mySqlExtensions = modelBuilder.Model.MySql();
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, mySqlExtensions.ValueGenerationStrategy);
Assert.Equal("Snook", mySqlExtensions.HiLoSequenceName);
Assert.Equal("Tasty", mySqlExtensions.HiLoSequenceSchema);
ValidateSchemaNamedSpecificSequence(relationalExtensions.FindSequence("Snook", "Tasty"));
ValidateSchemaNamedSpecificSequence(mySqlExtensions.FindSequence("Snook", "Tasty"));
}
private static void ValidateSchemaNamedSpecificSequence(ISequence sequence)
{
Assert.Equal("Snook", sequence.Name);
Assert.Equal("Tasty", sequence.Schema);
Assert.Equal(11, sequence.IncrementBy);
Assert.Equal(1729, sequence.StartValue);
Assert.Equal(111, sequence.MinValue);
Assert.Equal(2222, sequence.MaxValue);
Assert.Same(typeof(int), sequence.ClrType);
}
[Fact]
public void Can_set_identities_for_model()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder.ForMySqlUseIdentityColumns();
var relationalExtensions = modelBuilder.Model.Relational();
var mySqlExtensions = modelBuilder.Model.MySql();
Assert.Equal(MySqlValueGenerationStrategy.IdentityColumn, mySqlExtensions.ValueGenerationStrategy);
Assert.Null(mySqlExtensions.HiLoSequenceName);
Assert.Null(mySqlExtensions.HiLoSequenceSchema);
Assert.Null(relationalExtensions.FindSequence(MySqlModelAnnotations.DefaultHiLoSequenceName));
Assert.Null(mySqlExtensions.FindSequence(MySqlModelAnnotations.DefaultHiLoSequenceName));
}
[Fact]
public void Setting_MySql_identities_for_model_is_lower_priority_than_relational_default_values()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>(
eb =>
{
eb.Property(e => e.Id).HasDefaultValue(1);
eb.Property(e => e.Name).HasComputedColumnSql("Default");
eb.Property(e => e.Offset).HasDefaultValueSql("Now");
});
modelBuilder.ForMySqlUseIdentityColumns();
var model = modelBuilder.Model;
var idProperty = model.FindEntityType(typeof(Customer)).FindProperty(nameof(Customer.Id));
Assert.Null(idProperty.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, idProperty.ValueGenerated);
Assert.Equal(1, idProperty.Relational().DefaultValue);
Assert.Equal(1, idProperty.MySql().DefaultValue);
var nameProperty = model.FindEntityType(typeof(Customer)).FindProperty(nameof(Customer.Name));
Assert.Null(nameProperty.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAddOrUpdate, nameProperty.ValueGenerated);
Assert.Equal("Default", nameProperty.Relational().ComputedColumnSql);
Assert.Equal("Default", nameProperty.MySql().ComputedColumnSql);
var offsetProperty = model.FindEntityType(typeof(Customer)).FindProperty(nameof(Customer.Offset));
Assert.Null(offsetProperty.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, offsetProperty.ValueGenerated);
Assert.Equal("Now", offsetProperty.Relational().DefaultValueSql);
Assert.Equal("Now", offsetProperty.MySql().DefaultValueSql);
}
[Fact]
public void Can_set_sequence_for_property()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ForMySqlUseSequenceHiLo();
var model = modelBuilder.Model;
var property = model.FindEntityType(typeof(Customer)).FindProperty("Id");
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
Assert.Equal(MySqlModelAnnotations.DefaultHiLoSequenceName, property.MySql().HiLoSequenceName);
Assert.NotNull(model.Relational().FindSequence(MySqlModelAnnotations.DefaultHiLoSequenceName));
Assert.NotNull(model.MySql().FindSequence(MySqlModelAnnotations.DefaultHiLoSequenceName));
}
[Fact]
public void Can_set_sequences_with_name_for_property()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ForMySqlUseSequenceHiLo("Snook");
var model = modelBuilder.Model;
var property = model.FindEntityType(typeof(Customer)).FindProperty("Id");
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
Assert.Equal("Snook", property.MySql().HiLoSequenceName);
Assert.Null(property.MySql().HiLoSequenceSchema);
Assert.NotNull(model.Relational().FindSequence("Snook"));
var sequence = model.MySql().FindSequence("Snook");
Assert.Equal("Snook", sequence.Name);
Assert.Null(sequence.Schema);
Assert.Equal(10, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.ClrType);
}
[Fact]
public void Can_set_sequences_with_schema_and_name_for_property()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ForMySqlUseSequenceHiLo("Snook", "Tasty");
var model = modelBuilder.Model;
var property = model.FindEntityType(typeof(Customer)).FindProperty("Id");
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
Assert.Equal("Snook", property.MySql().HiLoSequenceName);
Assert.Equal("Tasty", property.MySql().HiLoSequenceSchema);
Assert.NotNull(model.MySql().FindSequence("Snook", "Tasty"));
var sequence = model.Relational().FindSequence("Snook", "Tasty");
Assert.Equal("Snook", sequence.Name);
Assert.Equal("Tasty", sequence.Schema);
Assert.Equal(10, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.ClrType);
}
[Fact]
public void Can_set_use_of_existing_relational_sequence_for_property()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence<int>("Snook", "Tasty")
.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ForMySqlUseSequenceHiLo("Snook", "Tasty");
var model = modelBuilder.Model;
var property = model.FindEntityType(typeof(Customer)).FindProperty("Id");
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
Assert.Equal("Snook", property.MySql().HiLoSequenceName);
Assert.Equal("Tasty", property.MySql().HiLoSequenceSchema);
ValidateSchemaNamedSpecificSequence(model.Relational().FindSequence("Snook", "Tasty"));
ValidateSchemaNamedSpecificSequence(model.MySql().FindSequence("Snook", "Tasty"));
}
[Fact]
public void Can_set_use_of_existing_relational_sequence_for_property_using_nested_closure()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence<int>("Snook", "Tasty", b => b.IncrementsBy(11).StartsAt(1729).HasMin(111).HasMax(2222))
.Entity<Customer>()
.Property(e => e.Id)
.ForMySqlUseSequenceHiLo("Snook", "Tasty");
var model = modelBuilder.Model;
var property = model.FindEntityType(typeof(Customer)).FindProperty("Id");
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
Assert.Equal("Snook", property.MySql().HiLoSequenceName);
Assert.Equal("Tasty", property.MySql().HiLoSequenceSchema);
ValidateSchemaNamedSpecificSequence(model.Relational().FindSequence("Snook", "Tasty"));
ValidateSchemaNamedSpecificSequence(model.MySql().FindSequence("Snook", "Tasty"));
}
[Fact]
public void Can_set_use_of_existing_SQL_sequence_for_property()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence<int>("Snook", "Tasty")
.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ForMySqlUseSequenceHiLo("Snook", "Tasty");
var model = modelBuilder.Model;
var property = model.FindEntityType(typeof(Customer)).FindProperty("Id");
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
Assert.Equal("Snook", property.MySql().HiLoSequenceName);
Assert.Equal("Tasty", property.MySql().HiLoSequenceSchema);
ValidateSchemaNamedSpecificSequence(model.Relational().FindSequence("Snook", "Tasty"));
ValidateSchemaNamedSpecificSequence(model.MySql().FindSequence("Snook", "Tasty"));
}
[Fact]
public void Can_set_use_of_existing_SQL_sequence_for_property_using_nested_closure()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence<int>(
"Snook", "Tasty", b =>
{
b.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
})
.Entity<Customer>()
.Property(e => e.Id)
.ForMySqlUseSequenceHiLo("Snook", "Tasty");
var model = modelBuilder.Model;
var property = model.FindEntityType(typeof(Customer)).FindProperty("Id");
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
Assert.Equal("Snook", property.MySql().HiLoSequenceName);
Assert.Equal("Tasty", property.MySql().HiLoSequenceSchema);
ValidateSchemaNamedSpecificSequence(model.Relational().FindSequence("Snook", "Tasty"));
ValidateSchemaNamedSpecificSequence(model.MySql().FindSequence("Snook", "Tasty"));
}
[Fact]
public void Can_set_identities_for_property()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.UseMySqlIdentityColumn();
var model = modelBuilder.Model;
var property = model.FindEntityType(typeof(Customer)).FindProperty("Id");
Assert.Equal(MySqlValueGenerationStrategy.IdentityColumn, property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
Assert.Null(property.MySql().HiLoSequenceName);
Assert.Null(model.Relational().FindSequence(MySqlModelAnnotations.DefaultHiLoSequenceName));
Assert.Null(model.MySql().FindSequence(MySqlModelAnnotations.DefaultHiLoSequenceName));
}
[Fact]
public void Can_create_named_sequence()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder.HasSequence("Snook");
Assert.NotNull(modelBuilder.Model.Relational().FindSequence("Snook"));
var sequence = modelBuilder.Model.MySql().FindSequence("Snook");
Assert.Equal("Snook", sequence.Name);
Assert.Null(sequence.Schema);
Assert.Equal(1, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.ClrType);
}
[Fact]
public void Can_create_schema_named_sequence()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder.HasSequence("Snook", "Tasty");
Assert.NotNull(modelBuilder.Model.Relational().FindSequence("Snook", "Tasty"));
var sequence = modelBuilder.Model.MySql().FindSequence("Snook", "Tasty");
Assert.Equal("Snook", sequence.Name);
Assert.Equal("Tasty", sequence.Schema);
Assert.Equal(1, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.ClrType);
}
[Fact]
public void Can_create_named_sequence_with_specific_facets()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence<int>("Snook")
.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
ValidateNamedSpecificSequence<int>(modelBuilder.Model.Relational().FindSequence("Snook"));
ValidateNamedSpecificSequence<int>(modelBuilder.Model.MySql().FindSequence("Snook"));
}
[Fact]
public void Can_create_named_sequence_with_specific_facets_non_generic()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence(typeof(int), "Snook")
.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
ValidateNamedSpecificSequence<int>(modelBuilder.Model.Relational().FindSequence("Snook"));
ValidateNamedSpecificSequence<int>(modelBuilder.Model.MySql().FindSequence("Snook"));
}
[Fact]
public void Can_create_named_sequence_with_specific_facets_using_nested_closure()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence<int>(
"Snook", b =>
{
b.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
});
ValidateNamedSpecificSequence<int>(modelBuilder.Model.Relational().FindSequence("Snook"));
ValidateNamedSpecificSequence<int>(modelBuilder.Model.MySql().FindSequence("Snook"));
}
[Fact]
public void Can_create_named_sequence_with_specific_facets_using_nested_closure_non_generic()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence(
typeof(int), "Snook", b =>
{
b.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
});
ValidateNamedSpecificSequence<int>(modelBuilder.Model.Relational().FindSequence("Snook"));
ValidateNamedSpecificSequence<int>(modelBuilder.Model.MySql().FindSequence("Snook"));
}
private static void ValidateNamedSpecificSequence<T>(ISequence sequence)
{
Assert.Equal("Snook", sequence.Name);
Assert.Null(sequence.Schema);
Assert.Equal(11, sequence.IncrementBy);
Assert.Equal(1729, sequence.StartValue);
Assert.Equal(111, sequence.MinValue);
Assert.Equal(2222, sequence.MaxValue);
Assert.Same(typeof(T), sequence.ClrType);
}
[Fact]
public void Can_create_schema_named_sequence_with_specific_facets()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence<int>("Snook", "Tasty")
.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
ValidateSchemaNamedSpecificSequence(modelBuilder.Model.Relational().FindSequence("Snook", "Tasty"));
ValidateSchemaNamedSpecificSequence(modelBuilder.Model.MySql().FindSequence("Snook", "Tasty"));
}
[Fact]
public void Can_create_schema_named_sequence_with_specific_facets_non_generic()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence(typeof(int), "Snook", "Tasty")
.IncrementsBy(11)
.StartsAt(1729)
.HasMin(111)
.HasMax(2222);
ValidateSchemaNamedSpecificSequence(modelBuilder.Model.Relational().FindSequence("Snook", "Tasty"));
ValidateSchemaNamedSpecificSequence(modelBuilder.Model.MySql().FindSequence("Snook", "Tasty"));
}
[Fact]
public void Can_create_schema_named_sequence_with_specific_facets_using_nested_closure()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence<int>("Snook", "Tasty", b => b.IncrementsBy(11).StartsAt(1729).HasMin(111).HasMax(2222));
ValidateSchemaNamedSpecificSequence(modelBuilder.Model.Relational().FindSequence("Snook", "Tasty"));
ValidateSchemaNamedSpecificSequence(modelBuilder.Model.MySql().FindSequence("Snook", "Tasty"));
}
[Fact]
public void Can_create_schema_named_sequence_with_specific_facets_using_nested_closure_non_generic()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.HasSequence(typeof(int), "Snook", "Tasty", b => b.IncrementsBy(11).StartsAt(1729).HasMin(111).HasMax(2222));
ValidateSchemaNamedSpecificSequence(modelBuilder.Model.Relational().FindSequence("Snook", "Tasty"));
ValidateSchemaNamedSpecificSequence(modelBuilder.Model.MySql().FindSequence("Snook", "Tasty"));
}
[Fact]
public void MySql_entity_methods_dont_break_out_of_the_generics()
{
var modelBuilder = CreateConventionModelBuilder();
AssertIsGeneric(
modelBuilder
.Entity<Customer>()
.ToTable("Will"));
AssertIsGeneric(
modelBuilder
.Entity<Customer>()
.ToTable("Jay", "Simon"));
}
[Fact]
public void MySql_entity_methods_have_non_generic_overloads()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity(typeof(Customer))
.ToTable("Will");
modelBuilder
.Entity<Customer>()
.ToTable("Jay", "Simon");
}
[Fact]
public void MySql_property_methods_dont_break_out_of_the_generics()
{
var modelBuilder = CreateConventionModelBuilder();
AssertIsGeneric(
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasColumnName("Will"));
AssertIsGeneric(
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasColumnType("Jay"));
AssertIsGeneric(
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasDefaultValueSql("Simon"));
AssertIsGeneric(
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasComputedColumnSql("Simon"));
AssertIsGeneric(
modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.HasDefaultValue("Neil"));
AssertIsGeneric(
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ForMySqlUseSequenceHiLo());
AssertIsGeneric(
modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.UseMySqlIdentityColumn());
}
[Fact]
public void MySql_property_methods_have_non_generic_overloads()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity(typeof(Customer))
.Property(typeof(string), "Name")
.HasColumnName("Will");
modelBuilder
.Entity<Customer>()
.Property(typeof(string), "Name")
.HasColumnName("Jay");
modelBuilder
.Entity(typeof(Customer))
.Property(typeof(string), "Name")
.HasColumnType("Simon");
modelBuilder
.Entity<Customer>()
.Property(typeof(string), "Name")
.HasColumnType("Neil");
modelBuilder
.Entity(typeof(Customer))
.Property(typeof(string), "Name")
.HasDefaultValueSql("Simon");
modelBuilder
.Entity<Customer>()
.Property(typeof(string), "Name")
.HasDefaultValueSql("Neil");
modelBuilder
.Entity(typeof(Customer))
.Property(typeof(string), "Name")
.HasDefaultValue("Simon");
modelBuilder
.Entity<Customer>()
.Property(typeof(string), "Name")
.HasDefaultValue("Neil");
modelBuilder
.Entity(typeof(Customer))
.Property(typeof(string), "Name")
.HasComputedColumnSql("Simon");
modelBuilder
.Entity<Customer>()
.Property(typeof(string), "Name")
.HasComputedColumnSql("Neil");
modelBuilder
.Entity(typeof(Customer))
.Property(typeof(int), "Id")
.ForMySqlUseSequenceHiLo();
modelBuilder
.Entity<Customer>()
.Property(typeof(int), "Id")
.ForMySqlUseSequenceHiLo();
modelBuilder
.Entity(typeof(Customer))
.Property(typeof(int), "Id")
.UseMySqlIdentityColumn();
modelBuilder
.Entity<Customer>()
.Property(typeof(int), "Id")
.UseMySqlIdentityColumn();
}
[Fact]
public void MySql_relationship_methods_dont_break_out_of_the_generics()
{
var modelBuilder = CreateConventionModelBuilder();
AssertIsGeneric(
modelBuilder
.Entity<Customer>().HasMany(e => e.Orders)
.WithOne(e => e.Customer)
.HasConstraintName("Will"));
AssertIsGeneric(
modelBuilder
.Entity<Order>()
.HasOne(e => e.Customer)
.WithMany(e => e.Orders)
.HasConstraintName("Jay"));
AssertIsGeneric(
modelBuilder
.Entity<Order>()
.HasOne(e => e.Details)
.WithOne(e => e.Order)
.HasConstraintName("Simon"));
}
[Fact]
public void MySql_relationship_methods_have_non_generic_overloads()
{
var modelBuilder = CreateConventionModelBuilder();
modelBuilder
.Entity<Customer>().HasMany(typeof(Order), "Orders")
.WithOne("Customer")
.HasConstraintName("Will");
modelBuilder
.Entity<Order>()
.HasOne(e => e.Customer)
.WithMany(e => e.Orders)
.HasConstraintName("Jay");
modelBuilder
.Entity<Order>()
.HasOne(e => e.Details)
.WithOne(e => e.Order)
.HasConstraintName("Simon");
}
[Fact]
public void Can_set_index_name_generic()
{
// this is EFCore.Relational test, however accessing `IndexBuilder<T>` currently goes through SQL server
var modelBuilder = CreateConventionModelBuilder();
var returnedBuilder = modelBuilder
.Entity<Customer>()
.ForMySqlHasIndex(e => e.Name)
.HasName("Eeeendeeex");
AssertIsGeneric(returnedBuilder);
Assert.IsType<IndexBuilder<Customer>>(returnedBuilder);
var index = modelBuilder.Model.FindEntityType(typeof(Customer)).GetIndexes().Single();
Assert.Equal("Eeeendeeex", index.Relational().Name);
}
[Fact]
public void Can_write_index_builder_extension_with_where_clauses_generic()
{
// this is EFCore.Relational test, however accessing `IndexBuilder<T>` currently goes through SQL server
var modelBuilder = CreateConventionModelBuilder();
var returnedBuilder = modelBuilder
.Entity<Customer>()
.ForMySqlHasIndex(e => e.Id)
.HasFilter("[Id] % 2 = 0");
AssertIsGeneric(returnedBuilder);
Assert.IsType<IndexBuilder<Customer>>(returnedBuilder);
var index = modelBuilder.Model.FindEntityType(typeof(Customer)).GetIndexes().Single();
Assert.Equal("[Id] % 2 = 0", index.Relational().Filter);
}
private void AssertIsGeneric(EntityTypeBuilder<Customer> _)
{
}
private void AssertIsGeneric(PropertyBuilder<string> _)
{
}
private void AssertIsGeneric(PropertyBuilder<int> _)
{
}
private void AssertIsGeneric(ReferenceCollectionBuilder<Customer, Order> _)
{
}
private void AssertIsGeneric(ReferenceReferenceBuilder<Order, OrderDetails> _)
{
}
private void AssertIsGeneric(IndexBuilder<Customer> _)
{
}
protected virtual ModelBuilder CreateConventionModelBuilder()
{
return MySqlTestHelpers.Instance.CreateConventionBuilder();
}
private class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public DateTimeOffset Offset { get; set; }
public IEnumerable<Order> Orders { get; set; }
}
private class Order
{
public int OrderId { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
public OrderDetails Details { get; set; }
}
private class OrderDetails
{
public int Id { get; set; }
public int OrderId { get; set; }
public Order Order { 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.Diagnostics;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
public sealed partial class FileCodeModel
{
private const int ElementAddedDispId = 1;
private const int ElementChangedDispId = 2;
private const int ElementDeletedDispId = 3;
private const int ElementDeletedDispId2 = 4;
public bool FireEvents()
{
var needMoreTime = false;
_elementTable.Cleanup(out needMoreTime);
if (this.IsZombied)
{
// file is removed from the solution. this can happen if a fireevent is enqueued to foreground notification service
// but the file itself is removed from the solution before it has a chance to run
return needMoreTime;
}
Document document;
if (!TryGetDocument(out document))
{
// file is removed from the solution. this can happen if a fireevent is enqueued to foreground notification service
// but the file itself is removed from the solution before it has a chance to run
return needMoreTime;
}
// TODO(DustinCa): Enqueue unknown change event if a file is closed without being saved.
var oldTree = _lastSyntaxTree;
var newTree = document
.GetSyntaxTreeAsync(CancellationToken.None)
.WaitAndGetResult(CancellationToken.None);
_lastSyntaxTree = newTree;
if (oldTree == newTree ||
oldTree.IsEquivalentTo(newTree, topLevel: true))
{
return needMoreTime;
}
var eventQueue = this.CodeModelService.CollectCodeModelEvents(oldTree, newTree);
if (eventQueue.Count == 0)
{
return needMoreTime;
}
var provider = GetAbstractProject() as IProjectCodeModelProvider;
if (provider == null)
{
return needMoreTime;
}
ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> fileCodeModelHandle;
if (!provider.ProjectCodeModel.TryGetCachedFileCodeModel(this.Workspace.GetFilePath(GetDocumentId()), out fileCodeModelHandle))
{
return needMoreTime;
}
var extensibility = (EnvDTE80.IVsExtensibility2)this.State.ServiceProvider.GetService(typeof(EnvDTE.IVsExtensibility));
foreach (var codeModelEvent in eventQueue)
{
EnvDTE.CodeElement element;
object parentElement;
GetElementsForCodeModelEvent(codeModelEvent, out element, out parentElement);
if (codeModelEvent.Type == CodeModelEventType.Add)
{
extensibility.FireCodeModelEvent(ElementAddedDispId, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown);
}
else if (codeModelEvent.Type == CodeModelEventType.Remove)
{
extensibility.FireCodeModelEvent3(ElementDeletedDispId2, parentElement, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown);
extensibility.FireCodeModelEvent(ElementDeletedDispId, element, EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown);
}
else if (codeModelEvent.Type.IsChange())
{
extensibility.FireCodeModelEvent(ElementChangedDispId, element, ConvertToChangeKind(codeModelEvent.Type));
}
else
{
Debug.Fail("Invalid event type: " + codeModelEvent.Type);
}
}
return needMoreTime;
}
private EnvDTE80.vsCMChangeKind ConvertToChangeKind(CodeModelEventType eventType)
{
EnvDTE80.vsCMChangeKind result = 0;
if ((eventType & CodeModelEventType.Rename) != 0)
{
result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindRename;
}
if ((eventType & CodeModelEventType.Unknown) != 0)
{
result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindUnknown;
}
if ((eventType & CodeModelEventType.BaseChange) != 0)
{
result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindBaseChange;
}
if ((eventType & CodeModelEventType.TypeRefChange) != 0)
{
result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindTypeRefChange;
}
if ((eventType & CodeModelEventType.SigChange) != 0)
{
result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindSignatureChange;
}
if ((eventType & CodeModelEventType.ArgChange) != 0)
{
result |= EnvDTE80.vsCMChangeKind.vsCMChangeKindArgumentChange;
}
return result;
}
// internal for testing
internal void GetElementsForCodeModelEvent(CodeModelEvent codeModelEvent, out EnvDTE.CodeElement element, out object parentElement)
{
parentElement = GetParentElementForCodeModelEvent(codeModelEvent);
if (codeModelEvent.Node == null)
{
element = this.CodeModelService.CreateUnknownRootNamespaceCodeElement(this.State, this);
}
else if (this.CodeModelService.IsParameterNode(codeModelEvent.Node))
{
element = GetParameterElementForCodeModelEvent(codeModelEvent, parentElement);
}
else if (this.CodeModelService.IsAttributeNode(codeModelEvent.Node))
{
element = GetAttributeElementForCodeModelEvent(codeModelEvent, parentElement);
}
else if (this.CodeModelService.IsAttributeArgumentNode(codeModelEvent.Node))
{
element = GetAttributeArgumentElementForCodeModelEvent(codeModelEvent, parentElement);
}
else
{
if (codeModelEvent.Type == CodeModelEventType.Remove)
{
element = this.CodeModelService.CreateUnknownCodeElement(this.State, this, codeModelEvent.Node);
}
else
{
element = this.CreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.Node);
}
}
if (element == null)
{
Debug.Fail("We should have created an element for this event!");
}
Debug.Assert(codeModelEvent.Type != CodeModelEventType.Remove || parentElement != null);
}
private object GetParentElementForCodeModelEvent(CodeModelEvent codeModelEvent)
{
if (this.CodeModelService.IsParameterNode(codeModelEvent.Node) ||
this.CodeModelService.IsAttributeArgumentNode(codeModelEvent.Node))
{
if (codeModelEvent.ParentNode != null)
{
return this.CreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode);
}
}
else if (this.CodeModelService.IsAttributeNode(codeModelEvent.Node))
{
if (codeModelEvent.ParentNode != null)
{
return this.CreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode);
}
else
{
return this;
}
}
else if (codeModelEvent.Type == CodeModelEventType.Remove)
{
if (codeModelEvent.ParentNode != null &&
codeModelEvent.ParentNode.Parent != null)
{
return this.CreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode);
}
else
{
return this;
}
}
return null;
}
private EnvDTE.CodeElement GetParameterElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement)
{
var parentDelegate = parentElement as EnvDTE.CodeDelegate;
if (parentDelegate != null)
{
return GetParameterElementForCodeModelEvent(codeModelEvent, parentDelegate.Parameters, parentElement);
}
var parentFunction = parentElement as EnvDTE.CodeFunction;
if (parentFunction != null)
{
return GetParameterElementForCodeModelEvent(codeModelEvent, parentFunction.Parameters, parentElement);
}
var parentProperty = parentElement as EnvDTE80.CodeProperty2;
if (parentProperty != null)
{
return GetParameterElementForCodeModelEvent(codeModelEvent, parentProperty.Parameters, parentElement);
}
return null;
}
private EnvDTE.CodeElement GetParameterElementForCodeModelEvent(CodeModelEvent codeModelEvent, EnvDTE.CodeElements parentParameters, object parentElement)
{
if (parentParameters == null)
{
return null;
}
var parameterName = this.CodeModelService.GetName(codeModelEvent.Node);
if (codeModelEvent.Type == CodeModelEventType.Remove)
{
var parentCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeMember>(parentElement);
if (parentCodeElement != null)
{
return (EnvDTE.CodeElement)CodeParameter.Create(this.State, parentCodeElement, parameterName);
}
}
else
{
return parentParameters.Item(parameterName);
}
return null;
}
private EnvDTE.CodeElement GetAttributeElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement)
{
var node = codeModelEvent.Node;
var parentNode = codeModelEvent.ParentNode;
var eventType = codeModelEvent.Type;
var parentType = parentElement as EnvDTE.CodeType;
if (parentType != null)
{
return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentType.Attributes, parentElement);
}
var parentFunction = parentElement as EnvDTE.CodeFunction;
if (parentFunction != null)
{
return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentFunction.Attributes, parentElement);
}
var parentProperty = parentElement as EnvDTE.CodeProperty;
if (parentProperty != null)
{
return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentProperty.Attributes, parentElement);
}
var parentEvent = parentElement as EnvDTE80.CodeEvent;
if (parentEvent != null)
{
return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentEvent.Attributes, parentElement);
}
var parentVariable = parentElement as EnvDTE.CodeVariable;
if (parentVariable != null)
{
return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentVariable.Attributes, parentElement);
}
// In the following case, parentNode is null and the root should be used instead.
var parentFileCodeModel = parentElement as EnvDTE.FileCodeModel;
if (parentFileCodeModel != null)
{
var fileCodeModel = ComAggregate.TryGetManagedObject<FileCodeModel>(parentElement);
parentNode = fileCodeModel.GetSyntaxRoot();
return GetAttributeElementForCodeModelEvent(node, parentNode, eventType, parentFileCodeModel.CodeElements, parentElement);
}
return null;
}
private EnvDTE.CodeElement GetAttributeElementForCodeModelEvent(SyntaxNode node, SyntaxNode parentNode, CodeModelEventType eventType, EnvDTE.CodeElements elementsToSearch, object parentObject)
{
if (elementsToSearch == null)
{
return null;
}
string name;
int ordinal;
CodeModelService.GetAttributeNameAndOrdinal(parentNode, node, out name, out ordinal);
if (eventType == CodeModelEventType.Remove)
{
if (parentObject is EnvDTE.CodeElement)
{
var parentCodeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(parentObject);
if (parentCodeElement != null)
{
return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this, parentCodeElement, name, ordinal);
}
}
else if (parentObject is EnvDTE.FileCodeModel)
{
var parentFileCodeModel = ComAggregate.TryGetManagedObject<FileCodeModel>(parentObject);
if (parentFileCodeModel != null && parentFileCodeModel == this)
{
return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this, null, name, ordinal);
}
}
}
else
{
int testOridinal = 0;
foreach (EnvDTE.CodeElement element in elementsToSearch)
{
if (element.Kind != EnvDTE.vsCMElement.vsCMElementAttribute)
{
continue;
}
if (element.Name == name)
{
if (ordinal == testOridinal)
{
return element;
}
testOridinal++;
}
}
}
return null;
}
private EnvDTE.CodeElement GetAttributeArgumentElementForCodeModelEvent(CodeModelEvent codeModelEvent, object parentElement)
{
var parentAttribute = parentElement as EnvDTE80.CodeAttribute2;
if (parentAttribute != null)
{
return GetAttributeArgumentForCodeModelEvent(codeModelEvent, parentAttribute.Arguments, parentElement);
}
return null;
}
private EnvDTE.CodeElement GetAttributeArgumentForCodeModelEvent(CodeModelEvent codeModelEvent, EnvDTE.CodeElements parentAttributeArguments, object parentElement)
{
if (parentAttributeArguments == null)
{
return null;
}
SyntaxNode attributeNode;
int ordinal;
CodeModelService.GetAttributeArgumentParentAndIndex(codeModelEvent.Node, out attributeNode, out ordinal);
if (codeModelEvent.Type == CodeModelEventType.Remove)
{
var parentCodeElement = ComAggregate.TryGetManagedObject<CodeAttribute>(parentElement);
if (parentCodeElement != null)
{
return (EnvDTE.CodeElement)CodeAttributeArgument.Create(this.State, parentCodeElement, ordinal);
}
}
else
{
return parentAttributeArguments.Item(ordinal + 1); // Needs to be 1-based to call back into code model
}
return null;
}
}
}
| |
using NUnit.Framework;
using Shouldly;
using StructureMap.Configuration.DSL;
using StructureMap.Pipeline;
using StructureMap.Testing.Widget;
using StructureMap.Testing.Widget3;
namespace StructureMap.Testing.Graph
{
[TestFixture]
public class ContainerTester : Registry
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
_container = new Container(registry =>
{
registry.Scan(x => x.Assembly("StructureMap.Testing.Widget"));
registry.For<Rule>();
registry.For<IWidget>();
registry.For<WidgetMaker>();
});
}
#endregion
private IContainer _container;
private void addColorInstance(string Color)
{
_container.Configure(r =>
{
r.For<Rule>().Use<ColorRule>().Ctor<string>("color").Is(Color).Named(Color);
r.For<IWidget>().Use<ColorWidget>().Ctor<string>("color").Is(Color).Named(
Color);
r.For<WidgetMaker>().Use<ColorWidgetMaker>().Ctor<string>("color").Is(Color).
Named(Color);
});
}
public interface IProvider
{
}
public class Provider : IProvider
{
}
public class ClassThatUsesProvider
{
private readonly IProvider _provider;
public ClassThatUsesProvider(IProvider provider)
{
_provider = provider;
}
public IProvider Provider
{
get { return _provider; }
}
}
public class DifferentProvider : IProvider
{
}
private void assertColorIs(IContainer container, string color)
{
container.GetInstance<IService>().ShouldBeOfType<ColorService>().Color.ShouldBe(color);
}
[Test]
public void can_inject_into_a_running_container()
{
var container = new Container();
container.Inject(typeof (ISport), new ConstructorInstance(typeof (Football)));
container.GetInstance<ISport>()
.ShouldBeOfType<Football>();
}
[Test]
public void Can_set_profile_name_and_reset_defaults()
{
var container = new Container(r =>
{
r.For<IService>()
.Use<ColorService>().Named("Orange").Ctor<string>("color").Is(
"Orange");
r.For<IService>().AddInstances(x =>
{
x.Type<ColorService>().Named("Red").Ctor<string>("color").Is("Red");
x.Type<ColorService>().Named("Blue").Ctor<string>("color").Is("Blue");
x.Type<ColorService>().Named("Green").Ctor<string>("color").Is("Green");
});
r.Profile("Red", x => { x.For<IService>().Use("Red"); });
r.Profile("Blue", x => { x.For<IService>().Use("Blue"); });
});
assertColorIs(container, "Orange");
assertColorIs(container.GetProfile("Red"), "Red");
assertColorIs(container.GetProfile("Blue"), "Blue");
assertColorIs(container, "Orange");
}
[Test]
public void CanBuildConcreteTypesThatAreNotPreviouslyRegistered()
{
IContainer manager = new Container(
registry => registry.For<IProvider>().Use<Provider>());
// Now, have that same Container create a ClassThatUsesProvider. StructureMap will
// see that ClassThatUsesProvider is concrete, determine its constructor args, and build one
// for you with the default IProvider. No other configuration necessary.
var classThatUsesProvider = manager.GetInstance<ClassThatUsesProvider>();
classThatUsesProvider.Provider.ShouldBeOfType<Provider>();
}
[Test]
public void CanBuildConcreteTypesThatAreNotPreviouslyRegisteredWithArgumentsProvided()
{
IContainer manager =
new Container(
registry => registry.For<IProvider>().Use<Provider>());
var differentProvider = new DifferentProvider();
var args = new ExplicitArguments();
args.Set<IProvider>(differentProvider);
var classThatUsesProvider = manager.GetInstance<ClassThatUsesProvider>(args);
differentProvider.ShouldBeTheSameAs(classThatUsesProvider.Provider);
}
[Test]
public void can_get_the_default_instance()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
_container.Configure(x => x.For<Rule>().Use("Blue"));
_container.GetInstance<Rule>().ShouldBeOfType<ColorRule>().Color.ShouldBe("Blue");
}
[Test]
public void GetInstanceOf3Types()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
var rule = _container.GetInstance(typeof (Rule), "Blue") as ColorRule;
rule.ShouldNotBeNull();
rule.Color.ShouldBe("Blue");
var widget = _container.GetInstance(typeof (IWidget), "Red") as ColorWidget;
widget.ShouldNotBeNull();
widget.Color.ShouldBe("Red");
var maker = _container.GetInstance(typeof (WidgetMaker), "Orange") as ColorWidgetMaker;
maker.ShouldNotBeNull();
maker.Color.ShouldBe("Orange");
}
[Test]
public void GetMissingType()
{
var ex =
Exception<StructureMapConfigurationException>.ShouldBeThrownBy(
() => { _container.GetInstance(typeof (string)); });
ex.Title.ShouldContain("No default");
}
[Test]
public void InjectStub_by_name()
{
IContainer container = new Container();
var red = new ColorRule("Red");
var blue = new ColorRule("Blue");
container.Configure(x =>
{
x.For<Rule>().Add(red).Named("Red");
x.For<Rule>().Add(blue).Named("Blue");
});
red.ShouldBeTheSameAs(container.GetInstance<Rule>("Red"));
blue.ShouldBeTheSameAs(container.GetInstance<Rule>("Blue"));
}
[Test]
public void TryGetInstance_returns_instance_for_an_open_generic_that_it_can_close()
{
var container =
new Container(
x =>
x.For(typeof (IOpenGeneric<>)).Use(typeof (ConcreteOpenGeneric<>)));
container.TryGetInstance<IOpenGeneric<object>>().ShouldNotBeNull();
}
[Test]
public void TryGetInstance_returns_null_for_an_open_generic_that_it_cannot_close()
{
var container =
new Container(
x =>
x.For(typeof (IOpenGeneric<>)).Use(typeof (ConcreteOpenGeneric<>)));
container.TryGetInstance<IAnotherOpenGeneric<object>>().ShouldBeNull();
}
[Test]
public void TryGetInstance_ReturnsInstance_WhenTypeFound()
{
_container.Configure(c => c.For<IProvider>().Use<Provider>());
var instance = _container.TryGetInstance(typeof (IProvider));
instance.ShouldBeOfType(typeof (Provider));
}
[Test]
public void TryGetInstance_ReturnsNull_WhenTypeNotFound()
{
var instance = _container.TryGetInstance(typeof (IProvider));
instance.ShouldBeNull();
}
[Test]
public void TryGetInstanceViaGeneric_ReturnsInstance_WhenTypeFound()
{
_container.Configure(c => c.For<IProvider>().Use<Provider>());
var instance = _container.TryGetInstance<IProvider>();
instance.ShouldBeOfType(typeof (Provider));
}
[Test]
public void TryGetInstanceViaGeneric_ReturnsNull_WhenTypeNotFound()
{
var instance = _container.TryGetInstance<IProvider>();
instance.ShouldBeNull();
}
[Test]
public void TryGetInstanceViaName_ReturnsNull_WhenNotFound()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
var rule = _container.TryGetInstance(typeof (Rule), "Yellow");
rule.ShouldBeNull();
}
[Test]
public void TryGetInstanceViaName_ReturnsTheOutInstance_WhenFound()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
var rule = _container.TryGetInstance(typeof (Rule), "Orange");
rule.ShouldBeOfType(typeof (ColorRule));
}
[Test]
public void TryGetInstanceViaNameAndGeneric_ReturnsInstance_WhenTypeFound()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
// "Orange" exists, so an object should be returned
var instance = _container.TryGetInstance<Rule>("Orange");
instance.ShouldBeOfType(typeof (ColorRule));
}
[Test]
public void TryGetInstanceViaNameAndGeneric_ReturnsNull_WhenTypeNotFound()
{
addColorInstance("Red");
addColorInstance("Orange");
addColorInstance("Blue");
// "Yellow" does not exist, so return null
var instance = _container.TryGetInstance<Rule>("Yellow");
instance.ShouldBeNull();
}
}
public interface ISport
{
}
public class Football : ISport
{
}
public interface IOpenGeneric<T>
{
void Nop();
}
public interface IAnotherOpenGeneric<T>
{
}
public class ConcreteOpenGeneric<T> : IOpenGeneric<T>
{
public void Nop()
{
}
}
public class StringOpenGeneric : ConcreteOpenGeneric<string>
{
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Reflection.Emit;
using System.Configuration;
using System.Reflection;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using PHP.Core;
using PHP.Core.Reflection;
using System.Diagnostics;
namespace PHP.Core
{
/// <summary>
/// Command line compiler.
/// </summary>
public sealed class PhpNetCompiler
{
private TextWriter/*!*/ output;
private TextWriter/*!*/ errors;
private CommandLineParser/*!*/ commandLineParser = new CommandLineParser();
#region Helpers
/// <summary>
/// Writes Phalanger logo on output.
/// </summary>
private void ShowLogo()
{
Version php_net = Assembly.GetExecutingAssembly().GetName().Version;
Version runtime = Environment.Version;
output.WriteLine("Phalanger - the PHP Language Compiler - version {0}.{1}", php_net.Major, php_net.Minor);
output.WriteLine("for Microsoft (R) .NET Framework version {0}.{1}", runtime.Major, runtime.Minor);
}
/// <summary>
/// Displays a help.
/// </summary>
private void ShowHelp()
{
output.WriteLine("Usage:");
foreach (KeyValuePair<string, string> option in CommandLineParser.GetSupportedOptions())
{
output.WriteLine("{0}\n{1}\n", option.Key, option.Value);
}
output.WriteLine();
output.WriteLine(CoreResources.GetString("phpc_other_args"));
output.WriteLine();
}
private void DumpArguments(List<string>/*!*/ args)
{
if (commandLineParser.Verbose && args.Count > 0)
{
output.WriteLine(CoreResources.GetString("Arguments") + ":");
for (int i = 0; i < args.Count; i++) output.WriteLine(args[i]);
output.WriteLine();
}
}
private void DumpLoadedLibraries()
{
output.WriteLine(CoreResources.GetString("loaded_libraries") + ":");
foreach (DAssembly assembly in ApplicationContext.Default.GetLoadedAssemblies())
output.WriteLine(assembly.DisplayName);
output.WriteLine();
}
#endregion
#region Handling assembly load
/// <summary>
/// Name and file path to the specified assembly.
/// </summary>
private struct AssemblyInfo
{
public AssemblyName Name;
public string Path;
}
/// <summary>
/// Add AssemblyResolve handler that handles loading of assemblies in specified directory by their FullName.
/// </summary>
/// <param name="directoryName">The directory to load assemblies by their FullName from.</param>
private void HandleAssemblies(string directoryName)
{
if (!Directory.Exists(directoryName))
return;
var files = Directory.GetFiles(directoryName, "*.dll", SearchOption.TopDirectoryOnly);
var assembliesInDirectory = new List<AssemblyInfo>(files.Length);
foreach (string file in files)
{
try
{
assembliesInDirectory.Add(new AssemblyInfo()
{
Name = AssemblyName.GetAssemblyName(file),
Path = file
});
}
catch
{
}
}
//set domain AssemblyResolve to lookup assemblies found in directoryName
if (assembliesInDirectory.Count > 0)
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(
delegate(object o, ResolveEventArgs ea)
{
AssemblyName name = new AssemblyName(ea.Name);
foreach (var assembly in assembliesInDirectory)
{
if (AssemblyName.ReferenceMatchesDefinition(assembly.Name, name))
return Assembly.LoadFile(assembly.Path);
}
return null;
}
);
}
#endregion
#region Main
/// <summary>
/// Runs the compiler with specified options.
/// </summary>
/// <param name="args">Command line arguments.</param>
/// <returns>Whether the compilation was successful.</returns>
public bool Compile(List<string>/*!*/ args)
{
if (args == null)
throw new ArgumentNullException("args");
TextErrorSink errorSink = null;
// processes arguments:
try
{
try
{
commandLineParser.Parse(args);
}
finally
{
if (commandLineParser.Quiet)
{
output = errors = TextWriter.Null;
}
else if (commandLineParser.RedirectErrors)
{
output = errors = Console.Out;
}
else
{
output = Console.Out;
errors = Console.Error;
}
errorSink = new TextErrorSink(errors);
ShowLogo();
if (commandLineParser.ShowHelp)
{
ShowHelp();
}
else
{
DumpArguments(args);
}
}
}
catch (InvalidCommandLineArgumentException e)
{
e.Report(errorSink);
return false;
}
if (commandLineParser.ShowHelp)
return true;
// allow loading of all assemblies in /Bin directory by their FullName
HandleAssemblies(Path.Combine(commandLineParser.Parameters.SourceRoot, "Bin"));
//
ApplicationContext.DefineDefaultContext(false, true, false);
ApplicationContext app_context = ApplicationContext.Default;
CompilerConfiguration compiler_config;
// loads entire configuration:
try
{
if (commandLineParser.Parameters.ConfigPaths.Count == 0)
{
// Add config files for known targets
switch (commandLineParser.Parameters.Target)
{
case ApplicationCompiler.Targets.Web:
if (File.Exists("web.config"))
commandLineParser.Parameters.ConfigPaths.Add(new FullPath("web.config"));
break;
case ApplicationCompiler.Targets.WinApp:
if (File.Exists("app.config"))
commandLineParser.Parameters.ConfigPaths.Add(new FullPath("app.config"));
break;
}
}
compiler_config = ApplicationCompiler.LoadConfiguration(app_context,
commandLineParser.Parameters.ConfigPaths, output);
commandLineParser.Parameters.ApplyToConfiguration(compiler_config);
}
catch (ConfigurationErrorsException e)
{
if (commandLineParser.Verbose)
{
output.WriteLine(CoreResources.GetString("reading_configuration") + ":");
output.WriteLine();
if (!String.IsNullOrEmpty(e.Filename)) // Mono puts here null
{
output.WriteLine(FileSystemUtils.ReadFileLine(e.Filename, e.Line).Trim());
output.WriteLine();
}
}
errorSink.AddConfigurationError(e);
return false;
}
// load referenced assemblies:
try
{
try
{
app_context.AssemblyLoader.Load(commandLineParser.Parameters.References);
}
finally
{
if (commandLineParser.Verbose)
DumpLoadedLibraries();
}
}
catch (ConfigurationErrorsException e)
{
errorSink.AddConfigurationError(e);
return false;
}
output.WriteLine(CoreResources.GetString("performing_compilation") + " ...");
try
{
CommandLineParser p = commandLineParser;
Statistics.DrawGraph = p.DrawInclusionGraph;
errorSink.DisabledGroups = compiler_config.Compiler.DisabledWarnings;
errorSink.DisabledWarnings = compiler_config.Compiler.DisabledWarningNumbers;
errorSink.TreatWarningsAsErrors = compiler_config.Compiler.TreatWarningsAsErrors;
// initializes log:
DebugUtils.ConsoleInitialize(Path.GetDirectoryName(p.Parameters.OutPath));
new ApplicationCompiler().Compile(app_context, compiler_config, errorSink, p.Parameters);
}
catch (InvalidSourceException e)
{
e.Report(errorSink);
return false;
}
catch (Exception e)
{
errorSink.AddInternalError(e);
return false;
}
var errorscount = errorSink.ErrorCount + errorSink.FatalErrorCount;
var warningcount = errorSink.WarningCount + errorSink.WarningAsErrorCount;
output.WriteLine();
output.WriteLine("Build complete -- {0} error{1}, {2} warning{3}.",
errorscount, (errorscount == 1) ? "" : "s",
warningcount, (warningcount == 1) ? "" : "s");
return !errorSink.AnyError;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static int Main(string[] args)
{
return new PhpNetCompiler().Compile(new List<string>(args)) ? 0 : 1;
}
#endregion
}
}
| |
using System;
using System.Linq;
using Audit.Core;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using System.Text;
#if NETSTANDARD2_0 || NETSTANDARD2_1 || NET5_0
using Microsoft.Data.SqlClient;
#else
using System.Data.SqlClient;
using System.Data.Common;
#endif
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NETSTANDARD2_1 || NET5_0
using Microsoft.EntityFrameworkCore;
#endif
namespace Audit.SqlServer.Providers
{
/// <summary>
/// SQL Server data access
/// </summary>
/// <remarks>
/// Settings:
/// - ConnectionString: SQL connection string
/// - TableName: Table name (default is 'Event')
/// - JsonColumnName: Column name where the JSON will be stored (default is 'Data')
/// - IdColumnName: Column name with the primary key (default is 'EventId')
/// - LastUpdatedDateColumnName: datetime column to update when replacing events (NULL to ignore)
/// - Schema: The Schema Name to use
/// - CustomColumns: A collection of custom columns to be added when saving the audit event
/// </remarks>
public class SqlDataProvider : AuditDataProvider
{
#if NET45
/// <summary>
/// True to set the database initializer to NULL on the internal DbContext
/// </summary>
public bool SetDatabaseInitializerNull { get; set; }
/// <summary>
/// The DbConnection builder to use, alternative to ConnectionString when you need more control or configuration over the DB connection.
/// </summary>
public Func<AuditEvent, DbConnection> DbConnectionBuilder { get; set; }
#endif
/// <summary>
/// The SQL connection string builder
/// </summary>
public Func<AuditEvent, string> ConnectionStringBuilder { get; set; }
/// <summary>
/// The SQL connection string
/// </summary>
public string ConnectionString { set { ConnectionStringBuilder = _ => value; } }
/// <summary>
/// The SQL events Table Name builder
/// </summary>
public Func<AuditEvent, string> TableNameBuilder { get; set; } = ev => "Event";
/// <summary>
/// The SQL events Table Name
/// </summary>
public string TableName { set { TableNameBuilder = _ => value; } }
/// <summary>
/// The Column Name that stores the JSON
/// </summary>
public Func<AuditEvent, string> JsonColumnNameBuilder { get; set; }
/// <summary>
/// The Column Name that stores the JSON
/// </summary>
public string JsonColumnName { set { JsonColumnNameBuilder = _ => value; } }
/// <summary>
/// The Column Name that stores the Last Updated Date (NULL to ignore)
/// </summary>
public Func<AuditEvent, string> LastUpdatedDateColumnNameBuilder { get; set; } = null;
/// <summary>
/// The Column Name that stores the Last Updated Date (NULL to ignore)
/// </summary>
public string LastUpdatedDateColumnName { set { LastUpdatedDateColumnNameBuilder = _ => value; } }
/// <summary>
/// The Column Name that is the primary ley
/// </summary>
public Func<AuditEvent, string> IdColumnNameBuilder { get; set; } = ev => "EventId";
/// <summary>
/// The Column Name that is the primary ley
/// </summary>
public string IdColumnName { set { IdColumnNameBuilder = _ => value; } }
/// <summary>
/// The Schema Name to use (NULL to ignore)
/// </summary>
public Func<AuditEvent, string> SchemaBuilder { get; set; } = null;
/// <summary>
/// The Schema Name to use (NULL to ignore)
/// </summary>
public string Schema { set { SchemaBuilder = _ => value; } }
/// <summary>
/// A collection of custom columns to be added when saving the audit event
/// </summary>
public List<CustomColumn> CustomColumns { get; set; } = new List<CustomColumn>();
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NETSTANDARD2_1 || NET5_0
/// <summary>
/// The DbContext options builder, to provide custom database options for the DbContext
/// </summary>
[CLSCompliant(false)]
public Func<AuditEvent, DbContextOptions> DbContextOptionsBuilder { get; set; } = null;
#endif
public SqlDataProvider()
{
}
[CLSCompliant(false)]
public SqlDataProvider(Action<Configuration.ISqlServerProviderConfigurator> config)
{
var sqlConfig = new Configuration.SqlServerProviderConfigurator();
if (config != null)
{
config.Invoke(sqlConfig);
ConnectionStringBuilder = sqlConfig._connectionStringBuilder;
IdColumnNameBuilder = sqlConfig._idColumnNameBuilder;
JsonColumnNameBuilder = sqlConfig._jsonColumnNameBuilder;
LastUpdatedDateColumnNameBuilder = sqlConfig._lastUpdatedColumnNameBuilder;
SchemaBuilder = sqlConfig._schemaBuilder;
TableNameBuilder = sqlConfig._tableNameBuilder;
CustomColumns = sqlConfig._customColumns;
#if NET45
SetDatabaseInitializerNull = sqlConfig._setDatabaseInitializerNull;
DbConnectionBuilder = sqlConfig._dbConnectionBuilder;
#else
DbContextOptionsBuilder = sqlConfig._dbContextOptionsBuilder;
#endif
}
}
public override object InsertEvent(AuditEvent auditEvent)
{
var parameters = GetParametersForInsert(auditEvent);
using (var ctx = CreateContext(auditEvent))
{
var cmdText = GetInsertCommandText(auditEvent);
#if NET45
var result = ctx.Database.SqlQuery<string>(cmdText, parameters);
return result.ToList().FirstOrDefault();
#elif NETSTANDARD1_3
var result = ctx.FakeIdSet.FromSql(cmdText, parameters);
return result.ToList().FirstOrDefault()?.Id;
#elif NETSTANDARD2_0 || NETSTANDARD2_1 || NET5_0
var result = ctx.FakeIdSet.FromSqlRaw(cmdText, parameters);
return result.ToList().FirstOrDefault()?.Id;
#endif
}
}
public override async Task<object> InsertEventAsync(AuditEvent auditEvent)
{
var parameters = GetParametersForInsert(auditEvent);
using (var ctx = CreateContext(auditEvent))
{
var cmdText = GetInsertCommandText(auditEvent);
#if NET45
var result = ctx.Database.SqlQuery<string>(cmdText, parameters);
return (await result.ToListAsync()).FirstOrDefault();
#elif NETSTANDARD1_3
var result = ctx.FakeIdSet.FromSql(cmdText, parameters);
return (await result.ToListAsync()).FirstOrDefault()?.Id;
#elif NETSTANDARD2_0 || NETSTANDARD2_1 || NET5_0
var result = ctx.FakeIdSet.FromSqlRaw(cmdText, parameters);
return (await result.ToListAsync()).FirstOrDefault()?.Id;
#endif
}
}
public override void ReplaceEvent(object eventId, AuditEvent auditEvent)
{
var parameters = GetParametersForReplace(eventId, auditEvent);
using (var ctx = CreateContext(auditEvent))
{
var cmdText = GetReplaceCommandText(auditEvent);
#if NETSTANDARD2_0 || NETSTANDARD2_1 || NET5_0
ctx.Database.ExecuteSqlRaw(cmdText, parameters);
#else
ctx.Database.ExecuteSqlCommand(cmdText, parameters);
#endif
}
}
public override async Task ReplaceEventAsync(object eventId, AuditEvent auditEvent)
{
var parameters = GetParametersForReplace(eventId, auditEvent);
using (var ctx = CreateContext(auditEvent))
{
var cmdText = GetReplaceCommandText(auditEvent);
#if NETSTANDARD1_3
await ctx.Database.ExecuteSqlCommandAsync(cmdText, default(CancellationToken), parameters);
#elif NETSTANDARD2_0 || NETSTANDARD2_1 || NET5_0
await ctx.Database.ExecuteSqlRawAsync(cmdText, parameters);
#else
await ctx.Database.ExecuteSqlCommandAsync(cmdText, parameters);
#endif
}
}
public override T GetEvent<T>(object eventId)
{
if (JsonColumnNameBuilder == null)
{
return null;
}
using (var ctx = CreateContext(null))
{
var cmdText = GetSelectCommandText(null);
#if NET45
var result = ctx.Database.SqlQuery<string>(cmdText, new SqlParameter("@eventId", eventId));
var json = result.FirstOrDefault();
#elif NETSTANDARD1_3
var result = ctx.FakeIdSet.FromSql(cmdText, new SqlParameter("@eventId", eventId));
var json = result.FirstOrDefault()?.Id;
#elif NETSTANDARD2_0 || NETSTANDARD2_1 || NET5_0
var result = ctx.FakeIdSet.FromSqlRaw(cmdText, new SqlParameter("@eventId", eventId));
var json = result.FirstOrDefault()?.Id;
#endif
if (json != null)
{
return AuditEvent.FromJson<T>(json);
}
}
return null;
}
public override async Task<T> GetEventAsync<T>(object eventId)
{
if (JsonColumnNameBuilder == null)
{
return null;
}
using (var ctx = CreateContext(null))
{
var cmdText = GetSelectCommandText(null);
#if NET45
var result = ctx.Database.SqlQuery<string>(cmdText, new SqlParameter("@eventId", eventId));
var json = await result.FirstOrDefaultAsync();
#elif NETSTANDARD1_3
var result = ctx.FakeIdSet.FromSql(cmdText, new SqlParameter("@eventId", eventId));
var json = (await result.FirstOrDefaultAsync())?.Id;
#elif NETSTANDARD2_0 || NETSTANDARD2_1 || NET5_0
var result = ctx.FakeIdSet.FromSqlRaw(cmdText, new SqlParameter("@eventId", eventId));
var json = (await result.FirstOrDefaultAsync())?.Id;
#endif
if (json != null)
{
return AuditEvent.FromJson<T>(json);
}
}
return null;
}
private string GetFullTableName(AuditEvent auditEvent)
{
return SchemaBuilder != null
? string.Format("[{0}].[{1}]", SchemaBuilder.Invoke(auditEvent), TableNameBuilder.Invoke(auditEvent))
: string.Format("[{0}]", TableNameBuilder.Invoke(auditEvent));
}
private string GetInsertCommandText(AuditEvent auditEvent)
{
return string.Format("INSERT INTO {0} ({1}) OUTPUT CONVERT(NVARCHAR(MAX), INSERTED.[{2}]) AS [Id] VALUES ({3})",
GetFullTableName(auditEvent),
GetColumnsForInsert(auditEvent),
IdColumnNameBuilder.Invoke(auditEvent),
GetValuesForInsert(auditEvent));
}
private string GetColumnsForInsert(AuditEvent auditEvent)
{
var columns = new List<string>();
var jsonColumnName = JsonColumnNameBuilder?.Invoke(auditEvent);
if (jsonColumnName != null)
{
columns.Add(jsonColumnName);
}
if (CustomColumns != null)
{
foreach (var column in CustomColumns)
{
columns.Add(column.Name);
}
}
return string.Join(", ", columns.Select(c => $"[{c}]"));
}
private string GetValuesForInsert(AuditEvent auditEvent)
{
var values = new List<string>();
if (JsonColumnNameBuilder != null)
{
values.Add("@json");
}
if (CustomColumns != null)
{
for (int i = 0; i < CustomColumns.Count; i++)
{
values.Add($"@c{i}");
}
}
return string.Join(", ", values);
}
private SqlParameter[] GetParametersForInsert(AuditEvent auditEvent)
{
var parameters = new List<SqlParameter>();
if (JsonColumnNameBuilder != null)
{
parameters.Add(new SqlParameter("@json", auditEvent.ToJson()));
}
if (CustomColumns != null)
{
for (int i = 0; i < CustomColumns.Count; i++)
{
parameters.Add(new SqlParameter($"@c{i}", CustomColumns[i].Value.Invoke(auditEvent) ?? DBNull.Value));
}
}
return parameters.ToArray();
}
private SqlParameter[] GetParametersForReplace(object eventId, AuditEvent auditEvent)
{
var parameters = new List<SqlParameter>();
if (JsonColumnNameBuilder != null)
{
parameters.Add(new SqlParameter("@json", auditEvent.ToJson()));
}
parameters.Add(new SqlParameter("@eventId", eventId));
if (CustomColumns != null)
{
for (int i = 0; i < CustomColumns.Count; i++)
{
parameters.Add(new SqlParameter($"@c{i}", CustomColumns[i].Value.Invoke(auditEvent) ?? DBNull.Value));
}
}
return parameters.ToArray();
}
private string GetReplaceCommandText(AuditEvent auditEvent)
{
var cmdText = string.Format("UPDATE {0} SET {1} WHERE [{2}] = @eventId",
GetFullTableName(auditEvent),
GetSetForUpdate(auditEvent),
IdColumnNameBuilder.Invoke(auditEvent));
return cmdText;
}
private string GetSetForUpdate(AuditEvent auditEvent)
{
var jsonColumnName = JsonColumnNameBuilder?.Invoke(auditEvent);
var ludColumn = LastUpdatedDateColumnNameBuilder?.Invoke(auditEvent);
var sets = new List<string>();
if (jsonColumnName != null)
{
sets.Add($"[{jsonColumnName}] = @json");
}
if (ludColumn != null)
{
sets.Add($"[{ludColumn}] = GETUTCDATE()");
}
if (CustomColumns != null && CustomColumns.Any())
{
for(int i = 0; i < CustomColumns.Count; i++)
{
sets.Add($"[{CustomColumns[i].Name}] = @c{i}");
}
}
return string.Join(", ", sets);
}
private string GetSelectCommandText(AuditEvent auditEvent)
{
var cmdText = string.Format("SELECT [{0}] As [Id] FROM {1} WHERE [{2}] = @eventId",
JsonColumnNameBuilder.Invoke(auditEvent),
GetFullTableName(auditEvent),
IdColumnNameBuilder.Invoke(auditEvent));
return cmdText;
}
private AuditContext CreateContext(AuditEvent auditEvent)
{
#if NET45
if (DbConnectionBuilder != null)
{
return new AuditContext(DbConnectionBuilder.Invoke(auditEvent), SetDatabaseInitializerNull, true);
}
else
{
return new AuditContext(ConnectionStringBuilder?.Invoke(auditEvent), SetDatabaseInitializerNull);
}
#else
if (DbContextOptionsBuilder != null)
{
return new AuditContext(ConnectionStringBuilder?.Invoke(auditEvent), DbContextOptionsBuilder.Invoke(auditEvent));
}
else
{
return new AuditContext(ConnectionStringBuilder?.Invoke(auditEvent));
}
#endif
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Int32Rect.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.WindowsBase;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Windows.Markup;
using System.Windows.Converters;
using System.Windows;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows
{
[Serializable]
[TypeConverter(typeof(Int32RectConverter))]
[ValueSerializer(typeof(Int32RectValueSerializer))] // Used by MarkupWriter
partial struct Int32Rect : IFormattable
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Compares two Int32Rect instances for exact equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which are logically equal may fail.
/// Furthermore, using this equality operator, Double.NaN is not equal to itself.
/// </summary>
/// <returns>
/// bool - true if the two Int32Rect instances are exactly equal, false otherwise
/// </returns>
/// <param name='int32Rect1'>The first Int32Rect to compare</param>
/// <param name='int32Rect2'>The second Int32Rect to compare</param>
public static bool operator == (Int32Rect int32Rect1, Int32Rect int32Rect2)
{
return int32Rect1.X == int32Rect2.X &&
int32Rect1.Y == int32Rect2.Y &&
int32Rect1.Width == int32Rect2.Width &&
int32Rect1.Height == int32Rect2.Height;
}
/// <summary>
/// Compares two Int32Rect instances for exact inequality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which are logically equal may fail.
/// Furthermore, using this equality operator, Double.NaN is not equal to itself.
/// </summary>
/// <returns>
/// bool - true if the two Int32Rect instances are exactly unequal, false otherwise
/// </returns>
/// <param name='int32Rect1'>The first Int32Rect to compare</param>
/// <param name='int32Rect2'>The second Int32Rect to compare</param>
public static bool operator != (Int32Rect int32Rect1, Int32Rect int32Rect2)
{
return !(int32Rect1 == int32Rect2);
}
/// <summary>
/// Compares two Int32Rect instances for object equality. In this equality
/// Double.NaN is equal to itself, unlike in numeric equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which
/// are logically equal may fail.
/// </summary>
/// <returns>
/// bool - true if the two Int32Rect instances are exactly equal, false otherwise
/// </returns>
/// <param name='int32Rect1'>The first Int32Rect to compare</param>
/// <param name='int32Rect2'>The second Int32Rect to compare</param>
public static bool Equals (Int32Rect int32Rect1, Int32Rect int32Rect2)
{
if (int32Rect1.IsEmpty)
{
return int32Rect2.IsEmpty;
}
else
{
return int32Rect1.X.Equals(int32Rect2.X) &&
int32Rect1.Y.Equals(int32Rect2.Y) &&
int32Rect1.Width.Equals(int32Rect2.Width) &&
int32Rect1.Height.Equals(int32Rect2.Height);
}
}
/// <summary>
/// Equals - compares this Int32Rect with the passed in object. In this equality
/// Double.NaN is equal to itself, unlike in numeric equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which
/// are logically equal may fail.
/// </summary>
/// <returns>
/// bool - true if the object is an instance of Int32Rect and if it's equal to "this".
/// </returns>
/// <param name='o'>The object to compare to "this"</param>
public override bool Equals(object o)
{
if ((null == o) || !(o is Int32Rect))
{
return false;
}
Int32Rect value = (Int32Rect)o;
return Int32Rect.Equals(this,value);
}
/// <summary>
/// Equals - compares this Int32Rect with the passed in object. In this equality
/// Double.NaN is equal to itself, unlike in numeric equality.
/// Note that double values can acquire error when operated upon, such that
/// an exact comparison between two values which
/// are logically equal may fail.
/// </summary>
/// <returns>
/// bool - true if "value" is equal to "this".
/// </returns>
/// <param name='value'>The Int32Rect to compare to "this"</param>
public bool Equals(Int32Rect value)
{
return Int32Rect.Equals(this, value);
}
/// <summary>
/// Returns the HashCode for this Int32Rect
/// </summary>
/// <returns>
/// int - the HashCode for this Int32Rect
/// </returns>
public override int GetHashCode()
{
if (IsEmpty)
{
return 0;
}
else
{
// Perform field-by-field XOR of HashCodes
return X.GetHashCode() ^
Y.GetHashCode() ^
Width.GetHashCode() ^
Height.GetHashCode();
}
}
/// <summary>
/// Parse - returns an instance converted from the provided string using
/// the culture "en-US"
/// <param name="source"> string with Int32Rect data </param>
/// </summary>
public static Int32Rect Parse(string source)
{
IFormatProvider formatProvider = System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS;
TokenizerHelper th = new TokenizerHelper(source, formatProvider);
Int32Rect value;
String firstToken = th.NextTokenRequired();
// The token will already have had whitespace trimmed so we can do a
// simple string compare.
if (firstToken == "Empty")
{
value = Empty;
}
else
{
value = new Int32Rect(
Convert.ToInt32(firstToken, formatProvider),
Convert.ToInt32(th.NextTokenRequired(), formatProvider),
Convert.ToInt32(th.NextTokenRequired(), formatProvider),
Convert.ToInt32(th.NextTokenRequired(), formatProvider));
}
// There should be no more tokens in this string.
th.LastTokenRequired();
return value;
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// X - int. Default value is 0.
/// </summary>
public int X
{
get
{
return _x;
}
set
{
_x = value;
}
}
/// <summary>
/// Y - int. Default value is 0.
/// </summary>
public int Y
{
get
{
return _y;
}
set
{
_y = value;
}
}
/// <summary>
/// Width - int. Default value is 0.
/// </summary>
public int Width
{
get
{
return _width;
}
set
{
_width = value;
}
}
/// <summary>
/// Height - int. Default value is 0.
/// </summary>
public int Height
{
get
{
return _height;
}
set
{
_height = value;
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// Creates a string representation of this object based on the current culture.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
public override string ToString()
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, null /* format provider */);
}
/// <summary>
/// Creates a string representation of this object based on the IFormatProvider
/// passed in. If the provider is null, the CurrentCulture is used.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
public string ToString(IFormatProvider provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, provider);
}
/// <summary>
/// Creates a string representation of this object based on the format string
/// and IFormatProvider passed in.
/// If the provider is null, the CurrentCulture is used.
/// See the documentation for IFormattable for more information.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
string IFormattable.ToString(string format, IFormatProvider provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(format, provider);
}
/// <summary>
/// Creates a string representation of this object based on the format string
/// and IFormatProvider passed in.
/// If the provider is null, the CurrentCulture is used.
/// See the documentation for IFormattable for more information.
/// </summary>
/// <returns>
/// A string representation of this object.
/// </returns>
internal string ConvertToString(string format, IFormatProvider provider)
{
if (IsEmpty)
{
return "Empty";
}
// Helper to get the numeric list separator for a given culture.
char separator = MS.Internal.TokenizerHelper.GetNumericListSeparator(provider);
return String.Format(provider,
"{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}",
separator,
_x,
_y,
_width,
_height);
}
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal int _x;
internal int _y;
internal int _width;
internal int _height;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#endregion Constructors
}
}
| |
// Copyright (c) 2017 Trevor Redfern
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
namespace SilverNeedle.Serialization
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using YamlDotNet.RepresentationModel;
using SilverNeedle.Utility;
/// <summary>
/// A wrapper around the YamlNodes that abstracts away complexities of the Yaml format
/// </summary>
public class YamlObjectStore : IObjectStore
{
/// <summary>
/// Has a value if node is a sequence node
/// </summary>
private YamlSequenceNode sequenceNode;
/// <summary>
/// Has a value if the mode maps to other nodes
/// </summary>
private YamlMappingNode mappingNode;
/// <summary>
/// Gets the node for the YAML
/// </summary>
/// <value>The node.</value>
private YamlNode node;
/// <summary>
/// Initializes a new instance of the <see cref="SilverNeedle.YamlNodeWrapper"/> class.
/// </summary>
/// <param name="wrap">YamlNode to wrap.</param>
public YamlObjectStore(YamlNode wrap)
{
this.node = wrap;
this.sequenceNode = this.node as YamlSequenceNode;
this.mappingNode = this.node as YamlMappingNode;
}
public YamlObjectStore()
{
this.mappingNode = new YamlMappingNode();
this.node = this.mappingNode;
}
/// <summary>
/// Determines whether this instance has children.
/// </summary>
/// <returns><c>true</c> if this instance has children; otherwise, <c>false</c>.</returns>
public bool HasChildren
{
get
{
return Children.Count() > 0;
}
}
/// <summary>
/// Children found in this instance of YAML
/// </summary>
/// <returns>Returns the children of this node if there are any</returns>
public IEnumerable<IObjectStore> Children
{
get
{
if(this.sequenceNode == null)
return new List<IObjectStore>();
return this.sequenceNode.Children.Select(x => new YamlObjectStore(x)).ToList();
}
}
public bool HasKey(string node)
{
return Keys.Any(x => x == node);
}
/// <summary>
/// Gets a string value from the node based on the key.
/// Note: Throws exception if key is not found
/// </summary>
/// <returns>The string value of the key</returns>
/// <param name="key">Key to lookup</param>
public string GetString(string key)
{
var item = this.GetScalarNode(key);
return item.Value;
}
private YamlScalarNode GetScalarNode(string key)
{
var item = GetScalarNodeOptional(key);
if(item == null)
throw new KeyNotFoundException(key);
return item;
}
/// <summary>
/// Gets the string based on a key optionally.
/// </summary>
/// <returns>The string of the key or null if key is not found</returns>
/// <param name="key">Key to lookup in node</param>
public string GetStringOptional(string key, string defaultValue = null)
{
var item = this.GetScalarNodeOptional(key);
if (item != null)
{
return item.Value;
}
return defaultValue;
}
private YamlScalarNode GetScalarNodeOptional(string key)
{
var keyNode = new YamlScalarNode(key);
if(mappingNode.Children.ContainsKey(keyNode))
{
return mappingNode.Children[keyNode] as YamlScalarNode;
}
return null;
}
/// <summary>
/// Translates a key that contains commma separated values into a string array
/// </summary>
/// <returns>The string array split and trimmed around commas.
/// Returns an empty array if key is not found </returns>
/// <param name="key">Key to the comma delimited string</param>
public string[] GetListOptional(string key)
{
if(this.HasKey(key))
return GetList(key);
return new string[] { };
}
public string[] GetList(string key)
{
var sequence = mappingNode.Children[new YamlScalarNode(key)] as YamlSequenceNode;
return sequence.Children.OfType<YamlScalarNode>().Select(x => x.Value).ToArray();
}
public IEnumerable<IObjectStore> GetObjectList(string key)
{
var sequence = mappingNode.Children[new YamlScalarNode(key)] as YamlSequenceNode;
return sequence.Children.Select(x => new YamlObjectStore(x));
}
public IEnumerable<IObjectStore> GetObjectListOptional(string key)
{
if(HasKey(key))
return GetObjectList(key);
return new List<IObjectStore>();
}
public bool GetBool(string key)
{
return Boolean.Parse(this.GetString(key));
}
/// <summary>
/// Gets a boolean value from the YAML document.
/// Boolean must match "yes" to be true
/// </summary>
/// <returns><c>true</c>, if bool optional was gotten, <c>false</c> otherwise.</returns>
/// <param name="key">Key to lookup in YAML node</param>
public bool GetBoolOptional(string key, bool defaultValue = false)
{
if(HasKey(key))
return GetBool(key);
return defaultValue;
}
/// <summary>
/// Gets the integer optional.
/// </summary>
/// <returns>The integer value found, 0 otherwise.</returns>
/// <param name="key">Key to lookup in YAML node</param>
public int GetIntegerOptional(string key, int defaultValue = 0)
{
var v = this.GetStringOptional(key);
if (v == null)
{
return defaultValue;
}
return int.Parse(v);
}
/// <summary>
/// Gets an integer from the YAML document. Throws exception if not found
/// </summary>
/// <returns>The integer value</returns>
/// <param name="key">Key to lookup in YAML node</param>
public int GetInteger(string key)
{
return int.Parse(this.GetString(key));
}
/// <summary>
/// Gets a float from the YAML document. Throws exception if not found
/// </summary>
/// <returns>The float value from the key</returns>
/// <param name="key">Key to lookup in YAML node</param>
public float GetFloat(string key)
{
return float.Parse(this.GetString(key));
}
public float GetFloatOptional(string key, float defaultValue = 0)
{
var v = GetStringOptional(key);
if (v == null)
{
return defaultValue;
}
return float.Parse(v);
}
/// <summary>
/// Gets an enum value from the YAML node. Throws exception if not found
/// Ignores Case
/// </summary>
/// <returns>The enum value parsed out</returns>
/// <param name="key">Key to lookup in YAML node</param>
/// <typeparam name="T">The enum type to parse</typeparam>
public T GetEnum<T>(string key)
{
return (T)Enum.Parse(typeof(T), this.GetStringOptional(key), true);
}
public IEnumerable<string> Keys
{
get
{
return this.mappingNode.Children.Select(x => x.Key.ToString());
}
}
/// <summary>
/// Gets a wrapper node based on key for traversing trees. Throws exception if not found
/// </summary>
/// <returns>The node from the key</returns>
/// <param name="key">Key to lookup in YAML node</param>
public IObjectStore GetObject(string key)
{
try
{
var item = this.mappingNode.Children[new YamlScalarNode(key)];
return new YamlObjectStore(item);
}
catch(Exception ex)
{
throw new ObjectStoreKeyNotFoundException(this, key, ex);
}
}
/// <summary>
/// Gets the node optional.
/// </summary>
/// <returns>The node optional.</returns>
/// <param name="key">Key to lookup in YAML node</param>
public IObjectStore GetObjectOptional(string key)
{
if (!HasKey(key))
return null;
var item = this.mappingNode.Children[new YamlScalarNode(key)];
return new YamlObjectStore(item);
}
public string GetTag()
{
return this.node.Tag;
}
public IList<T> Load<T>()
{
var type = typeof(T);
var list = new List<T>();
foreach(var obj in Children)
{
list.Add(type.Instantiate<T>(obj));
}
return list;
}
public void SetValue(string key, string val)
{
this.mappingNode.Children[new YamlScalarNode(key)] = new YamlScalarNode(val);
}
public void SetValue(string key, int val)
{
this.SetValue(key, val.ToString());
}
public void SetValue(string key, YamlObjectStore val)
{
this.mappingNode.Children[new YamlScalarNode(key)] = val.MappingNode;
}
public void SetValue(string key, IEnumerable<string> vals)
{
var sequenceNode = new YamlSequenceNode();
var nodes = vals.Select(x => new YamlScalarNode(x));
sequenceNode.Children.Add(nodes);
this.mappingNode.Children[new YamlScalarNode(key)] = sequenceNode;
}
public void SetValue(string key, IEnumerable<YamlObjectStore> vals)
{
var sequenceNode = new YamlSequenceNode();
var nodes = vals.Select(x => x.MappingNode);
sequenceNode.Children.Add(nodes);
this.mappingNode.Children[new YamlScalarNode(key)] = sequenceNode;
}
public void SetValue(string key, bool v)
{
SetValue(key, v.ToString());
}
public void SetValue(string key, float v)
{
SetValue(key, v.ToString());
}
public YamlMappingNode MappingNode { get { return this.mappingNode; } }
}
}
| |
// 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.Xml; //Required for Content Type File manipulation
using System.Diagnostics;
using System.IO.Compression;
namespace System.IO.Packaging
{
/// <summary>
/// ZipPackage is a specific implementation for the abstract Package
/// class, corresponding to the Zip file format.
/// This is a part of the Packaging Layer APIs.
/// </summary>
public sealed class ZipPackage : Package
{
#region Public Methods
#region PackagePart Methods
/// <summary>
/// This method is for custom implementation for the underlying file format
/// Adds a new item to the zip archive corresponding to the PackagePart in the package.
/// </summary>
/// <param name="partUri">PartName</param>
/// <param name="contentType">Content type of the part</param>
/// <param name="compressionOption">Compression option for this part</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">If partUri parameter is null</exception>
/// <exception cref="ArgumentNullException">If contentType parameter is null</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
/// <exception cref="ArgumentOutOfRangeException">If CompressionOption enumeration [compressionOption] does not have one of the valid values</exception>
protected override PackagePart CreatePartCore(Uri partUri,
string contentType,
CompressionOption compressionOption)
{
//Validating the PartUri - this method will do the argument checking required for uri.
partUri = PackUriHelper.ValidatePartUri(partUri);
if (contentType == null)
throw new ArgumentNullException(nameof(contentType));
Package.ThrowIfCompressionOptionInvalid(compressionOption);
// Convert Metro CompressionOption to Zip CompressionMethodEnum.
CompressionLevel level;
GetZipCompressionMethodFromOpcCompressionOption(compressionOption,
out level);
// Create new Zip item.
// We need to remove the leading "/" character at the beginning of the part name.
// The partUri object must be a ValidatedPartUri
string zipItemName = ((PackUriHelper.ValidatedPartUri)partUri).PartUriString.Substring(1);
ZipArchiveEntry zipArchiveEntry = _zipArchive.CreateEntry(zipItemName, level);
//Store the content type of this part in the content types stream.
_contentTypeHelper.AddContentType((PackUriHelper.ValidatedPartUri)partUri, new ContentType(contentType), level);
return new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry, _zipStreamManager, (PackUriHelper.ValidatedPartUri)partUri, contentType, compressionOption);
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// Returns the part after reading the actual physical bits. The method
/// returns a null to indicate that the part corresponding to the specified
/// Uri was not found in the container.
/// This method does not throw an exception if a part does not exist.
/// </summary>
/// <param name="partUri"></param>
/// <returns></returns>
protected override PackagePart GetPartCore(Uri partUri)
{
//Currently the design has two aspects which makes it possible to return
//a null from this method -
// 1. All the parts are loaded at Package.Open time and as such, this
// method would not be invoked, unless the user is asking for -
// i. a part that does not exist - we can safely return null
// ii.a part(interleaved/non-interleaved) that was added to the
// underlying package by some other means, and the user wants to
// access the updated part. This is currently not possible as the
// underlying zip i/o layer does not allow for FileShare.ReadWrite.
// 2. Also, its not a straightforward task to determine if a new part was
// added as we need to look for atomic as well as interleaved parts and
// this has to be done in a case sensitive manner. So, effectively
// we will have to go through the entire list of zip items to determine
// if there are any updates.
// If ever the design changes, then this method must be updated accordingly
return null;
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// Deletes the part corresponding to the uri specified. Deleting a part that does not
/// exists is not an error and so we do not throw an exception in that case.
/// </summary>
/// <param name="partUri"></param>
/// <exception cref="ArgumentNullException">If partUri parameter is null</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
protected override void DeletePartCore(Uri partUri)
{
//Validating the PartUri - this method will do the argument checking required for uri.
partUri = PackUriHelper.ValidatePartUri(partUri);
string partZipName = GetZipItemNameFromOpcName(PackUriHelper.GetStringForPartUri(partUri));
ZipArchiveEntry zipArchiveEntry = _zipArchive.GetEntry(partZipName);
if (zipArchiveEntry != null)
{
// Case of an atomic part.
zipArchiveEntry.Delete();
}
//Delete the content type for this part if it was specified as an override
_contentTypeHelper.DeleteContentType((PackUriHelper.ValidatedPartUri)partUri);
}
/// <summary>
/// This method is for custom implementation specific to the file format.
/// This is the method that knows how to get the actual parts from the underlying
/// zip archive.
/// </summary>
/// <remarks>
/// <para>
/// Some or all of the parts may be interleaved. The Part object for an interleaved part encapsulates
/// the Uri of the proper part name and the ZipFileInfo of the initial piece.
/// This function does not go through the extra work of checking piece naming validity
/// throughout the package.
/// </para>
/// <para>
/// This means that interleaved parts without an initial piece will be silently ignored.
/// Other naming anomalies get caught at the Stream level when an I/O operation involves
/// an anomalous or missing piece.
/// </para>
/// <para>
/// This function reads directly from the underlying IO layer and is supposed to be called
/// just once in the lifetime of a package (at init time).
/// </para>
/// </remarks>
/// <returns>An array of ZipPackagePart.</returns>
protected override PackagePart[] GetPartsCore()
{
List<PackagePart> parts = new List<PackagePart>(InitialPartListSize);
// The list of files has to be searched linearly (1) to identify the content type
// stream, and (2) to identify parts.
System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipArchiveEntries = _zipArchive.Entries;
// We have already identified the [ContentTypes].xml pieces if any are present during
// the initialization of ZipPackage object
// Record parts and ignored items.
foreach (ZipArchiveEntry zipArchiveEntry in zipArchiveEntries)
{
//Returns false if -
// a. its a content type item
// b. items that have either a leading or trailing slash.
if (IsZipItemValidOpcPartOrPiece(zipArchiveEntry.FullName))
{
Uri partUri = new Uri(GetOpcNameFromZipItemName(zipArchiveEntry.FullName), UriKind.Relative);
PackUriHelper.ValidatedPartUri validatedPartUri;
if (PackUriHelper.TryValidatePartUri(partUri, out validatedPartUri))
{
ContentType contentType = _contentTypeHelper.GetContentType(validatedPartUri);
if (contentType != null)
{
// In case there was some redundancy between pieces and/or the atomic
// part, it will be detected at this point because the part's Uri (which
// is independent of interleaving) will already be in the dictionary.
parts.Add(new ZipPackagePart(this, zipArchiveEntry.Archive, zipArchiveEntry,
_zipStreamManager, validatedPartUri, contentType.ToString(), GetCompressionOptionFromZipFileInfo(zipArchiveEntry)));
}
}
//If not valid part uri we can completely ignore this zip file item. Even if later someone adds
//a new part, the corresponding zip item can never map to one of these items
}
// If IsZipItemValidOpcPartOrPiece returns false, it implies that either the zip file Item
// starts or ends with a "/" and as such we can completely ignore this zip file item. Even if later
// a new part gets added, its corresponding zip item cannot map to one of these items.
}
return parts.ToArray();
}
#endregion PackagePart Methods
#region Other Methods
/// <summary>
/// This method is for custom implementation corresponding to the underlying zip file format.
/// </summary>
protected override void FlushCore()
{
//Save the content type file to the archive.
_contentTypeHelper.SaveToFile();
}
/// <summary>
/// Closes the underlying ZipArchive object for this container
/// </summary>
/// <param name="disposing">True if called during Dispose, false if called during Finalize</param>
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_contentTypeHelper != null)
{
_contentTypeHelper.SaveToFile();
}
if (_zipStreamManager != null)
{
_zipStreamManager.Dispose();
}
if (_zipArchive != null)
{
_zipArchive.Dispose();
}
// _containerStream may be opened given a file name, in which case it should be closed here.
// _containerStream may be passed into the constructor, in which case, it should not be closed here.
if (_shouldCloseContainerStream)
{
_containerStream.Dispose();
}
else
{
}
_containerStream = null;
}
}
finally
{
base.Dispose(disposing);
}
}
#endregion Other Methods
#endregion Public Methods
#region Internal Constructors
/// <summary>
/// Internal constructor that is called by the OpenOnFile static method.
/// </summary>
/// <param name="path">File path to the container.</param>
/// <param name="packageFileMode">Container is opened in the specified mode if possible</param>
/// <param name="packageFileAccess">Container is opened with the specified access if possible</param>
/// <param name="share">Container is opened with the specified share if possible</param>
internal ZipPackage(string path, FileMode packageFileMode, FileAccess packageFileAccess, FileShare share)
: base(packageFileAccess)
{
ZipArchive zipArchive = null;
ContentTypeHelper contentTypeHelper = null;
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
try
{
_containerStream = new FileStream(path, _packageFileMode, _packageFileAccess, share);
_shouldCloseContainerStream = true;
ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
if (packageFileAccess == FileAccess.Read)
zipArchiveMode = ZipArchiveMode.Read;
else if (packageFileAccess == FileAccess.Write)
zipArchiveMode = ZipArchiveMode.Create;
else if (packageFileAccess == FileAccess.ReadWrite)
zipArchiveMode = ZipArchiveMode.Update;
zipArchive = new ZipArchive(_containerStream, zipArchiveMode, true, Text.Encoding.UTF8);
_zipStreamManager = new ZipStreamManager(zipArchive, _packageFileMode, _packageFileAccess);
contentTypeHelper = new ContentTypeHelper(zipArchive, _packageFileMode, _packageFileAccess, _zipStreamManager);
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
throw;
}
_zipArchive = zipArchive;
_contentTypeHelper = contentTypeHelper;
}
/// <summary>
/// Internal constructor that is called by the Open(Stream) static methods.
/// </summary>
/// <param name="s"></param>
/// <param name="packageFileMode"></param>
/// <param name="packageFileAccess"></param>
internal ZipPackage(Stream s, FileMode packageFileMode, FileAccess packageFileAccess)
: base(packageFileAccess)
{
ZipArchive zipArchive = null;
ContentTypeHelper contentTypeHelper = null;
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
try
{
if (s.CanSeek)
{
switch (packageFileMode)
{
case FileMode.Open:
if (s.Length == 0)
{
throw new FileFormatException(SR.ZipZeroSizeFileIsNotValidArchive);
}
break;
case FileMode.CreateNew:
if (s.Length != 0)
{
throw new IOException(SR.CreateNewOnNonEmptyStream);
}
break;
case FileMode.Create:
if (s.Length != 0)
{
s.SetLength(0); // Discard existing data
}
break;
}
}
ZipArchiveMode zipArchiveMode = ZipArchiveMode.Update;
if (packageFileAccess == FileAccess.Read)
zipArchiveMode = ZipArchiveMode.Read;
else if (packageFileAccess == FileAccess.Write)
zipArchiveMode = ZipArchiveMode.Create;
else if (packageFileAccess == FileAccess.ReadWrite)
zipArchiveMode = ZipArchiveMode.Update;
zipArchive = new ZipArchive(s, zipArchiveMode, true, Text.Encoding.UTF8);
_zipStreamManager = new ZipStreamManager(zipArchive, packageFileMode, packageFileAccess);
contentTypeHelper = new ContentTypeHelper(zipArchive, packageFileMode, packageFileAccess, _zipStreamManager);
}
catch (InvalidDataException)
{
throw new FileFormatException("File contains corrupted data.");
}
catch
{
if (zipArchive != null)
{
zipArchive.Dispose();
}
throw;
}
_containerStream = s;
_shouldCloseContainerStream = false;
_zipArchive = zipArchive;
_contentTypeHelper = contentTypeHelper;
}
#endregion Internal Constructors
#region Internal Methods
// More generic function than GetZipItemNameFromPartName. In particular, it will handle piece names.
internal static string GetZipItemNameFromOpcName(string opcName)
{
Debug.Assert(opcName != null && opcName.Length > 0);
return opcName.Substring(1);
}
// More generic function than GetPartNameFromZipItemName. In particular, it will handle piece names.
internal static string GetOpcNameFromZipItemName(string zipItemName)
{
return string.Concat(ForwardSlashString, zipItemName);
}
// Convert from Metro CompressionOption to ZipFileInfo compression properties.
internal static void GetZipCompressionMethodFromOpcCompressionOption(
CompressionOption compressionOption,
out CompressionLevel compressionLevel)
{
switch (compressionOption)
{
case CompressionOption.NotCompressed:
{
compressionLevel = CompressionLevel.NoCompression;
}
break;
case CompressionOption.Normal:
{
compressionLevel = CompressionLevel.Optimal;
}
break;
case CompressionOption.Maximum:
{
compressionLevel = CompressionLevel.Optimal;
}
break;
case CompressionOption.Fast:
{
compressionLevel = CompressionLevel.Fastest;
}
break;
case CompressionOption.SuperFast:
{
compressionLevel = CompressionLevel.Fastest;
}
break;
// fall-through is not allowed
default:
{
Debug.Fail("Encountered an invalid CompressionOption enum value");
goto case CompressionOption.NotCompressed;
}
}
}
#endregion Internal Methods
internal FileMode PackageFileMode
{
get
{
return _packageFileMode;
}
}
#region Private Methods
//returns a boolean indicating if the underlying zip item is a valid metro part or piece
// This mainly excludes the content type item, as well as entries with leading or trailing
// slashes.
private bool IsZipItemValidOpcPartOrPiece(string zipItemName)
{
Debug.Assert(zipItemName != null, "The parameter zipItemName should not be null");
//check if the zip item is the Content type item -case sensitive comparison
// The following test will filter out an atomic content type file, with name
// "[Content_Types].xml", as well as an interleaved one, with piece names such as
// "[Content_Types].xml/[0].piece" or "[Content_Types].xml/[5].last.piece".
if (zipItemName.StartsWith(ContentTypeHelper.ContentTypeFileName, StringComparison.OrdinalIgnoreCase))
return false;
else
{
//Could be an empty zip folder
//We decided to ignore zip items that contain a "/" as this could be a folder in a zip archive
//Some of the tools support this and some don't. There is no way ensure that the zip item never have
//a leading "/", although this is a requirement we impose on items created through our API
//Therefore we ignore them at the packaging api level.
if (zipItemName.StartsWith(ForwardSlashString, StringComparison.Ordinal))
return false;
//This will ignore the folder entries found in the zip package created by some zip tool
//PartNames ending with a "/" slash is also invalid so we are skipping these entries,
//this will also prevent the PackUriHelper.CreatePartUri from throwing when it encounters a
// partname ending with a "/"
if (zipItemName.EndsWith(ForwardSlashString, StringComparison.Ordinal))
return false;
else
return true;
}
}
// convert from Zip CompressionMethodEnum and DeflateOptionEnum to Metro CompressionOption
private static CompressionOption GetCompressionOptionFromZipFileInfo(ZipArchiveEntry zipFileInfo)
{
// Note: we can't determine compression method / level from the ZipArchiveEntry.
CompressionOption result = CompressionOption.Normal;
return result;
}
#endregion Private Methods
#region Private Members
private const int InitialPartListSize = 50;
private readonly ZipArchive _zipArchive;
private Stream _containerStream; // stream we are opened in if Open(Stream) was called
private readonly bool _shouldCloseContainerStream;
private readonly ContentTypeHelper _contentTypeHelper; // manages the content types for all the parts in the container
private readonly ZipStreamManager _zipStreamManager; // manages streams for all parts, avoiding opening streams multiple times
private readonly FileAccess _packageFileAccess;
private readonly FileMode _packageFileMode;
private const string ForwardSlashString = "/"; //Required for creating a part name from a zip item name
//IEqualityComparer for extensions
private static readonly ExtensionEqualityComparer s_extensionEqualityComparer = new ExtensionEqualityComparer();
#endregion Private Members
/// <summary>
/// ExtensionComparer
/// The Extensions are stored in the Default Dictionary in their original form,
/// however they are compared in a normalized manner.
/// Equivalence for extensions in the content type stream, should follow
/// the same rules as extensions of partnames. Also, by the time this code is invoked,
/// we have already validated, that the extension is in the correct format as per the
/// part name rules.So we are simplifying the logic here to just convert the extensions
/// to Upper invariant form and then compare them.
/// </summary>
private sealed class ExtensionEqualityComparer : IEqualityComparer<string>
{
bool IEqualityComparer<string>.Equals(string extensionA, string extensionB)
{
Debug.Assert(extensionA != null, "extension should not be null");
Debug.Assert(extensionB != null, "extension should not be null");
//Important Note: any change to this should be made in accordance
//with the rules for comparing/normalizing partnames.
//Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method.
//Currently normalization just involves upper-casing ASCII and hence the simplification.
return (string.CompareOrdinal(extensionA.ToUpperInvariant(), extensionB.ToUpperInvariant()) == 0);
}
int IEqualityComparer<string>.GetHashCode(string extension)
{
Debug.Assert(extension != null, "extension should not be null");
//Important Note: any change to this should be made in accordance
//with the rules for comparing/normalizing partnames.
//Refer to PackUriHelper.ValidatedPartUri.GetNormalizedPartUri method.
//Currently normalization just involves upper-casing ASCII and hence the simplification.
return extension.ToUpperInvariant().GetHashCode();
}
}
/// <summary>
/// This is a helper class that maintains the Content Types File related to
/// this ZipPackage.
/// </summary>
private class ContentTypeHelper
{
/// <summary>
/// Initialize the object without uploading any information from the package.
/// Complete initialization in read mode also involves calling ParseContentTypesFile
/// to deserialize content type information.
/// </summary>
internal ContentTypeHelper(ZipArchive zipArchive, FileMode packageFileMode, FileAccess packageFileAccess, ZipStreamManager zipStreamManager)
{
_zipArchive = zipArchive; //initialized in the ZipPackage constructor
_packageFileMode = packageFileMode;
_packageFileAccess = packageFileAccess;
_zipStreamManager = zipStreamManager; //initialized in the ZipPackage constructor
// The extensions are stored in the default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
_defaultDictionary = new Dictionary<string, ContentType>(DefaultDictionaryInitialSize, s_extensionEqualityComparer);
// Identify the content type file or files before identifying parts and piece sequences.
// This is necessary because the name of the content type stream is not a part name and
// the information it contains is needed to recognize valid parts.
if (_zipArchive.Mode == ZipArchiveMode.Read || _zipArchive.Mode == ZipArchiveMode.Update)
ParseContentTypesFile(_zipArchive.Entries);
//No contents to persist to the disk -
_dirty = false; //by default
//Lazy initialize these members as required
//_overrideDictionary - Overrides should be rare
//_contentTypeFileInfo - We will either find an atomin part, or
//_contentTypeStreamPieces - an interleaved part
//_contentTypeStreamExists - defaults to false - not yet found
}
internal static string ContentTypeFileName
{
get
{
return ContentTypesFile;
}
}
//Adds the Default entry if it is the first time we come across
//the extension for the partUri, does nothing if the content type
//corresponding to the default entry for the extension matches or
//adds a override corresponding to this part and content type.
//This call is made when a new part is being added to the package.
// This method assumes the partUri is valid.
internal void AddContentType(PackUriHelper.ValidatedPartUri partUri, ContentType contentType,
CompressionLevel compressionLevel)
{
//save the compressionOption and deflateOption that should be used
//to create the content type item later
if (!_contentTypeStreamExists)
{
_cachedCompressionLevel = compressionLevel;
}
// Figure out whether the mapping matches a default entry, can be made into a new
// default entry, or has to be entered as an override entry.
bool foundMatchingDefault = false;
string extension = partUri.PartUriExtension;
// Need to create an override entry?
if (extension.Length == 0
|| (_defaultDictionary.ContainsKey(extension)
&& !(foundMatchingDefault =
_defaultDictionary[extension].AreTypeAndSubTypeEqual(contentType))))
{
AddOverrideElement(partUri, contentType);
}
// Else, either there is already a mapping from extension to contentType,
// or one needs to be created.
else if (!foundMatchingDefault)
{
AddDefaultElement(extension, contentType);
}
}
//Returns the content type for the part, if present, else returns null.
internal ContentType GetContentType(PackUriHelper.ValidatedPartUri partUri)
{
//Step 1: Check if there is an override entry present corresponding to the
//partUri provided. Override takes precedence over the default entries
if (_overrideDictionary != null)
{
if (_overrideDictionary.ContainsKey(partUri))
return _overrideDictionary[partUri];
}
//Step 2: Check if there is a default entry corresponding to the
//extension of the partUri provided.
string extension = partUri.PartUriExtension;
if (_defaultDictionary.ContainsKey(extension))
return _defaultDictionary[extension];
//Step 3: If we did not find an entry in the override and the default
//dictionaries, this is an error condition
return null;
}
//Deletes the override entry corresponding to the partUri, if it exists
internal void DeleteContentType(PackUriHelper.ValidatedPartUri partUri)
{
if (_overrideDictionary != null)
{
if (_overrideDictionary.Remove(partUri))
_dirty = true;
}
}
internal void SaveToFile()
{
if (_dirty)
{
//Lazy init: Initialize when the first part is added.
if (!_contentTypeStreamExists)
{
_contentTypeZipArchiveEntry = _zipArchive.CreateEntry(ContentTypesFile, _cachedCompressionLevel);
_contentTypeStreamExists = true;
}
else
{
// delete and re-create entry for content part. When writing this, the stream will not truncate the content
// if the XML is shorter than the existing content part.
var contentTypefullName = _contentTypeZipArchiveEntry.FullName;
var thisArchive = _contentTypeZipArchiveEntry.Archive;
_zipStreamManager.Close(_contentTypeZipArchiveEntry);
_contentTypeZipArchiveEntry.Delete();
_contentTypeZipArchiveEntry = thisArchive.CreateEntry(contentTypefullName);
}
using (Stream s = _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite))
{
// use UTF-8 encoding by default
using (XmlWriter writer = XmlWriter.Create(s, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 }))
{
writer.WriteStartDocument();
// write root element tag - Types
writer.WriteStartElement(TypesTagName, TypesNamespaceUri);
// for each default entry
foreach (string key in _defaultDictionary.Keys)
{
WriteDefaultElement(writer, key, _defaultDictionary[key]);
}
if (_overrideDictionary != null)
{
// for each override entry
foreach (PackUriHelper.ValidatedPartUri key in _overrideDictionary.Keys)
{
WriteOverrideElement(writer, key, _overrideDictionary[key]);
}
}
// end of Types tag
writer.WriteEndElement();
// close the document
writer.WriteEndDocument();
_dirty = false;
}
}
}
}
private void EnsureOverrideDictionary()
{
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using the PartUriComparer
if (_overrideDictionary == null)
_overrideDictionary = new Dictionary<PackUriHelper.ValidatedPartUri, ContentType>(OverrideDictionaryInitialSize);
}
private void ParseContentTypesFile(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
{
// Find the content type stream, allowing for interleaving. Naming collisions
// (as between an atomic and an interleaved part) will result in an exception being thrown.
Stream s = OpenContentTypeStream(zipFiles);
// Allow non-existent content type stream.
if (s == null)
return;
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.IgnoreWhitespace = true;
using (s)
using (XmlReader reader = XmlReader.Create(s, xrs))
{
//This method expects the reader to be in ReadState.Initial.
//It will make the first read call.
PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader);
//Note: After the previous method call the reader should be at the first tag in the markup.
//MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
// look for our root tag and namespace pair - ignore others in case of version changes
// Make sure that the current node read is an Element
if ((reader.NodeType == XmlNodeType.Element)
&& (reader.Depth == 0)
&& (string.CompareOrdinal(reader.NamespaceURI, TypesNamespaceUri) == 0)
&& (string.CompareOrdinal(reader.Name, TypesTagName) == 0))
{
//There should be a namespace Attribute present at this level.
//Also any other attribute on the <Types> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0)
{
throw new XmlException(SR.TypesTagHasExtraAttributes, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
// start tag encountered
// now parse individual Default and Override tags
while (reader.Read())
{
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
//If MoveToContent() takes us to the end of the content
if (reader.NodeType == XmlNodeType.None)
continue;
// Make sure that the current node read is an element
// Currently we expect the Default and Override Tag at Depth 1
if (reader.NodeType == XmlNodeType.Element
&& reader.Depth == 1
&& (string.CompareOrdinal(reader.NamespaceURI, TypesNamespaceUri) == 0)
&& (string.CompareOrdinal(reader.Name, DefaultTagName) == 0))
{
ProcessDefaultTagAttributes(reader);
}
else if (reader.NodeType == XmlNodeType.Element
&& reader.Depth == 1
&& (string.CompareOrdinal(reader.NamespaceURI, TypesNamespaceUri) == 0)
&& (string.CompareOrdinal(reader.Name, OverrideTagName) == 0))
{
ProcessOverrideTagAttributes(reader);
}
else if (reader.NodeType == XmlNodeType.EndElement && reader.Depth == 0 && string.CompareOrdinal(reader.Name, TypesTagName) == 0)
{
continue;
}
else
{
throw new XmlException(SR.TypesXmlDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
}
else
{
throw new XmlException(SR.TypesElementExpected, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
}
}
/// <summary>
/// Find the content type stream, allowing for interleaving. Naming collisions
/// (as between an atomic and an interleaved part) will result in an exception being thrown.
/// Return null if no content type stream has been found.
/// </summary>
/// <remarks>
/// The input array is lexicographically sorted
/// </remarks>
private Stream OpenContentTypeStream(System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> zipFiles)
{
foreach (ZipArchiveEntry zipFileInfo in zipFiles)
{
if (zipFileInfo.Name.ToUpperInvariant().StartsWith(ContentTypesFileUpperInvariant, StringComparison.Ordinal))
{
// Atomic name.
if (zipFileInfo.Name.Length == ContentTypeFileName.Length)
{
// Record the file info.
_contentTypeZipArchiveEntry = zipFileInfo;
}
}
}
// If an atomic file was found, open a stream on it.
if (_contentTypeZipArchiveEntry != null)
{
_contentTypeStreamExists = true;
return _zipStreamManager.Open(_contentTypeZipArchiveEntry, _packageFileMode, FileAccess.ReadWrite);
}
// No content type stream was found.
return null;
}
// Process the attributes for the Default tag
private void ProcessDefaultTagAttributes(XmlReader reader)
{
//There could be a namespace Attribute present at this level.
//Also any other attribute on the <Default> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2)
throw new XmlException(SR.DefaultTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
// get the required Extension and ContentType attributes
string extensionAttributeValue = reader.GetAttribute(ExtensionAttributeName);
ValidateXmlAttribute(ExtensionAttributeName, extensionAttributeValue, DefaultTagName, reader);
string contentTypeAttributeValue = reader.GetAttribute(ContentTypeAttributeName);
ThrowIfXmlAttributeMissing(ContentTypeAttributeName, contentTypeAttributeValue, DefaultTagName, reader);
// The extensions are stored in the Default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
PackUriHelper.ValidatedPartUri temporaryUri = PackUriHelper.ValidatePartUri(
new Uri(TemporaryPartNameWithoutExtension + extensionAttributeValue, UriKind.Relative));
_defaultDictionary.Add(temporaryUri.PartUriExtension, new ContentType(contentTypeAttributeValue));
//Skip the EndElement for Default Tag
if (!reader.IsEmptyElement)
ProcessEndElement(reader, DefaultTagName);
}
// Process the attributes for the Default tag
private void ProcessOverrideTagAttributes(XmlReader reader)
{
//There could be a namespace Attribute present at this level.
//Also any other attribute on the <Override> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 2)
throw new XmlException(SR.OverrideTagDoesNotMatchSchema, null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
// get the required Extension and ContentType attributes
string partNameAttributeValue = reader.GetAttribute(PartNameAttributeName);
ValidateXmlAttribute(PartNameAttributeName, partNameAttributeValue, OverrideTagName, reader);
string contentTypeAttributeValue = reader.GetAttribute(ContentTypeAttributeName);
ThrowIfXmlAttributeMissing(ContentTypeAttributeName, contentTypeAttributeValue, OverrideTagName, reader);
PackUriHelper.ValidatedPartUri partUri = PackUriHelper.ValidatePartUri(new Uri(partNameAttributeValue, UriKind.Relative));
//Lazy initializing - ensure that the override dictionary has been initialized
EnsureOverrideDictionary();
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using PartUriComparer.
_overrideDictionary.Add(partUri, new ContentType(contentTypeAttributeValue));
//Skip the EndElement for Override Tag
if (!reader.IsEmptyElement)
ProcessEndElement(reader, OverrideTagName);
}
//If End element is present for Relationship then we process it
private void ProcessEndElement(XmlReader reader, string elementName)
{
Debug.Assert(!reader.IsEmptyElement, "This method should only be called it the Relationship Element is not empty");
reader.Read();
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
reader.MoveToContent();
if (reader.NodeType == XmlNodeType.EndElement && string.CompareOrdinal(elementName, reader.LocalName) == 0)
return;
else
throw new XmlException(SR.Format(SR.ElementIsNotEmptyElement, elementName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
private void AddOverrideElement(PackUriHelper.ValidatedPartUri partUri, ContentType contentType)
{
//Delete any entry corresponding in the Override dictionary
//corresponding to the PartUri for which the contentType is being added.
//This is to compensate for dead override entries in the content types file.
DeleteContentType(partUri);
//Lazy initializing - ensure that the override dictionary has been initialized
EnsureOverrideDictionary();
// The part Uris are stored in the Override Dictionary in their original form , but they are compared
// in a normalized manner using PartUriComparer.
_overrideDictionary.Add(partUri, contentType);
_dirty = true;
}
private void AddDefaultElement(string extension, ContentType contentType)
{
// The extensions are stored in the Default Dictionary in their original form , but they are compared
// in a normalized manner using the ExtensionComparer.
_defaultDictionary.Add(extension, contentType);
_dirty = true;
}
private void WriteOverrideElement(XmlWriter xmlWriter, PackUriHelper.ValidatedPartUri partUri, ContentType contentType)
{
xmlWriter.WriteStartElement(OverrideTagName);
xmlWriter.WriteAttributeString(PartNameAttributeName,
partUri.PartUriString);
xmlWriter.WriteAttributeString(ContentTypeAttributeName, contentType.ToString());
xmlWriter.WriteEndElement();
}
private void WriteDefaultElement(XmlWriter xmlWriter, string extension, ContentType contentType)
{
xmlWriter.WriteStartElement(DefaultTagName);
xmlWriter.WriteAttributeString(ExtensionAttributeName, extension);
xmlWriter.WriteAttributeString(ContentTypeAttributeName, contentType.ToString());
xmlWriter.WriteEndElement();
}
//Validate if the required XML attribute is present and not an empty string
private void ValidateXmlAttribute(string attributeName, string attributeValue, string tagName, XmlReader reader)
{
ThrowIfXmlAttributeMissing(attributeName, attributeValue, tagName, reader);
//Checking for empty attribute
if (attributeValue == string.Empty)
throw new XmlException(SR.Format(SR.RequiredAttributeEmpty, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
//Validate if the required Content type XML attribute is present
//Content type of a part can be empty
private void ThrowIfXmlAttributeMissing(string attributeName, string attributeValue, string tagName, XmlReader reader)
{
if (attributeValue == null)
throw new XmlException(SR.Format(SR.RequiredAttributeMissing, tagName, attributeName), null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
}
private Dictionary<PackUriHelper.ValidatedPartUri, ContentType> _overrideDictionary;
private readonly Dictionary<string, ContentType> _defaultDictionary;
private readonly ZipArchive _zipArchive;
private readonly FileMode _packageFileMode;
private readonly FileAccess _packageFileAccess;
private readonly ZipStreamManager _zipStreamManager;
private ZipArchiveEntry _contentTypeZipArchiveEntry;
private bool _contentTypeStreamExists;
private bool _dirty;
private CompressionLevel _cachedCompressionLevel;
private const string ContentTypesFile = "[Content_Types].xml";
private const string ContentTypesFileUpperInvariant = "[CONTENT_TYPES].XML";
private const int DefaultDictionaryInitialSize = 16;
private const int OverrideDictionaryInitialSize = 8;
//Xml tag specific strings for the Content Type file
private const string TypesNamespaceUri = "http://schemas.openxmlformats.org/package/2006/content-types";
private const string TypesTagName = "Types";
private const string DefaultTagName = "Default";
private const string ExtensionAttributeName = "Extension";
private const string ContentTypeAttributeName = "ContentType";
private const string OverrideTagName = "Override";
private const string PartNameAttributeName = "PartName";
private const string TemporaryPartNameWithoutExtension = "/tempfiles/sample.";
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: AdapterView.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Android.Views;
using Dot42;
namespace Android.Widget
{
[Dot42.DexImport("android/widget/AdapterView", Priority=1, IgnoreFromJava=true, AccessFlags = 1057, Signature = "<T::Landroid/widget/Adapter;>Landroid/view/ViewGroup;")]
public abstract class AdapterView : AdapterView<object>
{
/// <summary>
/// Event arguments for Item selected events.
/// </summary>
public class ItemSelectedEventArgs : EventArgs
{
/// <summary>
/// Default ctor
/// </summary>
public ItemSelectedEventArgs(AdapterView parent, View view, int position, long id)
{
Parent = parent;
Id = id;
Position = position;
View = view;
}
/// <summary>
/// The view that was selected (provided by the adapter)
/// </summary>
public View View { get; private set; }
/// <summary>
/// Position of the view within the adapter
/// </summary>
public int Position { get; private set; }
public AdapterView Parent { get; set; }
/// <summary>
/// Row id of the item that was selected
/// </summary>
public long Id { get; private set; }
}
/// <summary>
/// Event arguments for Item click events.
/// </summary>
public class ItemClickEventArgs : EventArgs
{
/// <summary>
/// Default ctor
/// </summary>
public ItemClickEventArgs(AdapterView parent, View view, int position, long id)
{
Parent = parent;
Id = id;
Position = position;
View = view;
}
/// <summary>
/// The view that was clicked (provided by the adapter)
/// </summary>
public View View { get; private set; }
/// <summary>
/// Position of the view within the adapter
/// </summary>
public int Position { get; private set; }
/// <summary>
/// The Adapter in which the click occured.
/// </summary>
public AdapterView Parent { get; set; }
/// <summary>
/// Row id of the item that was clicked
/// </summary>
public long Id { get; private set; }
/// <summary>
/// Set this property to true when the listenered has consumed the event.
/// </summary>
public bool IsHandled { get; set; }
}
}
partial class AdapterView<T>
{
#region System resource ID's
#pragma warning disable 649
[Dot42.ResourceId("__dot42_adapterview_itemclick_listener")]
private static readonly int itemClickListenerKey;
[Dot42.ResourceId("__dot42_adapterview_itemlongclick_listener")]
private static readonly int itemLongClickListenerKey;
[Dot42.ResourceId("__dot42_adapterview_itemselected_listener")]
private static readonly int itemSelectedListenerKey;
#pragma warning restore 649
#endregion // System resource ID's
/// <summary>
/// Fired when this view item is clicked on.
/// </summary>
[ListenerInterface("android/widget/AdapterView$OnItemClickListener")]
public event EventHandler<AdapterView.ItemClickEventArgs> ItemClick
{
add
{
var listener = (AdapterViewOnItemClickListener<T>)GetTag(itemClickListenerKey);
if (listener == null)
{
listener = new AdapterViewOnItemClickListener<T>();
SetTag(itemClickListenerKey, listener);
OnItemClickListener = listener;
}
listener.Add(value);
}
remove
{
var listener = (AdapterViewOnItemClickListener<T>)GetTag(itemClickListenerKey);
if (listener != null) listener.Remove(value);
}
}
/// <summary>
/// Fired when this view item is clicked on long.
/// </summary>
[ListenerInterface("android/widget/AdapterView$OnItemLongClickListener")]
public event EventHandler<AdapterView.ItemClickEventArgs> ItemLongClick
{
add
{
var listener = (AdapterViewOnItemClickListener<T>)GetTag(itemLongClickListenerKey);
if (listener == null)
{
listener = new AdapterViewOnItemClickListener<T>();
SetTag(itemLongClickListenerKey, listener);
OnItemLongClickListener = listener;
}
listener.Add(value);
}
remove
{
var listener = (AdapterViewOnItemClickListener<T>)GetTag(itemLongClickListenerKey);
if (listener != null) listener.Remove(value);
}
}
/// <summary>
/// Fired when an item in this view has been selected.
/// </summary>
[ListenerInterface("android/widget/AdapterView$OnItemSelectedListener")]
public event EventHandler<AdapterView.ItemSelectedEventArgs> ItemSelected
{
add
{
var listener = (AdapterViewOnItemSelectedListener<T>)GetTag(itemSelectedListenerKey);
if (listener == null)
{
listener = new AdapterViewOnItemSelectedListener<T>();
SetTag(itemSelectedListenerKey, listener);
OnItemSelectedListener = listener;
}
listener.ItemSelected.Add(value);
}
remove
{
var listener = (AdapterViewOnItemSelectedListener<T>)GetTag(itemSelectedListenerKey);
if (listener != null) listener.ItemSelected.Remove(value);
}
}
/// <summary>
/// Fired when the selection disappears from this view.
/// </summary>
[ListenerInterface("android/widget/AdapterView$OnItemSelectedListener")]
public event EventHandler NothingSelected
{
add
{
var listener = (AdapterViewOnItemSelectedListener<T>)GetTag(itemSelectedListenerKey);
if (listener == null)
{
listener = new AdapterViewOnItemSelectedListener<T>();
SetTag(itemSelectedListenerKey, listener);
OnItemSelectedListener = listener;
}
listener.NothingSelected.Add(value);
}
remove
{
var listener = (AdapterViewOnItemSelectedListener<T>)GetTag(itemSelectedListenerKey);
if (listener != null) listener.NothingSelected.Remove(value);
}
}
}
/// <summary>
/// Implementation of the <see cref="ItemClick"/> event.
/// </summary>
internal sealed class AdapterViewOnItemClickListener<T> : Dot42.EventHandlerListener<AdapterView.ItemClickEventArgs>,
AdapterView<T>.IOnItemClickListener, AdapterView<T>.IOnItemLongClickListener
{
/// <summary>
/// Invoke
/// </summary>
public void OnItemClick(AdapterView<object> adapterView, View view, int position, long id)
{
Invoke(adapterView, new AdapterView.ItemClickEventArgs((AdapterView)adapterView, view, position, id));
}
public bool OnItemLongClick(AdapterView<object> adapterView, View view, int position, long id)
{
var args = new AdapterView.ItemClickEventArgs((AdapterView)adapterView, view, position, id);
Invoke(adapterView, args);
return args.IsHandled;
}
}
/// <summary>
/// Implementation of the <see cref="ItemSelected"/> event.
/// </summary>
internal sealed class AdapterViewOnItemSelectedListener<T> : AdapterView<T>.IOnItemSelectedListener
{
internal readonly Dot42.EventHandlerListener<AdapterView.ItemSelectedEventArgs> ItemSelected = new EventHandlerListener<AdapterView.ItemSelectedEventArgs>();
internal readonly Dot42.EventHandlerListener NothingSelected = new EventHandlerListener();
public void OnItemSelected(AdapterView<object> adapterView, View view, int position, long id)
{
ItemSelected.Invoke(adapterView, new AdapterView.ItemSelectedEventArgs((AdapterView)adapterView, view, position, id));
}
public void OnNothingSelected(AdapterView<object> adapterView)
{
NothingSelected.Invoke(adapterView, System.EventArgs.Empty);
}
}
}
| |
#region Foreign-License
/*
Copyright (c) 1997 Sun Microsystems, Inc.
Copyright (c) 2012 Sky Morey
See the file "license.terms" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*/
#endregion
using System.Text;
namespace Tcl.Lang
{
// This class implements the string object type in Tcl.
public class TclString : IInternalRep
{
/// <summary> Called to convert the other object's internal rep to string.
///
/// </summary>
/// <param name="tobj">the TclObject to convert to use the TclString internal rep.
/// </param>
private static TclObject StringFromAny
{
set
{
IInternalRep rep = value.InternalRep;
if (!(rep is TclString))
{
// make sure that this object now has a valid string rep.
value.ToString();
// Change the type of the object to TclString.
value.InternalRep = new TclString();
}
}
/*
* public static String get(TclObject tobj) {;}
*
* There is no "get" class method for TclString representations.
* Use tobj.toString() instead.
*/
}
// Used to perform "append" operations. After an append op,
// sbuf.toString() will contain the latest value of the string and
// tobj.stringRep will be set to null. This field is not private
// since it will need to be accessed directly by Jacl's IO code.
internal StringBuilder sbuf;
private TclString()
{
sbuf = null;
}
private TclString(StringBuilder sb)
{
sbuf = sb;
}
/// <summary> Returns a dupilcate of the current object.</summary>
/// <param name="obj">the TclObject that contains this internalRep.
/// </param>
public IInternalRep Duplicate()
{
return new TclString();
}
/// <summary> Implement this no-op for the InternalRep interface.</summary>
public void Dispose()
{
}
/// <summary> Called to query the string representation of the Tcl object. This
/// method is called only by TclObject.toString() when
/// TclObject.stringRep is null.
///
/// </summary>
/// <returns> the string representation of the Tcl object.
/// </returns>
public override string ToString()
{
if (sbuf == null)
{
return "";
}
else
{
return sbuf.ToString();
}
}
/// <summary> Create a new TclObject that has a string representation with
/// the given string value.
/// </summary>
public static TclObject NewInstance(string str)
{
return new TclObject(new TclString(), str);
}
/// <summary> Create a new TclObject that makes use of the given StringBuffer
/// object. The passed in StringBuffer should not be modified after
/// it is passed to this method.
/// </summary>
internal static TclObject NewInstance(StringBuilder sb)
{
return new TclObject(new TclString(sb));
}
internal static TclObject NewInstance(System.Object o)
{
return NewInstance(o.ToString());
}
/// <summary> Create a TclObject with an internal TclString representation
/// whose initial value is a string with the single character.
///
/// </summary>
/// <param name="c">initial value of the string.
/// </param>
internal static TclObject NewInstance(char c)
{
char[] charArray = new char[1];
charArray[0] = c;
return NewInstance(new string(charArray));
}
/// <summary> Appends a string to a TclObject object. This method is equivalent to
/// Tcl_AppendToObj() in Tcl 8.0.
///
/// </summary>
/// <param name="tobj">the TclObject to append a string to.
/// </param>
/// <param name="string">the string to append to the object.
/// </param>
public static void append(TclObject tobj, string toAppend)
{
StringFromAny = tobj;
TclString tstr = (TclString)tobj.InternalRep;
if (tstr.sbuf == null)
{
tstr.sbuf = new StringBuilder(tobj.ToString());
}
tobj.invalidateStringRep();
tstr.sbuf.Append(toAppend);
}
/// <summary> Appends an array of characters to a TclObject Object.
/// Tcl_AppendUnicodeToObj() in Tcl 8.0.
///
/// </summary>
/// <param name="tobj">the TclObject to append a string to.
/// </param>
/// <param name="charArr">array of characters.
/// </param>
/// <param name="offset">index of first character to append.
/// </param>
/// <param name="length">number of characters to append.
/// </param>
public static void append(TclObject tobj, char[] charArr, int offset, int length)
{
StringFromAny = tobj;
TclString tstr = (TclString)tobj.InternalRep;
if (tstr.sbuf == null)
{
tstr.sbuf = new StringBuilder(tobj.ToString());
}
tobj.invalidateStringRep();
tstr.sbuf.Append(charArr, offset, length);
}
/// <summary> Appends a TclObject to a TclObject. This method is equivalent to
/// Tcl_AppendToObj() in Tcl 8.0.
///
/// The type of the TclObject will be a TclString that contains the
/// string value:
/// tobj.toString() + tobj2.toString();
/// </summary>
internal static void append(TclObject tobj, TclObject tobj2)
{
append(tobj, tobj2.ToString());
}
/// <summary> This procedure clears out an existing TclObject so
/// that it has a string representation of "".
/// </summary>
public static void empty(TclObject tobj)
{
StringFromAny = tobj;
TclString tstr = (TclString)tobj.InternalRep;
if (tstr.sbuf == null)
{
tstr.sbuf = new StringBuilder();
}
else
{
tstr.sbuf.Length = 0;
}
tobj.invalidateStringRep();
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Collections.Specialized;
namespace Kooboo.Drawing.Filters
{
/// <summary>
/// Text Water Mark Filter .Can be used to add a watermark text to the image.
/// The weater mark can be both horizontaly and verticaly aligned.
/// Also provides simple captions functionality (Simple text on an image)
/// </summary>
public class TextWatermarkFilter : WaterMarkFilter
{
#region Public Properties Tokens
public const string WIDTH_TOKEN_NAME = "Width";
public const string HEIGHT_TOKEN_NAME = "Height";
public const string ALPHA_TOKEN_NAME = "ALPHA";
#endregion Public Properties Tokens
#region Private Fields
private int _alpha = 75;
private Color _captionColor = Color.White;
private string _caption = "Test";
private int _textSize = 10; //default
private bool _automaticTextSizing = false;
#endregion Private Fields
#region Filter Properties
//public HAlign Halign = HAlign.Bottom;
//public VAlign Valign = VAlign.Center;
public int TextSize
{
get { return _textSize; }
set { _textSize = value; }
}
public bool AutomaticTextSize
{
get { return _automaticTextSizing; }
set { _automaticTextSizing = value; }
}
public int CaptionAlpha
{
get
{
return _alpha;
}
set
{
_alpha = value;
}
}
public Color CaptionColor
{
get { return _captionColor; }
set { _captionColor = value; }
}
public string Caption
{
get { return _caption; }
set { _caption = value; }
}
#endregion Filter Properties
#region Public Functions
/// <summary>
/// Executes this filter on the input image and returns the image with the WaterMark
/// </summary>
/// <param name="rawImage">input image</param>
/// <returns>transformed image</returns>
/// <example>
/// <code>
/// Image transformed;
/// TextWatermarkFilter textWaterMark = new TextWatermarkFilter();
/// textWaterMark.Caption = "Pitzi";
/// textWaterMark.TextSize = 20;
/// textWaterMark.AutomaticTextSize = false;
/// textWaterMark.Valign = TextWatermarkFilter.VAlign.Right;
/// textWaterMark.Halign = TextWatermarkFilter.HAlign.Bottom;
/// textWaterMark.CaptionColor = Color.Red;
/// transformed = textWaterMark.ExecuteFilter(myImg);
/// </code>
/// </example>
public override Image ExecuteFilter(Image rawImage)
{
_width = rawImage.Width;
_height = rawImage.Height;
//create a Bitmap the Size of the original photograph
Bitmap bmPhoto = new Bitmap(rawImage.Width, rawImage.Height, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(rawImage.HorizontalResolution, rawImage.VerticalResolution);
//load the Bitmap into a Graphics object
Graphics grPhoto = Graphics.FromImage(bmPhoto);
//Set the rendering quality for this Graphics object
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
//Draws the photo Image object at original size to the graphics object.
grPhoto.DrawImage(
rawImage, // Photo Image object
new Rectangle(0, 0, _width, _height), // Rectangle structure
0, // x-coordinate of the portion of the source image to draw.
0, // y-coordinate of the portion of the source image to draw.
_width, // Width of the portion of the source image to draw.
_height, // Height of the portion of the source image to draw.
GraphicsUnit.Pixel); // Units of measure
//-------------------------------------------------------
//Set up the automatic font settings
//-------------------------------------------------------
int[] sizes = new int[] { 128, 64, 32, 16, 14, 12, 10, 8, 6, 4 };
Font crFont = null;
SizeF crSize = new SizeF();
if (_automaticTextSizing)
{
//If automatic sizing is turned on
//loop through the defined sizes checking the length of the caption string string
for (int i = 0; i < sizes.Length; i++)
{
//set a Font object to Arial (i)pt, Bold
crFont = new Font("arial", sizes[i], FontStyle.Bold);
//Measure the Copyright string in this Font
crSize = grPhoto.MeasureString(_caption, crFont);
if ((ushort)crSize.Width < (ushort)_width)
break;
}
}
else
{
crFont = new Font("arial", _textSize, FontStyle.Bold);
}
crSize = grPhoto.MeasureString(_caption, crFont);
//Since all photographs will have varying heights, determine a
//position 5% from the bottom of the image
int yPixelsMargin = (int)(_height * .0002);
float yPosFromBottom;
float xPositionFromLeft;
CalcDrawPosition((int)crSize.Width,(int)crSize.Height, yPixelsMargin, out yPosFromBottom, out xPositionFromLeft);
//Define the text layout by setting the text alignment to centered
StringFormat StrFormat = new StringFormat();
//StrFormat.Alignment = StringAlignment.Near;
//define a Brush which is semi trasparent black (Alpha set to 153)
SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(_alpha, 0, 0, 0));
//Draw the Copyright string
grPhoto.DrawString(_caption, //string of text
crFont, //font
semiTransBrush2, //Brush
new PointF(xPositionFromLeft + 1, yPosFromBottom + 1), //Position
StrFormat);
//define a Brush which is semi trasparent white (Alpha set to 153)
SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(_alpha, _captionColor.R,_captionColor.G,_captionColor.B));
//Draw the Copyright string a second time to create a shadow effect
//Make sure to move this text 1 pixel to the right and down 1 pixel
grPhoto.DrawString(_caption, //string of text
crFont, //font
semiTransBrush, //Brush
new PointF(xPositionFromLeft, yPosFromBottom), //Position
StrFormat); //Text alignment
grPhoto.Dispose();
return bmPhoto;
}
public override Image ExecuteFilterDemo(Image rawImage)
{
this.Caption = "Caption Demo";
this.TextSize = 18;
this.AutomaticTextSize = false;
this.Halign = HAlign.Bottom;
this.Valign = VAlign.Right;
return this.ExecuteFilter(rawImage);
}
#endregion Public Functions
#region Private
#endregion Private
}
}
| |
// Copyright (c) 2013 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
#if !__MonoCS__
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Microsoft.Unmanaged.TSF;
using Microsoft.Win32;
using Palaso.UI.WindowsForms.Keyboarding.Interfaces;
using Palaso.UI.WindowsForms.Keyboarding.InternalInterfaces;
using Palaso.UI.WindowsForms.Keyboarding.Types;
using Palaso.WritingSystems;
namespace Palaso.UI.WindowsForms.Keyboarding.Windows
{
/// <summary>
/// Class for handling Windows system keyboards
/// </summary>
[SuppressMessage("Gendarme.Rules.Design", "TypesWithDisposableFieldsShouldBeDisposableRule",
Justification = "m_Timer gets disposed in Close() which gets called from KeyboardControllerImpl.Dispose")]
internal class WinKeyboardAdaptor: IKeyboardAdaptor
{
internal class LayoutName
{
public LayoutName()
{
Name = string.Empty;
LocalizedName = string.Empty;
}
public LayoutName(string layout): this(layout, layout)
{
}
public LayoutName(string layout, string localizedLayout)
{
Name = layout;
LocalizedName = localizedLayout;
}
public string Name;
public string LocalizedName;
}
private List<IKeyboardErrorDescription> m_BadLocales;
private Timer m_Timer;
private WinKeyboardDescription m_ExpectedKeyboard;
private bool m_fSwitchedLanguages;
/// <summary>Used to prevent re-entrancy. <c>true</c> while we're in the middle of switching keyboards.</summary>
private bool m_fSwitchingKeyboards;
internal ITfInputProcessorProfiles ProcessorProfiles { get; private set; }
internal ITfInputProcessorProfileMgr ProfileMgr { get; private set; }
public WinKeyboardAdaptor()
{
try
{
ProcessorProfiles = new TfInputProcessorProfilesClass();
}
catch (InvalidCastException)
{
ProcessorProfiles = null;
return;
}
// ProfileMgr will be null on Windows XP - the interface got introduced in Vista
ProfileMgr = ProcessorProfiles as ITfInputProcessorProfileMgr;
}
protected short[] Languages
{
get
{
if (ProcessorProfiles == null)
return new short[0];
var ptr = IntPtr.Zero;
try
{
var count = ProcessorProfiles.GetLanguageList(out ptr);
if (count <= 0)
return new short[0];
var langIds = new short[count];
Marshal.Copy(ptr, langIds, 0, count);
return langIds;
}
catch (InvalidCastException)
{
// For strange reasons tests on TeamCity failed with InvalidCastException: Unable
// to cast COM object of type TfInputProcessorProfilesClass to interface type
// ITfInputProcessorProfiles when trying to call GetLanguageList. Don't know why
// it wouldn't fail when we create the object. Since it's theoretically possible
// that this also happens on a users machine we catch the exception here - maybe
// TSF is not enabled?
ProcessorProfiles = null;
return new short[0];
}
finally
{
if (ptr != IntPtr.Zero)
Marshal.FreeCoTaskMem(ptr);
}
}
}
private void GetInputMethodsThroughTsf(short[] languages)
{
foreach (var langId in languages)
{
var profilesEnumerator = ProfileMgr.EnumProfiles(langId);
TfInputProcessorProfile profile;
while (profilesEnumerator.Next(1, out profile) == 1)
{
// We only deal with keyboards; skip other input methods
if (profile.CatId != Guids.TfcatTipKeyboard)
continue;
if ((profile.Flags & TfIppFlags.Enabled) == 0)
continue;
try
{
KeyboardController.Manager.RegisterKeyboard(new WinKeyboardDescription(profile, this));
}
catch (CultureNotFoundException)
{
// ignore if we can't find a culture (this can happen e.g. when a language gets
// removed that was previously assigned to a WS) - see LT-15333
}
}
}
}
private void GetInputMethodsThroughWinApi()
{
var countKeyboardLayouts = Win32.GetKeyboardLayoutList(0, IntPtr.Zero);
if (countKeyboardLayouts == 0)
return;
var keyboardLayouts = Marshal.AllocCoTaskMem(countKeyboardLayouts * IntPtr.Size);
try
{
Win32.GetKeyboardLayoutList(countKeyboardLayouts, keyboardLayouts);
var current = keyboardLayouts;
var elemSize = (ulong)IntPtr.Size;
for (int i = 0; i < countKeyboardLayouts; i++)
{
var hkl = (IntPtr)Marshal.ReadInt32(current);
KeyboardController.Manager.RegisterKeyboard(new WinKeyboardDescription(hkl, this));
current = (IntPtr)((ulong)current + elemSize);
}
}
finally
{
Marshal.FreeCoTaskMem(keyboardLayouts);
}
}
private void GetInputMethods()
{
if (ProfileMgr != null)
// Windows >= Vista
GetInputMethodsThroughTsf(Languages);
else
// Windows XP
GetInputMethodsThroughWinApi();
}
internal static LayoutName GetLayoutNameEx(IntPtr handle)
{
// InputLanguage.LayoutName is not to be trusted, especially where there are mutiple
// layouts (input methods) associated with a language. This function also provides
// the additional benefit that it does not matter whether a user switches from using
// InKey in Portable mode to using it in Installed mode (perhaps as the project is
// moved from one computer to another), as this function will identify the correct
// input language regardless, rather than (unhelpfully ) calling an InKey layout in
// portable mode the "US" layout. The layout is identified soley by the high-word of
// the HKL (a.k.a. InputLanguage.Handle). (The low word of the HKL identifies the
// language.)
// This function determines an HKL's LayoutName based on the following order of
// precedence:
// - Look up HKL in HKCU\\Software\\InKey\\SubstituteLayoutNames
// - Look up extended layout in HKLM\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts
// - Look up basic (non-extended) layout in HKLM\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts
// -Scan for ID of extended layout in HKLM\\SYSTEM\\CurrentControlSet\\Control\\Keyboard Layouts
var hkl = string.Format("{0:X8}", (int)handle);
// Get substitute first
var substituteHkl = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Keyboard Layout\Substitutes", hkl, null);
if (!string.IsNullOrEmpty(substituteHkl))
hkl = substituteHkl;
// Check InKey
var substituteLayoutName = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\InKey\SubstituteLayoutNames", hkl, null);
if (!string.IsNullOrEmpty(substituteLayoutName))
return new LayoutName(substituteLayoutName);
var layoutName = GetLayoutNameFromKey(string.Concat(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\", hkl));
if (layoutName != null)
return layoutName;
layoutName = GetLayoutNameFromKey(string.Concat(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\0000",
hkl.Substring(0, 4)));
if (layoutName != null)
return layoutName;
using (var regKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Keyboard Layouts"))
{
if (regKey == null)
return new LayoutName();
string layoutId = "0" + hkl.Substring(1, 3);
foreach (string subKeyName in regKey.GetSubKeyNames().Reverse())
// Scan in reverse order for efficiency, as the extended layouts are at the end.
{
using (var klid = regKey.OpenSubKey(subKeyName))
{
if (klid == null)
continue;
var layoutIdSk = ((string) klid.GetValue("Layout ID"));
if (layoutIdSk != null &&
layoutIdSk.Equals(layoutId, StringComparison.InvariantCultureIgnoreCase))
{
return GetLayoutNameFromKey(klid.Name);
}
}
}
}
return new LayoutName();
}
private static LayoutName GetLayoutNameFromKey(string key)
{
var layoutText = (string)Registry.GetValue(key, "Layout Text", null);
var displayName = (string)Registry.GetValue(key, "Layout Display Name", null);
if (string.IsNullOrEmpty(layoutText) && string.IsNullOrEmpty(displayName))
return null;
else if (string.IsNullOrEmpty(displayName))
return new LayoutName(layoutText);
else
{
var bldr = new StringBuilder(100);
Win32.SHLoadIndirectString(displayName, bldr, 100, IntPtr.Zero);
return string.IsNullOrEmpty(layoutText) ? new LayoutName(bldr.ToString()) :
new LayoutName(layoutText, bldr.ToString());
}
}
/// <summary>
/// Gets the InputLanguage that has the same layout as <paramref name="keyboardDescription"/>.
/// </summary>
internal static InputLanguage GetInputLanguage(IKeyboardDefinition keyboardDescription)
{
InputLanguage sameLayout = null;
InputLanguage sameCulture = null;
foreach (InputLanguage lang in InputLanguage.InstalledInputLanguages)
{
// TODO: write some tests
try
{
if (GetLayoutNameEx(lang.Handle).Name == keyboardDescription.Name)
{
if (keyboardDescription.Locale == lang.Culture.Name)
return lang;
if (sameLayout == null)
sameLayout = lang;
}
else if (keyboardDescription.Locale == lang.Culture.Name && sameCulture == null)
sameCulture = lang;
}
catch (CultureNotFoundException)
{
// we get an exception for non-supported cultures, probably because of a
// badly applied .NET patch.
// http://www.ironspeed.com/Designer/3.2.4/WebHelp/Part_VI/Culture_ID__XXX__is_not_a_supported_culture.htm and others
}
}
return sameLayout ?? sameCulture;
}
/// <summary>
/// Gets the keyboard description for the layout of <paramref name="inputLanguage"/>.
/// </summary>
private static KeyboardDescription GetKeyboardDescription(IInputLanguage inputLanguage)
{
KeyboardDescription sameLayout = null;
KeyboardDescription sameCulture = null;
// TODO: write some tests
var requestedLayout = GetLayoutNameEx(inputLanguage.Handle).Name;
foreach (KeyboardDescription keyboardDescription in Keyboard.Controller.AllAvailableKeyboards)
{
try
{
if (requestedLayout == keyboardDescription.Layout)
{
if (keyboardDescription.Locale == inputLanguage.Culture.Name)
return keyboardDescription;
if (sameLayout == null)
sameLayout = keyboardDescription;
}
else if (keyboardDescription.Locale == inputLanguage.Culture.Name && sameCulture == null)
sameCulture = keyboardDescription;
}
catch (CultureNotFoundException)
{
// we get an exception for non-supported cultures, probably because of a
// badly applied .NET patch.
// http://www.ironspeed.com/Designer/3.2.4/WebHelp/Part_VI/Culture_ID__XXX__is_not_a_supported_culture.htm and others
}
}
return sameLayout ?? sameCulture;
}
private void OnTimerTick(object sender, EventArgs eventArgs)
{
if (m_ExpectedKeyboard == null || !m_fSwitchedLanguages)
return;
if (InputLanguage.CurrentInputLanguage.Culture.KeyboardLayoutId == m_ExpectedKeyboard.InputLanguage.Culture.KeyboardLayoutId)
{
m_ExpectedKeyboard = null;
m_fSwitchedLanguages = false;
m_Timer.Enabled = false;
return;
}
SwitchKeyboard(m_ExpectedKeyboard);
}
private bool UseWindowsApiForKeyboardSwitching(WinKeyboardDescription winKeyboard)
{
return ProcessorProfiles == null ||
(ProfileMgr == null && winKeyboard.InputProcessorProfile.Hkl == IntPtr.Zero);
}
private void SwitchKeyboard(WinKeyboardDescription winKeyboard)
{
if (m_fSwitchingKeyboards)
return;
m_fSwitchingKeyboards = true;
try
{
((IKeyboardControllerImpl)Keyboard.Controller).ActiveKeyboard = ActivateKeyboard(winKeyboard);
if (Form.ActiveForm != null)
{
// If we activate a keyboard while a particular Form is active, we want to know about
// input language change calls for that form. The previous -= may help make sure we
// don't get multiple hookups.
Form.ActiveForm.InputLanguageChanged -= ActiveFormOnInputLanguageChanged;
Form.ActiveForm.InputLanguageChanged += ActiveFormOnInputLanguageChanged;
}
// If we have a TIP (TSF Input Processor) we don't have a handle. But we do the
// keyboard switching through TSF so we don't need the workaround below.
if (!UseWindowsApiForKeyboardSwitching(winKeyboard))
return;
m_ExpectedKeyboard = winKeyboard;
// The following lines help to work around a Windows bug (happens at least on
// XP-SP3): When you set the current input language (by any method), if there is more
// than one loaded input language associated with that same culture, Windows may
// initially go along with your request, and even respond to an immediate query of
// the current input language with the answer you expect. However, within a fraction
// of a second, it often takes the initiative to again change the input language to
// the _other_ input language having that same culture. We check that the proper
// input language gets set by enabling a timer so that we can re-set the input
// language if necessary.
m_fSwitchedLanguages = true;
// stop timer first so that the 0.5s interval restarts.
m_Timer.Stop();
m_Timer.Start();
}
finally
{
m_fSwitchingKeyboards = false;
}
}
private WinKeyboardDescription ActivateKeyboard(WinKeyboardDescription winKeyboard)
{
try
{
if (UseWindowsApiForKeyboardSwitching(winKeyboard))
{
// Win XP with regular keyboard, or TSF disabled
Win32.ActivateKeyboardLayout(new HandleRef(this, winKeyboard.InputLanguage.Handle), 0);
return winKeyboard;
}
var profile = winKeyboard.InputProcessorProfile;
if ((profile.Flags & TfIppFlags.Enabled) == 0)
return winKeyboard;
ProcessorProfiles.ChangeCurrentLanguage(profile.LangId);
if (ProfileMgr == null)
{
// Win XP with TIP (TSF Input Processor)
ProcessorProfiles.ActivateLanguageProfile(ref profile.ClsId, profile.LangId,
ref profile.GuidProfile);
}
else
{
// Windows >= Vista with either TIP or regular keyboard
ProfileMgr.ActivateProfile(profile.ProfileType, profile.LangId,
ref profile.ClsId, ref profile.GuidProfile, profile.Hkl,
TfIppMf.DontCareCurrentInputLanguage);
}
}
catch (ArgumentException)
{
// throws exception for non-supported culture, though seems to set it OK.
}
catch (COMException e)
{
var profile = winKeyboard.InputProcessorProfile;
var msg = string.Format("Got COM exception trying to activate IM:" + Environment.NewLine +
"LangId={0}, clsId={1}, hkl={2}, guidProfile={3}, flags={4}, type={5}, catId={6}",
profile.LangId, profile.ClsId, profile.Hkl, profile.GuidProfile, profile.Flags, profile.ProfileType, profile.CatId);
throw new ApplicationException(msg, e);
}
return winKeyboard;
}
/// <summary>
/// Save the state of the conversion and sentence mode for the current IME
/// so that we can restore it later.
/// </summary>
private void SaveImeConversionStatus(WinKeyboardDescription winKeyboard)
{
if (winKeyboard == null)
return;
var windowHandle = new HandleRef(this,
winKeyboard.WindowHandle != IntPtr.Zero ? winKeyboard.WindowHandle : Win32.GetFocus());
var contextPtr = Win32.ImmGetContext(windowHandle);
if (contextPtr == IntPtr.Zero)
return;
var contextHandle = new HandleRef(this, contextPtr);
int conversionMode;
int sentenceMode;
Win32.ImmGetConversionStatus(contextHandle, out conversionMode, out sentenceMode);
winKeyboard.ConversionMode = conversionMode;
winKeyboard.SentenceMode = sentenceMode;
Win32.ImmReleaseContext(windowHandle, contextHandle);
}
/// <summary>
/// Restore the conversion and sentence mode to the states they had last time
/// we activated this keyboard (unless we never activated this keyboard since the app
/// got started, in which case we use sensible default values).
/// </summary>
private void RestoreImeConversionStatus(KeyboardDescription keyboard)
{
var winKeyboard = keyboard as WinKeyboardDescription;
if (winKeyboard == null)
return;
// Restore the state of the new keyboard to the previous value. If we don't do
// that e.g. in Chinese IME the input mode will toggle between English and
// Chinese (LT-7487 et al).
var windowPtr = winKeyboard.WindowHandle != IntPtr.Zero ? winKeyboard.WindowHandle : Win32.GetFocus();
var windowHandle = new HandleRef(this, windowPtr);
// NOTE: Windows uses the same context for all windows of the current thread, so it
// doesn't really matter which window handle we pass.
var contextPtr = Win32.ImmGetContext(windowHandle);
if (contextPtr == IntPtr.Zero)
return;
// NOTE: Chinese Pinyin IME allows to switch between Chinese and Western punctuation.
// This can be selected in both Native and Alphanumeric conversion mode. However,
// when setting the value the punctuation setting doesn't get restored in Alphanumeric
// conversion mode, not matter what I try. I guess that is because Chinese punctuation
// doesn't really make sense with Latin characters.
var contextHandle = new HandleRef(this, contextPtr);
Win32.ImmSetConversionStatus(contextHandle, winKeyboard.ConversionMode, winKeyboard.SentenceMode);
Win32.ImmReleaseContext(windowHandle, contextHandle);
winKeyboard.WindowHandle = windowPtr;
}
private void ActiveFormOnInputLanguageChanged(object sender, InputLanguageChangedEventArgs inputLanguageChangedEventArgs)
{
RestoreImeConversionStatus(GetKeyboardDescription(inputLanguageChangedEventArgs.InputLanguage.Interface()));
}
#region IKeyboardAdaptor Members
[SuppressMessage("Gendarme.Rules.Correctness", "EnsureLocalDisposalRule",
Justification = "m_Timer gets disposed in Close() which gets called from KeyboardControllerImpl.Dispose")]
public void Initialize()
{
m_Timer = new Timer { Interval = 500 };
m_Timer.Tick += OnTimerTick;
GetInputMethods();
// Form.ActiveForm can be null when running unit tests
if (Form.ActiveForm != null)
Form.ActiveForm.InputLanguageChanged += ActiveFormOnInputLanguageChanged;
}
public void UpdateAvailableKeyboards()
{
GetInputMethods();
}
public void Close()
{
if (m_Timer != null)
{
m_Timer.Dispose();
m_Timer = null;
}
}
public List<IKeyboardErrorDescription> ErrorKeyboards
{
get { return m_BadLocales; }
}
public bool ActivateKeyboard(IKeyboardDefinition keyboard)
{
SwitchKeyboard(keyboard as WinKeyboardDescription);
return true;
}
public void DeactivateKeyboard(IKeyboardDefinition keyboard)
{
var winKeyboard = keyboard as WinKeyboardDescription;
Debug.Assert(winKeyboard != null);
SaveImeConversionStatus(winKeyboard);
}
public IKeyboardDefinition GetKeyboardForInputLanguage(IInputLanguage inputLanguage)
{
return GetKeyboardDescription(inputLanguage);
}
/// <summary>
/// Creates and returns a keyboard definition object based on the layout and locale.
/// Note that this method is used when we do NOT have a matching available keyboard.
/// Therefore we can presume that the created one is NOT available.
/// </summary>
public IKeyboardDefinition CreateKeyboardDefinition(string layout, string locale)
{
return new WinKeyboardDescription(locale, layout, this) {IsAvailable = false};
}
/// <summary>
/// Gets the default keyboard of the system.
/// </summary>
public IKeyboardDefinition DefaultKeyboard
{
get { return GetKeyboardDescription(InputLanguage.DefaultInputLanguage.Interface()); }
}
/// <summary>
/// The type of keyboards this adaptor handles: system or other (like Keyman, ibus...)
/// </summary>
public KeyboardType Type
{
get { return KeyboardType.System; }
}
#endregion
}
}
#endif
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
[CustomEditor(typeof(FracturedObject))]
public class FracturedObjectEditor : Editor
{
SerializedProperty PropSourceObject;
SerializedProperty PropGenerateIslands;
SerializedProperty PropGenerateChunkConnectionInfo;
SerializedProperty PropStartStatic;
SerializedProperty PropChunkConnectionMinArea;
SerializedProperty PropChunkConnectionStrength;
SerializedProperty PropChunkHorizontalRadiusSupportStrength;
SerializedProperty PropSupportChunksAreIndestructible;
SerializedProperty PropChunkIslandConnectionMaxDistance;
SerializedProperty PropTotalMass;
SerializedProperty PropChunkPhysicMaterial;
SerializedProperty PropMinColliderVolumeForBox;
SerializedProperty PropCapPrecisionFix;
SerializedProperty PropInvertCapNormals;
SerializedProperty PropFracturePattern;
SerializedProperty PropVoronoiVolumeOptimization;
SerializedProperty PropVoronoiProximityOptimization;
SerializedProperty PropVoronoiMultithreading;
SerializedProperty PropVoronoiCellsXCount;
SerializedProperty PropVoronoiCellsYCount;
SerializedProperty PropVoronoiCellsZCount;
SerializedProperty PropVoronoiCellsXSizeVariation;
SerializedProperty PropVoronoiCellsYSizeVariation;
SerializedProperty PropVoronoiCellsZSizeVariation;
SerializedProperty PropNumChunks;
SerializedProperty PropSplitsWorldSpace;
SerializedProperty PropSplitRegularly;
SerializedProperty PropSplitXProbability;
SerializedProperty PropSplitYProbability;
SerializedProperty PropSplitZProbability;
SerializedProperty PropSplitSizeVariation;
SerializedProperty PropSplitXVariation;
SerializedProperty PropSplitYVariation;
SerializedProperty PropSplitZVariation;
SerializedProperty PropSplitMaterial;
SerializedProperty PropSplitMappingTileU;
SerializedProperty PropSplitMappingTileV;
SerializedProperty PropEventDetachMinMass;
SerializedProperty PropEventDetachMinVelocity;
SerializedProperty PropEventDetachExitForce;
SerializedProperty PropEventDetachUpwardsModifier;
SerializedProperty PropEventDetachSound;
SerializedProperty PropEventDetachPrefabsArray;
SerializedProperty PropEventDetachCollisionCallMethod;
SerializedProperty PropEventDetachCollisionCallGameObject;
SerializedProperty PropEventDetachedMinLifeTime;
SerializedProperty PropEventDetachedMaxLifeTime;
SerializedProperty PropEventDetachedOffscreenLifeTime;
SerializedProperty PropEventDetachedMinMass;
SerializedProperty PropEventDetachedMinVelocity;
SerializedProperty PropEventDetachedMaxSounds;
SerializedProperty PropEventDetachedSoundArray;
SerializedProperty PropEventDetachedMaxPrefabs;
SerializedProperty PropEventDetachedPrefabsArray;
SerializedProperty PropEventDetachedCollisionCallMethod;
SerializedProperty PropEventDetachedCollisionCallGameObject;
SerializedProperty PropEventExplosionSound;
SerializedProperty PropEventExplosionPrefabInstanceCount;
SerializedProperty PropEventExplosionPrefabsArray;
SerializedProperty PropEventImpactSound;
SerializedProperty PropEventImpactPrefabsArray;
SerializedProperty PropEventDetachedAnyCallMethod;
SerializedProperty PropEventDetachedAnyCallGameObject;
SerializedProperty PropRandomSeed;
SerializedProperty PropDecomposePreview;
SerializedProperty PropAlwaysComputeColliders;
SerializedProperty PropShowChunkConnectionLines;
SerializedProperty PropShowChunkColoredState;
SerializedProperty PropShowChunkColoredRandomly;
SerializedProperty PropSaveMeshDataToAsset;
SerializedProperty PropMeshAssetDataFile;
SerializedProperty PropVerbose;
SerializedProperty PropIntegrateWithConcaveCollider;
SerializedProperty PropConcaveColliderAlgorithm;
SerializedProperty PropConcaveColliderMaxHulls;
SerializedProperty PropConcaveColliderMaxHullVertices;
SerializedProperty PropConcaveColliderLegacySteps;
bool m_bProgressCancelled;
[MenuItem("GameObject/Create Other/Ultimate Game Tools/Fractured Object")]
static void CreateFracturedObject()
{
GameObject fracturedObject = new GameObject();
fracturedObject.name = "Fractured Object";
fracturedObject.transform.position = Vector3.zero;
fracturedObject.AddComponent<FracturedObject>();
Selection.activeGameObject = fracturedObject;
}
void Progress(string strTitle, string strMessage, float fT)
{
if(EditorUtility.DisplayCancelableProgressBar(strTitle, strMessage, fT))
{
UltimateFracturing.Fracturer.CancelFracturing();
m_bProgressCancelled = true;
}
}
void OnEnable()
{
PropSourceObject = serializedObject.FindProperty("SourceObject");
PropGenerateIslands = serializedObject.FindProperty("GenerateIslands");
PropGenerateChunkConnectionInfo = serializedObject.FindProperty("GenerateChunkConnectionInfo");
PropStartStatic = serializedObject.FindProperty("StartStatic");
PropChunkConnectionMinArea = serializedObject.FindProperty("ChunkConnectionMinArea");
PropChunkConnectionStrength = serializedObject.FindProperty("ChunkConnectionStrength");
PropChunkHorizontalRadiusSupportStrength = serializedObject.FindProperty("ChunkHorizontalRadiusSupportStrength");
PropSupportChunksAreIndestructible = serializedObject.FindProperty("SupportChunksAreIndestructible");
PropChunkIslandConnectionMaxDistance = serializedObject.FindProperty("ChunkIslandConnectionMaxDistance");
PropTotalMass = serializedObject.FindProperty("TotalMass");
PropChunkPhysicMaterial = serializedObject.FindProperty("ChunkPhysicMaterial");
PropMinColliderVolumeForBox = serializedObject.FindProperty("MinColliderVolumeForBox");
PropCapPrecisionFix = serializedObject.FindProperty("CapPrecisionFix");
PropInvertCapNormals = serializedObject.FindProperty("InvertCapNormals");
PropFracturePattern = serializedObject.FindProperty("FracturePattern");
PropVoronoiVolumeOptimization = serializedObject.FindProperty("VoronoiVolumeOptimization");
PropVoronoiProximityOptimization = serializedObject.FindProperty("VoronoiProximityOptimization");
PropVoronoiMultithreading = serializedObject.FindProperty("VoronoiMultithreading");
PropVoronoiCellsXCount = serializedObject.FindProperty("VoronoiCellsXCount");
PropVoronoiCellsYCount = serializedObject.FindProperty("VoronoiCellsYCount");
PropVoronoiCellsZCount = serializedObject.FindProperty("VoronoiCellsZCount");
PropVoronoiCellsXSizeVariation = serializedObject.FindProperty("VoronoiCellsXSizeVariation");
PropVoronoiCellsYSizeVariation = serializedObject.FindProperty("VoronoiCellsYSizeVariation");
PropVoronoiCellsZSizeVariation = serializedObject.FindProperty("VoronoiCellsZSizeVariation");
PropNumChunks = serializedObject.FindProperty("GenerateNumChunks");
PropSplitsWorldSpace = serializedObject.FindProperty("SplitsWorldSpace");
PropSplitRegularly = serializedObject.FindProperty("SplitRegularly");
PropSplitXProbability = serializedObject.FindProperty("SplitXProbability");
PropSplitYProbability = serializedObject.FindProperty("SplitYProbability");
PropSplitZProbability = serializedObject.FindProperty("SplitZProbability");
PropSplitSizeVariation = serializedObject.FindProperty("SplitSizeVariation");
PropSplitXVariation = serializedObject.FindProperty("SplitXVariation");
PropSplitYVariation = serializedObject.FindProperty("SplitYVariation");
PropSplitZVariation = serializedObject.FindProperty("SplitZVariation");
PropSplitMaterial = serializedObject.FindProperty("SplitMaterial");
PropSplitMappingTileU = serializedObject.FindProperty("SplitMappingTileU");
PropSplitMappingTileV = serializedObject.FindProperty("SplitMappingTileV");
PropEventDetachMinMass = serializedObject.FindProperty("EventDetachMinMass");
PropEventDetachMinVelocity = serializedObject.FindProperty("EventDetachMinVelocity");
PropEventDetachExitForce = serializedObject.FindProperty("EventDetachExitForce");
PropEventDetachUpwardsModifier = serializedObject.FindProperty("EventDetachUpwardsModifier");
PropEventDetachSound = serializedObject.FindProperty("EventDetachSound");
PropEventDetachPrefabsArray = serializedObject.FindProperty("EventDetachPrefabsArray");
PropEventDetachCollisionCallMethod = serializedObject.FindProperty("EventDetachCollisionCallMethod");
PropEventDetachCollisionCallGameObject = serializedObject.FindProperty("EventDetachCollisionCallGameObject");
PropEventDetachedMinLifeTime = serializedObject.FindProperty("EventDetachedMinLifeTime");
PropEventDetachedMaxLifeTime = serializedObject.FindProperty("EventDetachedMaxLifeTime");
PropEventDetachedOffscreenLifeTime = serializedObject.FindProperty("EventDetachedOffscreenLifeTime");
PropEventDetachedMinMass = serializedObject.FindProperty("EventDetachedMinMass");
PropEventDetachedMinVelocity = serializedObject.FindProperty("EventDetachedMinVelocity");
PropEventDetachedMaxSounds = serializedObject.FindProperty("EventDetachedMaxSounds");
PropEventDetachedSoundArray = serializedObject.FindProperty("EventDetachedSoundArray");
PropEventDetachedMaxPrefabs = serializedObject.FindProperty("EventDetachedMaxPrefabs");
PropEventDetachedPrefabsArray = serializedObject.FindProperty("EventDetachedPrefabsArray");
PropEventDetachedCollisionCallMethod = serializedObject.FindProperty("EventDetachedCollisionCallMethod");
PropEventDetachedCollisionCallGameObject = serializedObject.FindProperty("EventDetachedCollisionCallGameObject");
PropEventExplosionSound = serializedObject.FindProperty("EventExplosionSound");
PropEventExplosionPrefabInstanceCount = serializedObject.FindProperty("EventExplosionPrefabsInstanceCount");
PropEventExplosionPrefabsArray = serializedObject.FindProperty("EventExplosionPrefabsArray");
PropEventImpactSound = serializedObject.FindProperty("EventImpactSound");
PropEventImpactPrefabsArray = serializedObject.FindProperty("EventImpactPrefabsArray");
PropEventDetachedAnyCallMethod = serializedObject.FindProperty("EventDetachedAnyCallMethod");
PropEventDetachedAnyCallGameObject = serializedObject.FindProperty("EventDetachedAnyCallGameObject");
PropRandomSeed = serializedObject.FindProperty("RandomSeed");
PropDecomposePreview = serializedObject.FindProperty("DecomposePreview");
PropShowChunkConnectionLines = serializedObject.FindProperty("ShowChunkConnectionLines");
PropShowChunkColoredState = serializedObject.FindProperty("ShowChunkColoredState");
PropShowChunkColoredRandomly = serializedObject.FindProperty("ShowChunkColoredRandomly");
PropSaveMeshDataToAsset = serializedObject.FindProperty("SaveMeshDataToAsset");
PropMeshAssetDataFile = serializedObject.FindProperty("MeshAssetDataFile");
PropAlwaysComputeColliders = serializedObject.FindProperty("AlwaysComputeColliders");
PropVerbose = serializedObject.FindProperty("Verbose");
PropIntegrateWithConcaveCollider = serializedObject.FindProperty("IntegrateWithConcaveCollider");
PropConcaveColliderAlgorithm = serializedObject.FindProperty("ConcaveColliderAlgorithm");
PropConcaveColliderMaxHulls = serializedObject.FindProperty("ConcaveColliderMaxHulls");
PropConcaveColliderMaxHullVertices = serializedObject.FindProperty("ConcaveColliderMaxHullVertices");
PropConcaveColliderLegacySteps = serializedObject.FindProperty("ConcaveColliderLegacySteps");
}
public void OnSceneGUI()
{
FracturedObject fracturedComponent = target as FracturedObject;
if(fracturedComponent == null)
{
return;
}
// Chunk connections
if(fracturedComponent.ShowChunkConnectionLines)
{
Color handlesColor = Handles.color;
Handles.color = new Color32(255, 0, 0, 255); //new Color32(155, 89, 182, 255);
foreach(FracturedChunk chunkA in fracturedComponent.ListFracturedChunks)
{
if(chunkA)
{
if(chunkA.ListAdjacentChunks.Count > 0)
{
Handles.DotCap(0, chunkA.transform.position, Quaternion.identity, HandleUtility.GetHandleSize(chunkA.transform.position) * 0.05f);
}
foreach(FracturedChunk.AdjacencyInfo chunkAdjacency in chunkA.ListAdjacentChunks)
{
if(chunkAdjacency.chunk)
{
Handles.DrawLine(chunkA.transform.position, chunkAdjacency.chunk.transform.position);
}
}
}
}
Handles.color = handlesColor;
}
// Support planes
bool bPlanesChanged = false;
if(fracturedComponent.ListSupportPlanes != null)
{
foreach(UltimateFracturing.SupportPlane supportPlane in fracturedComponent.ListSupportPlanes)
{
if(supportPlane.GUIShowInScene == false)
{
continue;
}
Vector3 v3WorldPosition = fracturedComponent.transform.TransformPoint(supportPlane.v3PlanePosition);
Quaternion qWorldRotation = fracturedComponent.transform.rotation * supportPlane.qPlaneRotation;
Vector3 v3WorldScale = Vector3.Scale(supportPlane.v3PlaneScale, fracturedComponent.transform.localScale);
Handles.Label(v3WorldPosition, supportPlane.GUIName);
// Normalize qWorldRotation
float fSum = 0;
for(int i = 0; i < 4; ++i) fSum += qWorldRotation[i] * qWorldRotation[i];
float fMagnitudeInverse = 1.0f / Mathf.Sqrt(fSum);
for(int i = 0; i < 4; ++i) qWorldRotation[i] *= fMagnitudeInverse;
Vector3 v3PlanePosition = supportPlane.v3PlanePosition;
Quaternion qPlaneRotation = supportPlane.qPlaneRotation;
Vector3 v3PlaneScale = supportPlane.v3PlaneScale;
// Use tools
switch(Tools.current)
{
case Tool.Move:
v3PlanePosition = fracturedComponent.transform.InverseTransformPoint(Handles.PositionHandle(v3WorldPosition, qWorldRotation));
break;
case Tool.Rotate:
qPlaneRotation = Quaternion.Inverse(fracturedComponent.transform.rotation) * Handles.RotationHandle(qWorldRotation, v3WorldPosition);
break;
case Tool.Scale:
v3PlaneScale = Vector3.Scale(Handles.ScaleHandle(v3WorldScale, v3WorldPosition, qWorldRotation, HandleUtility.GetHandleSize(v3WorldPosition)), new Vector3(1.0f / fracturedComponent.transform.localScale.x, 1.0f / fracturedComponent.transform.localScale.y, 1.0f / fracturedComponent.transform.localScale.z));
break;
}
if(GUI.changed)
{
EditorUtility.SetDirty(fracturedComponent);
bPlanesChanged = true;
switch(Tools.current)
{
case Tool.Move:
supportPlane.v3PlanePosition = v3PlanePosition;
break;
case Tool.Rotate:
supportPlane.qPlaneRotation = qPlaneRotation;
break;
case Tool.Scale:
supportPlane.v3PlaneScale = v3PlaneScale;
break;
}
}
}
}
if(bPlanesChanged)
{
fracturedComponent.ComputeSupportPlaneIntersections();
fracturedComponent.MarkNonSupportedChunks();
}
}
public override void OnInspectorGUI()
{
int nIndentationJump = 2;
Vector4 v4GUIColor = GUI.contentColor;
// Update the serializedProperty - always do this in the beginning of OnInspectorGUI.
serializedObject.Update();
FracturedObject fracturedComponent = serializedObject.targetObject as FracturedObject;
// Show the custom GUI controls
bool bDecomposePreviewUpdate = false;
bool bReassignSplitMaterial = false;
bool bComputeFracturing = false;
bool bComputeColliders = false;
bool bDeleteColliders = false;
bool bChunksDeleted = false;
bool bMarkNonSupportedChunks = false;
bool bRecomputePlanes = false;
EditorGUILayout.Space();
fracturedComponent.GUIExpandMain = EditorGUILayout.Foldout(fracturedComponent.GUIExpandMain, new GUIContent("Main", "Main fracturing parameters"));
if(fracturedComponent.GUIExpandMain)
{
GUI.contentColor = PropSourceObject.objectReferenceValue == null ? Color.red : GUI.contentColor;
PropSourceObject.objectReferenceValue = EditorGUILayout.ObjectField(new GUIContent("Source Object", "The object whose mesh will be used as input for the fracturing. It won't be deleted, just used as input."), PropSourceObject.objectReferenceValue, typeof(GameObject), true);
GUI.contentColor = v4GUIColor;
PropGenerateIslands.boolValue = EditorGUILayout.Toggle (new GUIContent("Island Generation", "Detect isolated meshes when splitting and make them separated chunks (f.e. if you split a U shape horizontally, it will give 3 objects with island generation (the bottom and the two tips separated), instead of 2 (the bottom on one hand and the two tips as the same object on the other)."), PropGenerateIslands.boolValue);
PropGenerateChunkConnectionInfo.boolValue = EditorGUILayout.Toggle (new GUIContent("Chunk Interconnection", "Will generate a connection graph between chunks to enable structural behavior."), PropGenerateChunkConnectionInfo.boolValue);
GUI.enabled = PropGenerateChunkConnectionInfo.boolValue;
PropStartStatic.boolValue = EditorGUILayout.Toggle (new GUIContent("Start Static", "If Chunk Interconnection is checked and no support planes or support chunks have been defined, an object would collapse on start. Check this if you want the object to stay static until first contact."), PropStartStatic.boolValue);
PropChunkConnectionMinArea.floatValue = EditorGUILayout.FloatField (new GUIContent("Interconnection Min Area", "Minimum area between 2 connected chunks to consider them connected. Setting it to zero won't consider all chunks connected, only those that share at least a common face area no matter how small."), PropChunkConnectionMinArea.floatValue);
PropChunkConnectionStrength.floatValue = EditorGUILayout.Slider (new GUIContent("Interconnection Strength", "When a chunk attached to the object is hit and detached, this controls how many connected chunks will detach too. 0.0 will make the whole object collapse, 1.0 won't detach any connected chunks."), PropChunkConnectionStrength.floatValue, 0.0f, 1.0f);
EditorGUI.BeginChangeCheck();
PropChunkHorizontalRadiusSupportStrength.floatValue = EditorGUILayout.FloatField (new GUIContent("Support Hor. Strength", "Controls the maximum horizontal distance a chunk must be from a support chunk to stay attached to the object. If its distance is greater than this value, it will fall."), PropChunkHorizontalRadiusSupportStrength.floatValue);
if(EditorGUI.EndChangeCheck())
{
bMarkNonSupportedChunks = true;
}
PropSupportChunksAreIndestructible.boolValue = EditorGUILayout.Toggle (new GUIContent("Support Is Indestructible", "If it is enabled, support chunks can not be destroyed/removed from the object."), PropSupportChunksAreIndestructible.boolValue);
GUI.enabled = PropGenerateChunkConnectionInfo.boolValue && PropGenerateIslands.boolValue;
PropChunkIslandConnectionMaxDistance.floatValue = EditorGUILayout.FloatField (new GUIContent("Island Max Connect Dist.", "When feeding a source object, and Island Generation is active, it may detect multiple closed meshes inside and some of them may be connected to others. This controls how far a face from one island can be from another island to consider the two islands connected."), PropChunkIslandConnectionMaxDistance.floatValue);
GUI.enabled = true;
EditorGUI.BeginChangeCheck();
PropTotalMass.floatValue = EditorGUILayout.FloatField (new GUIContent("Total Mass", "The total mass of the object. Each chunk mass will be computed depending on its size and this value."), PropTotalMass.floatValue);
if(EditorGUI.EndChangeCheck())
{
fracturedComponent.ComputeChunksMass(PropTotalMass.floatValue);
}
PropChunkPhysicMaterial.objectReferenceValue = EditorGUILayout.ObjectField(new GUIContent("Chunk Physic Material", "The physic material assigned to each chunk."), PropChunkPhysicMaterial.objectReferenceValue, typeof(PhysicMaterial), true);
PropMinColliderVolumeForBox.floatValue = EditorGUILayout.FloatField (new GUIContent("Min Collider Volume", "Chunks with a volume less than this value will have a box collider instead of a mesh collider to speed up collisions."), PropMinColliderVolumeForBox.floatValue);
PropCapPrecisionFix.floatValue = EditorGUILayout.FloatField (new GUIContent("Cap Precision Fix (Adv.)", "Change this value from 0 only if you experience weird triangles added to the mesh or unexpected crashes! This usually happens on meshes with very thin faces due to floating point errors. A good range is usually 0.001 to 0.02, larger values will introduce small visible variations on some splits. If there's only 2 or 3 problematic faces, then an alternative would be using another random seed."), PropCapPrecisionFix.floatValue);
PropInvertCapNormals.boolValue = EditorGUILayout.Toggle (new GUIContent("Reverse Cap Normals", "Check this if for some reason the interior faces have reversed lighting."), PropInvertCapNormals.boolValue);
}
EditorGUILayout.Space();
fracturedComponent.GUIExpandSplits = EditorGUILayout.Foldout(fracturedComponent.GUIExpandSplits, new GUIContent("Fracturing & Interior Material", "These parameters control the way the slicing will be performed."));
if(fracturedComponent.GUIExpandSplits)
{
bool bProbabilityXChanged = false;
bool bProbabilityYChanged = false;
bool bProbabilityZChanged = false;
float fProbabilityXBefore = PropSplitXProbability.floatValue;
float fProbabilityYBefore = PropSplitYProbability.floatValue;
float fProbabilityZBefore = PropSplitZProbability.floatValue;
EditorGUILayout.PropertyField(PropFracturePattern, new GUIContent("Fracture Method", "The fracture algorithm. Voronoi generates cellular, more natural looking chunks while BSP slices objects progressively using planes until the target number of chunks is reached. BSP is faster to compute and provides different control."));
if(PropFracturePattern.enumNames[PropFracturePattern.enumValueIndex] == FracturedObject.EFracturePattern.Voronoi.ToString())
{
EditorGUILayout.PropertyField(PropVoronoiVolumeOptimization, new GUIContent("Use Volume Optimization", "Will compute fracturing faster when using large meshes or with huge empty space."));
EditorGUILayout.PropertyField(PropVoronoiProximityOptimization, new GUIContent("Use Proximity Optimiza.", "Disable this if you find intersecting chunks."));
EditorGUILayout.PropertyField(PropVoronoiMultithreading, new GUIContent("Use Multithreading", "Will use multithreading for some Voronoi computation steps. It isn't fully tested/optimized but it should work. Only disable if you experience any problems."));
EditorGUILayout.PropertyField(PropVoronoiCellsXCount, new GUIContent("Cells In Local X", "Voronoi will generate X*Y*Z cells. This is number of cells to generate in the X dimension."));
EditorGUILayout.PropertyField(PropVoronoiCellsYCount, new GUIContent("Cells In Local Y", "Voronoi will generate X*Y*Z cells. This is number of cells to generate in the Y dimension."));
EditorGUILayout.PropertyField(PropVoronoiCellsZCount, new GUIContent("Cells In Local Z", "Voronoi will generate X*Y*Z cells. This is number of cells to generate in the Z dimension."));
PropVoronoiCellsXSizeVariation.floatValue = EditorGUILayout.Slider(new GUIContent("X Cells Variation", "Greater values will increase difference in size and positioning of cells in the X dimension"), PropVoronoiCellsXSizeVariation.floatValue, 0.0f, 1.0f);
PropVoronoiCellsYSizeVariation.floatValue = EditorGUILayout.Slider(new GUIContent("Y Cells Variation", "Greater values will increase difference in size and positioning of cells in the Y dimension"), PropVoronoiCellsYSizeVariation.floatValue, 0.0f, 1.0f);
PropVoronoiCellsZSizeVariation.floatValue = EditorGUILayout.Slider(new GUIContent("Z Cells Variation", "Greater values will increase difference in size and positioning of cells in the Z dimension"), PropVoronoiCellsZSizeVariation.floatValue, 0.0f, 1.0f);
}
if(PropFracturePattern.enumNames[PropFracturePattern.enumValueIndex] == FracturedObject.EFracturePattern.BSP.ToString())
{
PropNumChunks.intValue = EditorGUILayout.IntField(new GUIContent("Number Of Chunks", "The number of chunks to fracture the mesh into."), PropNumChunks.intValue);
PropSplitsWorldSpace.boolValue = EditorGUILayout.Toggle (new GUIContent("Slice In World Space", "Controls if the slicing will be performed in local object space or in world space. Note that the original object orientation is considered, not the fractured object."), PropSplitsWorldSpace.boolValue);
PropSplitRegularly.boolValue = EditorGUILayout.Toggle (new GUIContent("Slice Regularly", "If set, slices will always be performed to minimize the chunk size in all its axes, otherwise they will be performed randomly with the probabilities given."), PropSplitRegularly.boolValue);
GUI.enabled = PropSplitRegularly.boolValue == false;
EditorGUI.BeginChangeCheck();
PropSplitXProbability.floatValue = EditorGUILayout.Slider(new GUIContent("Slice X Probability", "Probability (0-1) that a slice is performed in X"), PropSplitXProbability.floatValue, 0.0f, 1.0f);
if(EditorGUI.EndChangeCheck()) bProbabilityXChanged = true;
EditorGUI.BeginChangeCheck();
PropSplitYProbability.floatValue = EditorGUILayout.Slider(new GUIContent("Slice Y Probability", "Probability (0-1) that a slice is performed in Y"), PropSplitYProbability.floatValue, 0.0f, 1.0f);
if(EditorGUI.EndChangeCheck()) bProbabilityYChanged = true;
EditorGUI.BeginChangeCheck();
PropSplitZProbability.floatValue = EditorGUILayout.Slider(new GUIContent("Slice Z Probability", "Probability (0-1) that a slice is performed in Z"), PropSplitZProbability.floatValue, 0.0f, 1.0f);
if(EditorGUI.EndChangeCheck()) bProbabilityZChanged = true;
GUI.enabled = true;
PropSplitSizeVariation.floatValue = EditorGUILayout.Slider(new GUIContent("Slice Size Variation", "0.0 will give chunks more equally sized. Increasing values will give chunks varying more in size."), PropSplitSizeVariation.floatValue, 0.0f, 1.0f);
PropSplitXVariation.floatValue = EditorGUILayout.Slider(new GUIContent("Slice X Variation", "Angular variation for the slices in the X plane."), PropSplitXVariation.floatValue, 0.0f, 1.0f);
PropSplitYVariation.floatValue = EditorGUILayout.Slider(new GUIContent("Slice Y Variation", "Angular variation for the slices in the Y plane."), PropSplitYVariation.floatValue, 0.0f, 1.0f);
PropSplitZVariation.floatValue = EditorGUILayout.Slider(new GUIContent("Slice Z Variation", "Angular variation for the slices in the Z plane."), PropSplitZVariation.floatValue, 0.0f, 1.0f);
}
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
PropSplitMaterial.objectReferenceValue = EditorGUILayout.ObjectField(new GUIContent("Interior Material", "Material applied to the interior faces of the chunks."), PropSplitMaterial.objectReferenceValue, typeof(Material), true);
if(EditorGUI.EndChangeCheck())
{
bReassignSplitMaterial = true;
}
PropSplitMappingTileU.floatValue = EditorGUILayout.FloatField (new GUIContent("Interior Mapping U Tile", "U Tiling of the interior faces mapping."), PropSplitMappingTileU.floatValue);
PropSplitMappingTileV.floatValue = EditorGUILayout.FloatField (new GUIContent("Interior Mapping V Tile", "V Tiling of the interior faces mapping."), PropSplitMappingTileV.floatValue);
float fNewSplitXProbability = PropSplitXProbability.floatValue;
float fNewSplitYProbability = PropSplitYProbability.floatValue;
float fNewSplitZProbability = PropSplitZProbability.floatValue;
if(bProbabilityXChanged) ChangeProbability(PropSplitXProbability.floatValue, fProbabilityXBefore, ref fNewSplitYProbability, ref fNewSplitZProbability);
if(bProbabilityYChanged) ChangeProbability(PropSplitYProbability.floatValue, fProbabilityYBefore, ref fNewSplitXProbability, ref fNewSplitZProbability);
if(bProbabilityZChanged) ChangeProbability(PropSplitZProbability.floatValue, fProbabilityZBefore, ref fNewSplitXProbability, ref fNewSplitYProbability);
PropSplitXProbability.floatValue = fNewSplitXProbability;
PropSplitYProbability.floatValue = fNewSplitYProbability;
PropSplitZProbability.floatValue = fNewSplitZProbability;
}
EditorGUILayout.Space();
fracturedComponent.GUIExpandEvents = EditorGUILayout.Foldout(fracturedComponent.GUIExpandEvents, new GUIContent("Events", "These parameters control the behavior of the object on some events."));
if(fracturedComponent.GUIExpandEvents)
{
EditorGUILayout.LabelField("Chunk Detach From Object Due To Physics Collision:");
EditorGUI.indentLevel += nIndentationJump;
EditorGUILayout.PropertyField(PropEventDetachMinMass, new GUIContent("Min Impact Mass", "The minimum mass an object needs to have to detach a chunk from this object on impact."));
EditorGUILayout.PropertyField(PropEventDetachMinVelocity, new GUIContent("Min Impact Velocity", "The minimum velocity an object needs to impact with to detach a chunk from this object."));
EditorGUILayout.PropertyField(PropEventDetachExitForce, new GUIContent("Exit Force", "If a chunk is detached due to an impact, it will have this value applied to it."));
EditorGUILayout.PropertyField(PropEventDetachUpwardsModifier, new GUIContent("Upwards Modifier", "Adds an upwards explosion effect to the chunks that have exit force. A value of 0.0 won't add any effect, while 2.0 means it will apply the force from a distance of 2 below the chunk."));
EditorGUILayout.PropertyField(PropEventDetachSound, new GUIContent("Detach Sound", "Will play this sound on the collision point when a chunk is detached due to an impact."));
EditorGUILayout.PropertyField(PropEventDetachPrefabsArray, new GUIContent("Instance Prefab List (1 Randomly Spawned On Detach)", "A list of prefabs. When a chunk is detached due to an impact, a random prefab will be picked from this list and instanced on the collision point. Use this for particles/explosions."), true);
EditorGUILayout.PropertyField(PropEventDetachCollisionCallMethod, new GUIContent("Call Method Name", "The method name that will be called on an impact-triggered detach chunk event."));
EditorGUILayout.PropertyField(PropEventDetachCollisionCallGameObject, new GUIContent("Call GameObject", "The GameObject whose method will be called."));
EditorGUI.indentLevel -= nIndentationJump;
EditorGUILayout.LabelField("Free (Detached) Chunks:");
EditorGUI.indentLevel += nIndentationJump;
EditorGUILayout.PropertyField(PropEventDetachedMinLifeTime, new GUIContent("Min Chunk LifeTime", "The minimum lifetime of a free chunk. When the life of a chunk expires it will be deleted."));
EditorGUILayout.PropertyField(PropEventDetachedMaxLifeTime, new GUIContent("Max Chunk LifeTime", "The maximum lifetime of a free chunk. When the life of a chunk expires it will be deleted."));
EditorGUILayout.PropertyField(PropEventDetachedOffscreenLifeTime, new GUIContent("Offscreen LifeTime", "If a free chunk is outside the visible screen for more than this seconds, it will be deleted."));
EditorGUILayout.PropertyField(PropEventDetachedMinMass, new GUIContent("Min Impact Mass", "The minimum mass a free chunk need to impact with in order to trigger a collision event."));
EditorGUILayout.PropertyField(PropEventDetachedMinVelocity, new GUIContent("Min Impact Velocity", "The minimum velocity a free chunk need to impact with in order to trigger a collision event."));
EditorGUILayout.PropertyField(PropEventDetachedMaxSounds, new GUIContent("Max Simult. Sounds", "The maximum collision sounds that will be played at the same time."));
EditorGUILayout.PropertyField(PropEventDetachedSoundArray, new GUIContent("Collision Sound List (1 Randomly Played On Collision)", "A list of sounds. On a free chunk collision a random sound will be picked from this list and played on the collision point."), true);
EditorGUILayout.PropertyField(PropEventDetachedMaxPrefabs, new GUIContent("Max Simult. Prefabs", "The maximum number of collision prefabs present at the same time."));
EditorGUILayout.PropertyField(PropEventDetachedPrefabsArray, new GUIContent("Collision Prefab List (1 Randomly Spawned On Collision)", "A list of prefabs. On a free chunk collision a random prefab will be picked from this list and instanced on the collision point. Use this for particles/explosions."), true);
EditorGUILayout.PropertyField(PropEventDetachedCollisionCallMethod, new GUIContent("Call Method Name", "The method name that will be called on a free chunk collision."));
EditorGUILayout.PropertyField(PropEventDetachedCollisionCallGameObject, new GUIContent("Call GameObject", "The GameObject whose method will be called."));
EditorGUI.indentLevel -= nIndentationJump;
EditorGUILayout.LabelField("When Explode() Is Called Through Scripting (Explosions):");
EditorGUI.indentLevel += nIndentationJump;
EditorGUILayout.PropertyField(PropEventExplosionSound, new GUIContent("Explosion Sound", "The sound that will be played when Explode() is called on this object."));
EditorGUILayout.PropertyField(PropEventExplosionPrefabInstanceCount, new GUIContent("Random Prefabs", "The number of prefabs to instance on random positions of the object."));
EditorGUILayout.PropertyField(PropEventExplosionPrefabsArray, new GUIContent("Instance Prefab List (Spawned Randomly Around)", "A list of prefabs. When Explode() is called a random number of them will be instanced on random positions of the object. Use this for particles/explosions."), true);
EditorGUI.indentLevel -= nIndentationJump;
EditorGUILayout.LabelField("When Impact() Is Called Through Scripting (f.e. Missiles):");
EditorGUI.indentLevel += nIndentationJump;
EditorGUILayout.PropertyField(PropEventImpactSound, new GUIContent("Impact Sound", "The sound that will be played when Impact() is called on this object."));
EditorGUILayout.PropertyField(PropEventImpactPrefabsArray, new GUIContent("Impact Prefab List (1 Randomly Spawned On Impact)", "A list of prefabs. When Impact() is called a random prefab will be instanced on the impact point. Use this for particles/explosions."), true);
EditorGUI.indentLevel -= nIndentationJump;
EditorGUILayout.LabelField("On Every Chunk Detach Event (Collision, Impact, Explosion, User scripted detach...):");
EditorGUI.indentLevel += nIndentationJump;
EditorGUILayout.PropertyField(PropEventDetachedAnyCallMethod, new GUIContent("Call Method Name", "The method name that will be called every time a chunk is detached for whatever reason."));
EditorGUILayout.PropertyField(PropEventDetachedAnyCallGameObject, new GUIContent("Call GameObject", "The GameObject whose method will be called."));
EditorGUI.indentLevel -= nIndentationJump;
}
EditorGUILayout.Space();
fracturedComponent.GUIExpandSupportPlanes = EditorGUILayout.Foldout(fracturedComponent.GUIExpandSupportPlanes, new GUIContent("Support Planes", "Support planes control which chunks are tagged as support. Chunks that act as support can't be destroyed and will hold the object together. A chunk needs to be connected to a support chunk (directly or through other chunks) or otherwise it will fall. This prevents chunks from staying static in the air and enables realistic collapsing behavior."));
if(fracturedComponent.GUIExpandSupportPlanes)
{
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
GUILayout.Label(" ");
if(GUILayout.Button(new GUIContent("Add Support Plane", "Adds a new support plane to this object. Support planes control which chunks are tagged as support. Chunks that act as support can't be destroyed and will hold the object together. A chunk needs to be connected to a support chunk (directly or through other chunks) or otherwise it will fall. This prevents chunks from staying static in the air and enables realistic collapsing behavior."), GUILayout.Width(200)))
{
fracturedComponent.AddSupportPlane();
fracturedComponent.ComputeSupportPlaneIntersections();
fracturedComponent.MarkNonSupportedChunks();
}
GUILayout.Label(" ");
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
int nDeletePlane = -1;
int nPlaneIndex = 0;
EditorGUI.indentLevel += nIndentationJump;
foreach(UltimateFracturing.SupportPlane supportPlane in fracturedComponent.ListSupportPlanes)
{
supportPlane.GUIExpanded = EditorGUILayout.Foldout(supportPlane.GUIExpanded, new GUIContent(supportPlane.GUIName, "Support plane parameters."));
if(supportPlane.GUIExpanded)
{
EditorGUI.indentLevel += nIndentationJump;
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
supportPlane.GUIShowInScene = EditorGUILayout.Toggle (new GUIContent("Show In Scene", "Controls if the plane is drawn or not in the scene view."), supportPlane.GUIShowInScene);
supportPlane.GUIName = EditorGUILayout.TextField (new GUIContent("Plane Name", "The name that will be shown on the scene view."), supportPlane.GUIName);
supportPlane.v3PlanePosition = EditorGUILayout.Vector3Field ("Local Position", supportPlane.v3PlanePosition);
supportPlane.qPlaneRotation = Quaternion.Euler(EditorGUILayout.Vector3Field("Local Rotation", supportPlane.qPlaneRotation.eulerAngles));
supportPlane.v3PlaneScale = EditorGUILayout.Vector3Field ("Local Scale", supportPlane.v3PlaneScale);
EditorGUILayout.BeginHorizontal();
GUILayout.Label(" ");
if(GUILayout.Button(new GUIContent("Delete", "Deletes this support plane."), GUILayout.Width(100)))
{
nDeletePlane = nPlaneIndex;
bRecomputePlanes = true;
}
GUILayout.Label(" ");
EditorGUILayout.EndHorizontal();
if(EditorGUI.EndChangeCheck())
{
bRecomputePlanes = true;
}
EditorGUI.indentLevel -= nIndentationJump;
}
nPlaneIndex++;
}
EditorGUI.indentLevel -= nIndentationJump;
if(nDeletePlane != -1)
{
fracturedComponent.ListSupportPlanes.RemoveAt(nDeletePlane);
}
}
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
PropRandomSeed.intValue = EditorGUILayout.IntField(new GUIContent("Random Seed", "Each seed will create a differently fractured object. Change the seed if you are not happy with the results."), PropRandomSeed.intValue);
if(GUILayout.Button(new GUIContent("New Seed"), GUILayout.Width(100)))
{
PropRandomSeed.intValue = Mathf.RoundToInt(Random.value * 1000000.0f);
}
EditorGUILayout.EndHorizontal();
EditorGUI.BeginChangeCheck();
PropDecomposePreview.floatValue = EditorGUILayout.Slider(new GUIContent("Preview Chunks", "Use this slider to preview the chunks that were generated."), PropDecomposePreview.floatValue, 0.0f, fracturedComponent.DecomposeRadius);
if(EditorGUI.EndChangeCheck())
{
bDecomposePreviewUpdate = true;
}
PropAlwaysComputeColliders.boolValue = EditorGUILayout.Toggle(new GUIContent("Always Gen. Colliders", "Will also generate colliders each time the chunks are computed."), PropAlwaysComputeColliders.boolValue);
PropShowChunkConnectionLines.boolValue = EditorGUILayout.Toggle(new GUIContent("Show Chunk Connections", "Will draw lines on the scene view to show how chunks are connected between each other."), PropShowChunkConnectionLines.boolValue);
PropShowChunkColoredState.boolValue = EditorGUILayout.Toggle(new GUIContent("Color Chunk State", "Will color chunks in the scene view to show which ones are support chunks and which ones aren't connected to any support chunks directly or indirectly and will fall down when checking for structure integrity."), PropShowChunkColoredState.boolValue);
PropShowChunkColoredRandomly.boolValue = EditorGUILayout.Toggle(new GUIContent("Color Chunks", "Will color chunks randomly in the scene window to see them better."), PropShowChunkColoredRandomly.boolValue);
EditorGUI.BeginChangeCheck();
PropSaveMeshDataToAsset.boolValue = EditorGUILayout.Toggle(new GUIContent("Enable Prefab Usage", "Will save the chunk and collider meshes to an asset file on disk when they are computed. Use this if you want to add this object to a prefab, otherwise the meshes and colliders won't be instanced properly."), PropSaveMeshDataToAsset.boolValue);
if(EditorGUI.EndChangeCheck())
{
if(PropSaveMeshDataToAsset.boolValue)
{
if(System.IO.File.Exists(fracturedComponent.MeshAssetDataFile) == false)
{
PropMeshAssetDataFile.stringValue = UnityEditor.EditorUtility.SaveFilePanelInProject("Save mesh asset", "mesh_" + fracturedComponent.name + this.GetInstanceID().ToString() + ".asset", "asset", "Please enter a file name to save the mesh asset to");
}
if(PropMeshAssetDataFile.stringValue.Length == 0)
{
PropSaveMeshDataToAsset.boolValue = false;
}
}
else
{
PropMeshAssetDataFile.stringValue = "";
}
}
PropVerbose.boolValue = EditorGUILayout.Toggle(new GUIContent("Output Console Info", "Outputs messages and warnings to the console window."), PropVerbose.boolValue);
// Fracture?
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
GUI.enabled = PropSourceObject.objectReferenceValue != null;
bComputeFracturing = GUILayout.Button(new GUIContent("Compute Chunks", "Computes the fractured chunks"));
GUI.enabled = true;
bool bHasChunks = fracturedComponent.ListFracturedChunks.Count > 0;
GUI.enabled = bHasChunks;
if(GUILayout.Button(new GUIContent("Delete Chunks", "Deletes the fractured chunks")))
{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo("Delete Chunks");
#endif
fracturedComponent.DeleteChunks();
bChunksDeleted = true;
}
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
PropIntegrateWithConcaveCollider.boolValue = EditorGUILayout.Toggle(new GUIContent("Use Concave Collider", "Use the external Concave Collider utility to have more control over how mesh colliders are generated."), PropIntegrateWithConcaveCollider.boolValue);
if(EditorGUI.EndChangeCheck())
{
if(PropIntegrateWithConcaveCollider.boolValue)
{
if(System.IO.File.Exists("Assets/Plugins/ConvexDecompositionDll.dll") == false && System.IO.File.Exists("Assets/Plugins/x86_64/ConvexDecompositionDll.dll"))
{
if(EditorUtility.DisplayDialog("Concave Collider not found", "Concave Collider is a utility for Unity that allows the automatic generation of compound colliders for dynamic objects.\n\nThe Ultimate Fracturing tool can use it to avoid generating hulls bigger than 255 triangles. It will also allow to specify the maximum number of vertices to generate for each collider to optimize collision calculations.\n\nNote: The Concave Collider requires a PRO license of Unity3D.", "Show Asset", "Cancel"))
{
Application.OpenURL("https://www.assetstore.unity3d.com/#/content/4596");
}
PropIntegrateWithConcaveCollider.boolValue = false;
}
}
}
GUI.enabled = PropIntegrateWithConcaveCollider.boolValue;
EditorGUILayout.PropertyField(PropConcaveColliderAlgorithm, new GUIContent("Algorithm", "The convex decomposition algorithm. Fast should be the best for 95% of the cases, use the other ones if fast does not work."));
// Uncomment for advanced control. The self-assignment is to avoid a compiler warning (warning CS0414: field assigned but value never used).
PropConcaveColliderMaxHulls.intValue = PropConcaveColliderMaxHulls.intValue;
// PropConcaveColliderMaxHulls.intValue = EditorGUILayout.IntSlider(new GUIContent("Max Colliders Per Chunk", "Limits the maximum collider hulls a chunk can have."), PropConcaveColliderMaxHulls.intValue, 1, 10);
if(PropConcaveColliderAlgorithm.enumNames[PropConcaveColliderAlgorithm.enumValueIndex] == FracturedObject.ECCAlgorithm.Fast.ToString() || PropConcaveColliderAlgorithm.enumNames[PropConcaveColliderAlgorithm.enumValueIndex] == FracturedObject.ECCAlgorithm.Normal.ToString())
{
PropConcaveColliderMaxHullVertices.intValue = EditorGUILayout.IntSlider(new GUIContent("Max Collider Vertices", "Limits the maximum vertices a collider hull can have."), PropConcaveColliderMaxHullVertices.intValue, 4, 1024);
}
if(PropConcaveColliderAlgorithm.enumNames[PropConcaveColliderAlgorithm.enumValueIndex] == FracturedObject.ECCAlgorithm.Legacy.ToString())
{
// Uncomment for advanced control. The self-assignment is to avoid a compiler warning (warning CS0414: field assigned but value never used).
PropConcaveColliderLegacySteps.intValue = PropConcaveColliderLegacySteps.intValue;
// EditorGUILayout.IntSlider(PropConcaveColliderLegacySteps, 1, 6, new GUIContent("Legacy Steps", "How many iterations to compute. More steps = more hulls and more computing time"));
}
GUI.enabled = true;
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
GUI.enabled = fracturedComponent.transform.childCount > 0;
if(GUILayout.Button(new GUIContent("Compute Colliders", "Computes the chunk colliders.")))
{
if(PropSaveMeshDataToAsset.boolValue == true)
{
EditorUtility.DisplayDialog("Chunks must be recomputed, sorry!", "If the parameter \"Enable Prefab Usage\" is checked, the colliders can only be recomputed through the \"Compute Chunks\" button with the \"Always Gen Colliders\" parameter enabled.", "OK");
}
else
{
bComputeColliders = true;
}
}
if(GUILayout.Button(new GUIContent("Delete Colliders", "Deletes the chunk colliders")))
{
bDeleteColliders = true;
}
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
// Apply changes to the serializedProperty
serializedObject.ApplyModifiedProperties();
// Perform actions
bool bProgressBarCreated = false;
m_bProgressCancelled = false;
if(bComputeFracturing)
{
bProgressBarCreated = true;
GameObject goSource = PropSourceObject.objectReferenceValue as GameObject;
if(goSource.GetComponent<MeshFilter>() == null)
{
EditorUtility.DisplayDialog("Error", "Source object has no mesh assigned", "OK");
}
else
{
bool bPositionOnSourceAndHideOriginal = false;
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo("Compute Chunks");
#endif
#if UNITY_3_5
bool bIsActive = goSource.active;
#else
bool bIsActive = goSource.activeSelf;
#endif
bool bIsAsset = AssetDatabase.Contains(goSource);
if(bIsActive && bHasChunks == false && bIsAsset == false)
{
if(EditorUtility.DisplayDialog("Hide old and position new?", "Do you want to hide the original object and place the new fractured object in its position?", "Yes", "No"))
{
bPositionOnSourceAndHideOriginal = true;
}
}
List<GameObject> listGameObjects;
bool bError = false;
float fStartTime = Time.realtimeSinceStartup;
try
{
UltimateFracturing.Fracturer.FractureToChunks(fracturedComponent, bPositionOnSourceAndHideOriginal, out listGameObjects, Progress);
}
catch(System.Exception e)
{
Debug.LogError(string.Format("Exception computing chunks ({0}):\n{1}", e.Message, e.StackTrace));
bError = true;
}
float fEndTime = Time.realtimeSinceStartup;
EditorUtility.ClearProgressBar();
if(bError == false && m_bProgressCancelled == false)
{
if(fracturedComponent.Verbose)
{
Debug.Log("Compute time = " + (fEndTime - fStartTime) + "seconds");
}
}
if(m_bProgressCancelled)
{
fracturedComponent.DeleteChunks();
}
}
}
if(bComputeColliders && m_bProgressCancelled == false)
{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo("Compute Colliders");
#endif
bProgressBarCreated = true;
UltimateFracturing.Fracturer.ComputeChunkColliders(fracturedComponent, Progress);
}
if(bDeleteColliders)
{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
Undo.RegisterSceneUndo("Delete Colliders");
#endif
UltimateFracturing.Fracturer.DeleteChunkColliders(fracturedComponent);
}
if((bDecomposePreviewUpdate || bComputeFracturing) && Application.isPlaying == false)
{
if(fracturedComponent.HasDetachedChunks() == false)
{
if(Mathf.Equals(PropDecomposePreview.floatValue, 0.0f))
{
fracturedComponent.SetSingleMeshVisibility(true);
}
else
{
fracturedComponent.SetSingleMeshVisibility(false);
}
}
}
foreach(FracturedChunk fracturedChunk in fracturedComponent.ListFracturedChunks)
{
if(fracturedChunk != null)
{
if(bDecomposePreviewUpdate || bComputeFracturing)
{
fracturedChunk.PreviewDecompositionValue = PropDecomposePreview.floatValue;
fracturedChunk.UpdatePreviewDecompositionPosition();
}
if(bReassignSplitMaterial)
{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2
Undo.RegisterUndo(fracturedChunk.renderer, "Assign Inside Material");
#else
Undo.RecordObject(fracturedChunk.GetComponent<Renderer>(), "Assign Inside Material");
#endif
if(fracturedChunk.SplitSubMeshIndex != -1)
{
Material[] aMaterials = new Material[fracturedChunk.GetComponent<Renderer>().sharedMaterials.Length];
for(int nMaterial = 0; nMaterial < aMaterials.Length; nMaterial++)
{
aMaterials[nMaterial] = nMaterial == fracturedChunk.SplitSubMeshIndex ? PropSplitMaterial.objectReferenceValue as Material : fracturedChunk.GetComponent<Renderer>().sharedMaterials[nMaterial];
}
fracturedChunk.GetComponent<Renderer>().sharedMaterials = aMaterials;
}
}
}
}
if(bRecomputePlanes)
{
SceneView.RepaintAll();
fracturedComponent.ComputeSupportPlaneIntersections();
}
if(bMarkNonSupportedChunks || bComputeFracturing || bRecomputePlanes)
{
fracturedComponent.MarkNonSupportedChunks();
}
if(fracturedComponent.SaveMeshDataToAsset && (bComputeFracturing || bComputeColliders) && (m_bProgressCancelled == false))
{
bProgressBarCreated = true;
if(fracturedComponent.MeshAssetDataFile.Length > 0)
{
bool bFirstAdded = false;
AssetDatabase.DeleteAsset(fracturedComponent.MeshAssetDataFile);
// Save chunks
for(int nChunk = 0; nChunk < fracturedComponent.ListFracturedChunks.Count && m_bProgressCancelled == false; nChunk++)
{
FracturedChunk chunk = fracturedComponent.ListFracturedChunks[nChunk];
Progress("Saving mesh assets to disk", string.Format("Chunk {0}/{1}", nChunk + 1, fracturedComponent.ListFracturedChunks.Count), (float)nChunk / (float)fracturedComponent.ListFracturedChunks.Count);
MeshFilter meshFilter = chunk.GetComponent<MeshFilter>();
// Save mesh
if(bFirstAdded == false && meshFilter != null)
{
UnityEditor.AssetDatabase.CreateAsset(meshFilter.sharedMesh, fracturedComponent.MeshAssetDataFile);
bFirstAdded = true;
}
else if(meshFilter != null)
{
UnityEditor.AssetDatabase.AddObjectToAsset(meshFilter.sharedMesh, fracturedComponent.MeshAssetDataFile);
UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(meshFilter.sharedMesh));
}
// Save collider mesh if it was generated by the concave collider
if(chunk.HasConcaveCollider)
{
MeshCollider meshCollider = chunk.GetComponent<MeshCollider>();
if(bFirstAdded == false && meshCollider != null)
{
UnityEditor.AssetDatabase.CreateAsset(meshCollider.sharedMesh, fracturedComponent.MeshAssetDataFile);
bFirstAdded = true;
}
else if(meshCollider != null)
{
UnityEditor.AssetDatabase.AddObjectToAsset(meshCollider.sharedMesh, fracturedComponent.MeshAssetDataFile);
UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(meshCollider.sharedMesh));
}
}
}
// Save planes
for(int nPlane = 0; nPlane < fracturedComponent.ListSupportPlanes.Count && m_bProgressCancelled == false; nPlane++)
{
UltimateFracturing.SupportPlane supportPlane = fracturedComponent.ListSupportPlanes[nPlane];
Progress("Saving support plane mesh assets to disk", string.Format("Plane {0}/{1}", nPlane + 1, fracturedComponent.ListSupportPlanes.Count), (float)nPlane / (float)fracturedComponent.ListSupportPlanes.Count);
// Save mesh
if(bFirstAdded == false && supportPlane.planeMesh != null)
{
UnityEditor.AssetDatabase.CreateAsset(supportPlane.planeMesh, fracturedComponent.MeshAssetDataFile);
bFirstAdded = true;
}
else if(supportPlane.planeMesh != null)
{
UnityEditor.AssetDatabase.AddObjectToAsset(supportPlane.planeMesh, fracturedComponent.MeshAssetDataFile);
UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(supportPlane.planeMesh));
}
}
// Save single draw object
MeshFilter meshFilterSingle = null;
if(fracturedComponent.SingleMeshObject)
{
meshFilterSingle = fracturedComponent.SingleMeshObject.GetComponent<MeshFilter>();
}
if(meshFilterSingle)
{
Progress("Saving single draw object mesh asset to disk", "Mesh", 1.0f);
if(bFirstAdded == false && meshFilterSingle.sharedMesh != null)
{
UnityEditor.AssetDatabase.CreateAsset(meshFilterSingle.sharedMesh, fracturedComponent.MeshAssetDataFile);
bFirstAdded = true;
}
else if(meshFilterSingle.sharedMesh != null)
{
UnityEditor.AssetDatabase.AddObjectToAsset(meshFilterSingle.sharedMesh, fracturedComponent.MeshAssetDataFile);
UnityEditor.AssetDatabase.ImportAsset(UnityEditor.AssetDatabase.GetAssetPath(meshFilterSingle.sharedMesh));
}
}
UnityEditor.AssetDatabase.Refresh();
}
}
if(bProgressBarCreated)
{
EditorUtility.ClearProgressBar();
}
if(bComputeColliders || bComputeFracturing || bDeleteColliders || bChunksDeleted)
{
Resources.UnloadUnusedAssets();
}
}
void ChangeProbability(float fNewValue, float fOldValue, ref float fOtherValue1Ref, ref float fOtherValue2Ref)
{
float fChange = fNewValue - fOldValue;
if(Mathf.Approximately(fOtherValue1Ref, 0.0f) && Mathf.Approximately(fOtherValue2Ref, 0.0f) == false)
{
fOtherValue1Ref = 0.0f;
fOtherValue2Ref = 1.0f - fNewValue;
}
else if(Mathf.Approximately(fOtherValue2Ref, 0.0f) && Mathf.Approximately(fOtherValue1Ref, 0.0f) == false)
{
fOtherValue1Ref = 1.0f - fNewValue;
fOtherValue2Ref = 0.0f;
}
else
{
fOtherValue1Ref = Mathf.Clamp01(fOtherValue1Ref - (fChange * 0.5f));
fOtherValue2Ref = 1.0f - (fNewValue + fOtherValue1Ref);
}
}
}
| |
// MIT License
//
// Copyright(c) 2022 ICARUS Consulting GmbH
//
// 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 Yaapii.Atoms.Fail;
using Yaapii.Atoms.Func;
using Yaapii.Atoms.Scalar;
using Yaapii.Atoms.Text;
namespace Yaapii.Atoms.Enumerable
{
/// <summary>
/// Element from position in a <see cref="IEnumerable{T}"/>.
/// </summary>
/// <typeparam name="T">type of element</typeparam>
public sealed class ItemAt<T> : ScalarEnvelope<T>
{
/// <summary>
/// First element in a <see cref="IEnumerable{T}"/> with given Exception thrwon on fallback
/// </summary>
/// <param name="source"></param>
/// <param name="ex"></param>
public ItemAt(IEnumerable<T> source, Exception ex) : this(
source,
0,
ex
)
{ }
/// <summary>
/// Element at position in <see cref="IEnumerable{T}"/> with given Exception thrown on fallback
/// </summary>
/// <param name="source"></param>
/// <param name="position"></param>
/// <param name="ex"></param>
public ItemAt(IEnumerable<T> source, int position, Exception ex) : this(
source,
position,
new FuncOf<IEnumerable<T>, T>(itr =>
throw ex
)
)
{ }
/// <summary>
/// First element in a <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="source">source enum</param>
public ItemAt(IEnumerable<T> source) : this(
source,
new BiFuncOf<Exception, IEnumerable<T>, T>((ex, itr) =>
throw new NoSuchElementException(
new Formatted("Cannot get first element: {0}", ex.Message).AsString()
)
)
)
{ }
/// <summary>
/// First element in a <see cref="IEnumerable{T}"/> with a fallback value.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="fallback">fallback func</param>
public ItemAt(IEnumerable<T> source, T fallback) : this(
source,
new FuncOf<IEnumerable<T>, T>(b => fallback)
)
{ }
/// <summary>
/// Element at a position in a <see cref="IEnumerable{T}"/> with a fallback value.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="position">position</param>
/// <param name="fallback">fallback func</param>
public ItemAt(IEnumerable<T> source, int position, T fallback) : this(
source,
position,
new FuncOf<IEnumerable<T>, T>(b => fallback)
)
{ }
/// <summary>
/// First element in a <see cref="IEnumerable{T}"/> with a fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">soruce enum</param>
/// <param name="fallback">fallback value</param>
public ItemAt(IEnumerable<T> source, IBiFunc<Exception, IEnumerable<T>, T> fallback) : this(
source,
0,
fallback
)
{ }
/// <summary>
/// First element in a <see cref="IEnumerable{T}"/> with a fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">soruce enum</param>
/// <param name="fallback">fallback value</param>
public ItemAt(IEnumerable<T> source, Func<IEnumerable<T>, T> fallback) : this(
source,
0,
new FuncOf<IEnumerable<T>, T>(fallback)
)
{ }
/// <summary>
/// First element in a <see cref="IEnumerable{T}"/> with a fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">soruce enum</param>
/// <param name="fallback">fallback value</param>
public ItemAt(IEnumerable<T> source, IFunc<IEnumerable<T>, T> fallback) : this(
source,
0,
fallback
)
{ }
/// <summary>
/// Element from position in a <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="position">position of item</param>
public ItemAt(IEnumerable<T> source, int position) : this(
source,
position,
new BiFuncOf<Exception, IEnumerable<T>, T>((ex, itr) =>
{
throw
new NoSuchElementException(
new Formatted(
"Cannot get element at position {0}: {1}",
position,
ex.Message
).AsString()
);
}
)
)
{ }
/// <summary>
/// Element from position in a <see cref="IEnumerable{T}"/> fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="position">position of item</param>
/// <param name="fallback">fallback func</param>
public ItemAt(IEnumerable<T> source, int position, IFunc<IEnumerable<T>, T> fallback) : this(
source,
position,
(ex, enumerable) => fallback.Invoke(enumerable)
)
{ }
/// <summary>
/// Element from position in a <see cref="IEnumerable{T}"/> fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="position">position of item</param>
/// <param name="fallback">fallback func</param>
public ItemAt(IEnumerable<T> source, int position, Func<IEnumerable<T>, T> fallback) : this(
source,
position,
new BiFuncOf<Exception, IEnumerable<T>, T>((ex, enumerable) =>
fallback.Invoke(enumerable)
)
)
{ }
/// <summary>
/// Element from position in a <see cref="IEnumerable{T}"/> fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="position">position of item</param>
/// <param name="fallback">fallback func</param>
public ItemAt(IEnumerable<T> source, int position, Func<Exception, IEnumerable<T>, T> fallback) : this(
source,
position,
new BiFuncOf<Exception, IEnumerable<T>, T>((ex, enumerable) =>
fallback.Invoke(ex, enumerable)
)
)
{ }
/// <summary>
/// Element from position in a <see cref="IEnumerable{T}"/> fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="position">position of item</param>
/// <param name="fallback">fallback func</param>
public ItemAt(IEnumerable<T> source, int position, IBiFunc<Exception, IEnumerable<T>, T> fallback) : base(() =>
new Enumerator.ItemAt<T>(
source.GetEnumerator(),
position,
fallback
).Value()
)
{ }
}
public sealed class ItemAt
{
/// <summary>
/// First element in a <see cref="IEnumerable{T}"/> with given Exception thrwon on fallback
/// </summary>
/// <param name="source"></param>
/// <param name="ex"></param>
public static IScalar<T> New<T>(IEnumerable<T> source, Exception ex)
=> new ItemAt<T>(source, ex);
/// <summary>
/// Element at position in <see cref="IEnumerable{T}"/> with given Exception thrown on fallback
/// </summary>
/// <param name="source"></param>
/// <param name="position"></param>
/// <param name="ex"></param>
public static IScalar<T> New<T>(IEnumerable<T> source, int position, Exception ex)
=> new ItemAt<T>(source, position, ex);
/// <summary>
/// First element in a <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="source">source enum</param>
public static IScalar<T> New<T>(IEnumerable<T> source)
=> new ItemAt<T>(source);
/// <summary>
/// First element in a <see cref="IEnumerable{T}"/> with a fallback value.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="fallback">fallback func</param>
public static IScalar<T> New<T>(IEnumerable<T> source, T fallback)
=> new ItemAt<T>(source, fallback);
/// <summary>
/// Element at a position in a <see cref="IEnumerable{T}"/> with a fallback value.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="position">position</param>
/// <param name="fallback">fallback func</param>
public static IScalar<T> New<T>(IEnumerable<T> source, int position, T fallback)
=> new ItemAt<T>(source, position, fallback);
/// <summary>
/// First element in a <see cref="IEnumerable{T}"/> with a fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">soruce enum</param>
/// <param name="fallback">fallback value</param>
public static IScalar<T> New<T>(IEnumerable<T> source, IBiFunc<Exception, IEnumerable<T>, T> fallback)
=> new ItemAt<T>(source, fallback);
/// <summary>
/// First element in a <see cref="IEnumerable{T}"/> with a fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">soruce enum</param>
/// <param name="fallback">fallback value</param>
public static IScalar<T> New<T>(IEnumerable<T> source, Func<IEnumerable<T>, T> fallback)
=> new ItemAt<T>(source, fallback);
/// <summary>
/// First element in a <see cref="IEnumerable{T}"/> with a fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">soruce enum</param>
/// <param name="fallback">fallback value</param>
public static IScalar<T> New<T>(IEnumerable<T> source, IFunc<IEnumerable<T>, T> fallback)
=> new ItemAt<T>(source, fallback);
/// <summary>
/// Element from position in a <see cref="IEnumerable{T}"/>.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="position">position of item</param>
public static IScalar<T> New<T>(IEnumerable<T> source, int position)
=> new ItemAt<T>(source, position);
/// <summary>
/// Element from position in a <see cref="IEnumerable{T}"/> fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="position">position of item</param>
/// <param name="fallback">fallback func</param>
public static IScalar<T> New<T>(IEnumerable<T> source, int position, IFunc<IEnumerable<T>, T> fallback)
=> new ItemAt<T>(source, position, fallback);
/// <summary>
/// Element from position in a <see cref="IEnumerable{T}"/> fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="position">position of item</param>
/// <param name="fallback">fallback func</param>
public static IScalar<T> New<T>(IEnumerable<T> source, int position, Func<IEnumerable<T>, T> fallback)
=> new ItemAt<T>(source, position, fallback);
/// <summary>
/// Element from position in a <see cref="IEnumerable{T}"/> fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="position">position of item</param>
/// <param name="fallback">fallback func</param>
public static IScalar<T> New<T>(IEnumerable<T> source, int position, Func<Exception, IEnumerable<T>, T> fallback)
=> new ItemAt<T>(source, position, fallback);
/// <summary>
/// Element from position in a <see cref="IEnumerable{T}"/> fallback function <see cref="IFunc{In, Out}"/>.
/// </summary>
/// <param name="source">source enum</param>
/// <param name="position">position of item</param>
/// <param name="fallback">fallback func</param>
public static IScalar<T> New<T>(IEnumerable<T> source, int position, IBiFunc<Exception, IEnumerable<T>, T> fallback)
=> new ItemAt<T>(source, position, fallback);
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Drawing;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Graphics;
using Axiom.Utility;
namespace Axiom.Core {
/// <summary>
/// Allows the rendering of a chain of connected billboards.
/// </summary>
/// <remarks>
/// A billboard chain operates much like a traditional billboard, ie its
/// segments always face the camera; the difference being that instead of
/// a set of disconnected quads, the elements in this class are connected
/// together in a chain which must always stay in a continuous strip. This
/// kind of effect is useful for creating effects such as trails, beams,
/// lightning effects, etc.
/// <p/>
/// A single instance of this class can actually render multiple separate
/// chain segments in a single render operation, provided they all use the
/// same material. To clarify the terminology: a 'segment' is a separate
/// sub-part of the chain with its own start and end (called the 'head'
/// and the 'tail'. An 'element' is a single position / color / texcoord
/// entry in a segment. You can add items to the head of a chain, and
/// remove them from the tail, very efficiently. Each segment has a max
/// size, and if adding an element to the segment would exceed this size,
/// the tail element is automatically removed and re-used as the new item
/// on the head.
/// <p/>
/// This class has no auto-updating features to do things like alter the
/// color of the elements or to automatically add / remove elements over
/// time - you have to do all this yourself as a user of the class.
/// Subclasses can however be used to provide this kind of behaviour
/// automatically. @see RibbonTrail
/// </remarks>
public class BillboardChain : MovableObject, IRenderable {
#region Member variables
// Create a logger for use in this class
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(BillboardChain));
protected List<Element> elementList;
/// <summary>
/// Maximum length of each chain
/// </summary>
protected int maxElementsPerChain = 20;
/// <summary>
/// Number of chains
/// </summary>
protected int numberOfChains = 1;
/// <summary>
/// Use texture coords?
/// </summary>
protected bool useTextureCoords = true;
/// <summary>
/// Use vertex color?
/// </summary>
protected bool useVertexColors = true;
/// <summary>
/// Dynamic use?
/// </summary>
protected bool dynamic = true;
/// <summary>
/// Vertex data
/// </summary>
protected VertexData vertexData;
/// <summary>
/// Index data (to allow multiple unconnected chains)
/// </summary>
protected IndexData indexData;
/// <summary>
/// Is the vertex declaration dirty?
/// </summary>
protected bool vertexDeclDirty;
/// <summary>
/// Do the buffers need recreating?
/// </summary>
protected bool buffersNeedRecreating;
/// <summary>
/// Do the bounds need redefining?
/// </summary>
protected bool boundsDirty;
/// <summary>
/// Is the index buffer dirty?
/// </summary>
protected bool indexContentDirty;
/// <summary>
/// AABB
/// </summary>
protected AxisAlignedBox abb = new AxisAlignedBox();
/// <summary>
/// Bounding radius
/// </summary>
protected float boundingRadius;
/// <summary>
/// Material
/// </summary>
string materialName;
/// <summary>
protected Material material;
/// </summary>
/// Texture coord direction
/// <summary>
TextureCoordDirection texCoordDirection;
/// </summary>
/// Other texture coord range
/// <summary>
protected float[] otherTexCoordRange;
/// </summary>
/// </summary>
/// The list holding the chain elements
/// <summary>
protected List<Element> chainElementList;
/// </summary>
/// A list of chain segments
/// <summary>
protected List<ChainSegment> chainSegmentList;
protected Dictionary<int, object> customParams = new Dictionary<int, object>();
#endregion Member variables
/// <summary>
/// Simple struct defining a chain segment by referencing a subset of
/// the preallocated buffer (which will be maxElementsPerChain * numberOfChains
/// long), by it's chain index, and a head and tail value which describe
/// the current chain. The buffer subset wraps at mMaxElementsPerChain
/// so that head and tail can move freely. head and tail are inclusive,
/// when the chain is empty head and tail are filled with high-values.
/// </summary>
public class ChainSegment {
/// The start of this chains subset of the buffer
public int start;
/// The 'head' of the chain, relative to start
public int head;
/// The 'tail' of the chain, relative to start
public int tail;
}
public const int SEGMENT_EMPTY = -1;
public class Element {
public Element()
{}
public Element(Vector3 position, float width, float textureCoord, ColorEx color) {
this.position = position;
this.width = width;
this.textureCoord = textureCoord;
this.color = color;
}
public Vector3 position;
public float width;
/// U or V texture coord depending on options
public float textureCoord;
public ColorEx color;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name"> The name to give this object</param>
/// <param name="maxElements"> The maximum number of elements per chain</param>
/// <param name="numberOfChains"> The number of separate chain segments contained in this object</param>
/// <param name="useTextureCoords"> If true, use texture coordinates from the chain elements</param>
/// <param name="useVertexColors"> If true, use vertex colors from the chain elements</param>
/// <param name="dynamic"> If true, buffers are created with the intention of being updated</param>
public BillboardChain(string name, int maxElementsPerChain, int numberOfChains,
bool useTextureCoords, bool useVertexColors, bool dynamic) : base(name) {
this.maxElementsPerChain = maxElementsPerChain;
this.numberOfChains = numberOfChains;
this.useTextureCoords = useTextureCoords;
this.useVertexColors = useVertexColors;
this.dynamic = dynamic;
this.texCoordDirection = TextureCoordDirection.U;
Initialize();
}
/// <summary>
/// Constructor
/// <param name="name"> The name to give this object</param>
/// <param name="parameters"> A varargs array of key/value pairs</param>
/// </summary>
public BillboardChain(string name, params Object[] parameters) : base(name) {
for (int i=0; i<parameters.Length; i+=2) {
string key = (string) parameters[i];
Object value = parameters[i + 1];
if (key == "maxElementsPerChain")
maxElementsPerChain = (int)value;
else if (key == "numberOfChains")
numberOfChains = (int)value;
else if (key == "useTextureCoords")
useTextureCoords = (bool)value;
else if (key == "useVertexColors")
useVertexColors = (bool)value;
else if (key == "dynamic")
dynamic = (bool)value;
else
log.Error("BillboardChain constructor: unrecognized parameter '" + key + "'");
}
Initialize();
}
protected void Initialize() {
this.vertexDeclDirty = true;
this.buffersNeedRecreating = true;
this.boundsDirty = true;
this.indexContentDirty = true;
this.boundingRadius = 0.0f;
vertexData = new VertexData();
indexData = new IndexData();
otherTexCoordRange = new float[2];
otherTexCoordRange[0] = 0.0f;
otherTexCoordRange[1] = 1.0f;
SetupChainContainers();
vertexData.vertexStart = 0;
// index data set up later
// set basic white material
this.materialName = "BaseWhiteNoLighting";
}
// Currently unreferenced
public void DisposeBuffers() {
if (vertexData != null)
vertexData = null;
if (indexData != null)
indexData = null;
}
protected void SetupChainContainers() {
// Allocate enough space for everything
int elements = numberOfChains * maxElementsPerChain;
chainElementList = new List<Element>();
for (int i=0; i<elements; i++)
chainElementList.Add(new Element());
vertexData.vertexCount = elements * 2;
// Configure chains
chainSegmentList = new List<ChainSegment>();
for (int i=0; i<numberOfChains; i++) {
ChainSegment seg = new ChainSegment();
seg.start = i * maxElementsPerChain;
seg.tail = seg.head = SEGMENT_EMPTY;
chainSegmentList.Add(seg);
}
}
protected void SetupVertexDeclaration() {
if (vertexDeclDirty) {
VertexDeclaration decl = vertexData.vertexDeclaration;
int offset = 0;
// Add a description for the buffer of the positions of the vertices
decl.AddElement(0, offset, VertexElementType.Float3, VertexElementSemantic.Position);
offset += VertexElement.GetTypeSize(VertexElementType.Float3);
if (useVertexColors) {
decl.AddElement(0, offset, VertexElementType.Color, VertexElementSemantic.Diffuse);
offset += VertexElement.GetTypeSize(VertexElementType.Color);
}
if (useTextureCoords) {
decl.AddElement(0, offset, VertexElementType.Float2, VertexElementSemantic.TexCoords);
offset += VertexElement.GetTypeSize(VertexElementType.Float2);
}
if (!useTextureCoords && !useVertexColors) {
log.Error(
"Error - BillboardChain '" + name + "' is using neither " +
"texture coordinates or vertex colors; it will not be " +
"visible on some rendering APIs so you should change this " +
"so you use one or the other.");
}
vertexDeclDirty = false;
}
}
protected void SetupBuffers() {
SetupVertexDeclaration();
if (buffersNeedRecreating) {
// Create the vertex buffer (always dynamic due to the camera adjust)
HardwareVertexBuffer pBuffer =
HardwareBufferManager.Instance.CreateVertexBuffer(
vertexData.vertexDeclaration.GetVertexSize(0),
vertexData.vertexCount,
BufferUsage.DynamicWriteOnlyDiscardable);
// (re)Bind the buffer
// Any existing buffer will lose its reference count and be destroyed
vertexData.vertexBufferBinding.SetBinding(0, pBuffer);
indexData.indexBuffer =
HardwareBufferManager.Instance.CreateIndexBuffer(
IndexType.Size16,
numberOfChains * maxElementsPerChain * 6, // max we can use
dynamic? BufferUsage.DynamicWriteOnly : BufferUsage.StaticWriteOnly);
// NB we don't set the indexCount on IndexData here since we will
// probably use less than the maximum number of indices
buffersNeedRecreating = false;
}
}
/// <summary>
/// Gets or sets the maximum number of chain elements per chain
/// </summary>
public virtual int MaxChainElements {
get {
return maxElementsPerChain;
}
set {
maxElementsPerChain = value;
SetupChainContainers();
buffersNeedRecreating = true;
indexContentDirty = true;
}
}
/// <summary>
/// Get the number of chain segments (this class can render
/// multiple chains at once using the same material).
/// </summary>
public virtual int NumberOfChains {
get {
return numberOfChains;
}
set {
numberOfChains = value;
SetupChainContainers();
buffersNeedRecreating = true;
indexContentDirty = true;
}
}
/// <summary>
/// Gets or sets whether texture coordinate information should be
/// included in the final buffers generated.
/// </summary>
/// <note>
/// You must use either texture coordinates or vertex color since the
/// vertices have no normals and without one of these there is no source of
/// color for the vertices.
/// </note>
public virtual bool UseTextureCoords {
get {
return useTextureCoords;
}
set {
useTextureCoords = value;
vertexDeclDirty = true;
buffersNeedRecreating = true;
indexContentDirty = true;
}
}
/// <summary>
/// Gets or sets the direction in which texture coords specified on each element
/// are deemed to run along the length of the chain.
/// </summary>
/// <param name="dir"> The direction, default is TextureCoordDirection.U.</param>
public virtual TextureCoordDirection TexCoordDirection {
get {
return texCoordDirection;
}
set {
texCoordDirection = value;
}
}
/// <summary>
/// Sets the range of the texture coordinates generated across the width of
/// the chain elements.
/// </summary>
/// <param name="start"> Start coordinate, default 0.0.</param>
/// <param name="end"> End coordinate, default 1.0.</param>
public virtual void SetOtherTextureCoordRange(float start, float end) {
otherTexCoordRange[0] = start;
otherTexCoordRange[1] = end;
}
/// <summary>
/// Gets or sets whether vertex color information should be included in the
/// final buffers generated.
/// </summary>
/// <note>
/// You must use either texture coordinates or vertex color since the
/// vertices have no normals and without one of these there is no source of
/// color for the vertices.
/// </note>
public bool UseVertexColors {
get {
return useVertexColors;
}
set {
useVertexColors = value;
vertexDeclDirty = true;
buffersNeedRecreating = true;
indexContentDirty = true;
}
}
/// <summary>
/// Sets whether or not the buffers created for this object are suitable
/// for dynamic alteration.
/// </summary>
public bool Dynamic {
get {
return dynamic;
}
set {
dynamic = value;
buffersNeedRecreating = true;
indexContentDirty = true;
}
}
/// <summary>
/// Gets or sets the material name in use
/// </summary>
public string MaterialName {
get {
return materialName;
}
set {
materialName = value;
material = MaterialManager.Instance.GetByName(materialName);
if (material == null) {
log.Warn("BillboardChain.MaterialName setter: Can't assign material " + materialName +
" to BillboardChain " + name + " because this " +
"Material does not exist. Have you forgotten to define it in a " +
".material script?");
material = MaterialManager.Instance.GetByName("BaseWhiteNoLighting");
if (material == null) {
log.Error("BillboardChain.MaterialName setter: Can't assign default material " +
"to BillboardChain of " + name + ". Did " +
"you forget to call MaterialManager.Initialise()?");
}
}
// Ensure new material loaded (will not load again if already loaded)
material.Load();
}
}
/// <summary>
/// Add an element to the 'head' of a chain.
/// </summary>
/// <remarks>
/// If this causes the number of elements to exceed the maximum elements
/// per chain, the last element in the chain (the 'tail') will be removed
/// to allow the additional element to be added.
/// </remarks>
/// <param name="chainIndex"> The index of the chain</param>
/// <param name="billboardChainElement"> The details to add</param>
protected void AddChainElement(int chainIndex, Element dtls) {
if (chainIndex >= numberOfChains) {
log.Error("BillboardChain.AddChainElement: chainIndex " + chainIndex + " out of bounds");
return;
}
ChainSegment seg = chainSegmentList[chainIndex];
if (seg.head == SEGMENT_EMPTY) {
// Tail starts at end, head grows backwards
seg.tail = maxElementsPerChain - 1;
seg.head = seg.tail;
indexContentDirty = true;
}
else
{
if (seg.head == 0)
// Wrap backwards
seg.head = maxElementsPerChain - 1;
else
// Just step backward
--seg.head;
// Run out of elements?
if (seg.head == seg.tail) {
// Move tail backwards too, losing the end of the segment and re-using
// it in the head
if (seg.tail == 0)
seg.tail = maxElementsPerChain - 1;
else
--seg.tail;
}
}
// Set the details
chainElementList[seg.start + seg.head] = dtls;
indexContentDirty = true;
boundsDirty = true;
// tell parent node to update bounds
if (parentNode != null)
parentNode.NeedUpdate();
}
/// <summary>
/// Remove an element from the 'tail' of a chain.
/// </summary>
/// <param name="chainIndex"> The index of the chain</param>
protected void RemoveChainElement(int chainIndex) {
if (chainIndex >= numberOfChains) {
log.Error("BillboardChain.RemoveChainElement: chainIndex " + chainIndex + " out of bounds");
return;
}
ChainSegment seg = chainSegmentList[chainIndex];
if (seg.head == SEGMENT_EMPTY)
return; // do nothing, nothing to remove
if (seg.tail == seg.head)
// last item
seg.head = seg.tail = SEGMENT_EMPTY;
else if (seg.tail == 0)
seg.tail = maxElementsPerChain - 1;
else
--seg.tail;
// we removed an entry so indexes need updating
indexContentDirty = true;
boundsDirty = true;
// tell parent node to update bounds
if (parentNode != null)
parentNode.NeedUpdate();
}
/// <summary>
/// Remove all elements of a given chain (but leave the chain intact).
/// </summary>
public virtual void ClearChain(int chainIndex) {
if (chainIndex >= numberOfChains) {
log.Error("BillboardChain.ClearChain: chainIndex " + chainIndex + " out of bounds");
return;
}
ChainSegment seg = chainSegmentList[chainIndex];
// Just reset head & tail
seg.tail = seg.head = SEGMENT_EMPTY;
// we removed an entry so indexes need updating
indexContentDirty = true;
boundsDirty = true;
// tell parent node to update bounds
if (parentNode != null)
parentNode.NeedUpdate();
}
/// <summary>
/// Remove all elements from all chains (but leave the chains themselves intact).
/// </summary>
public void ClearAllChains() {
for (int i=0; i<numberOfChains; i++)
ClearChain(i);
}
/// <summary>
/// Update the details of an existing chain element.
/// </summary>
/// <param name="chainIndex> The index of the chain</param>
/// <param name="elementIndex"> The element index within the chain, measured from the 'head' of the chain</param>
/// <param name="billboardChainElement"> The details to set</param>
protected void UpdateChainElement(int chainIndex, int elementIndex, Element dtls) {
if (chainIndex >= numberOfChains) {
log.Error("BillboardChain.UpdateChainElement: chainIndex " + chainIndex + " out of bounds");
return;
}
ChainSegment seg = chainSegmentList[chainIndex];
if (seg.head == SEGMENT_EMPTY) {
log.Error("BillboardChain.UpdateChainElement: Chain segment is empty " + chainIndex + " is empty");
return;
}
int idx = seg.head + elementIndex;
// adjust for the edge and start
idx = (idx % maxElementsPerChain) + seg.start;
chainElementList[idx] = dtls;
boundsDirty = true;
// tell parent node to update bounds
if (parentNode != null)
parentNode.NeedUpdate();
}
/// <summary>
/// Get the detail of a chain element.
/// </summary>
/// <param name="chainIndex> The index of the chain</param>
/// <param name="elementIndex"> The element index within the chain, measured from the 'head' of the chain</param>
protected Element GetChainElement(int chainIndex, int elementIndex) {
if (chainIndex >= numberOfChains) {
log.Error("BillboardChain.GetChainElement: chainIndex " + chainIndex + " out of bounds");
return null;
}
ChainSegment seg = chainSegmentList[chainIndex];
int idx = seg.head + elementIndex;
// adjust for the edge and start
idx = (idx % maxElementsPerChain) + seg.start;
return chainElementList[idx];
}
#region IRenderable members
public bool CastsShadows {
get {
return false;
}
}
public Technique Technique {
get {
return material.GetBestTechnique();
}
}
public Material Material {
get {
return material;
}
}
public virtual void GetWorldTransforms(Matrix4[] matrices) {
matrices[0] = parentNode.FullTransform;
}
/// <summary>
///
/// </summary>
public virtual ushort NumWorldTransforms {
get {
return 1;
}
}
///
/// </summary>
public bool UseIdentityProjection {
get {
return false;
}
}
/// <summary>
///
/// </summary>
public bool UseIdentityView {
get {
return false;
}
}
/// <summary>
///
/// </summary>
public SceneDetailLevel RenderDetail {
get {
return SceneDetailLevel.Solid;
}
}
public float GetSquaredViewDepth(Camera camera) {
Vector3 min = abb.Minimum;
Vector3 max = abb.Maximum;
Vector3 mid = ((max - min) * 0.5f) + min;
Vector3 dist = camera.DerivedPosition - mid;
return dist.LengthSquared;
}
/// <summary>
///
/// </summary>
public Quaternion WorldOrientation {
get {
return parentNode.DerivedOrientation;
}
}
/// <summary>
///
/// </summary>
public Vector3 WorldPosition {
get {
return parentNode.DerivedPosition;
}
}
public List<Light> Lights {
get {
return parentNode.Lights;
}
}
public void GetRenderOperation(RenderOperation op) {
op.indexData = indexData;
op.operationType = OperationType.TriangleList;
op.useIndices = true;
op.vertexData = vertexData;
}
public override void NotifyCurrentCamera(Camera camera) {
UpdateVertexBuffer(camera);
}
/// <summary>
/// Local bounding radius of this billboard set.
/// </summary>
public override float BoundingRadius {
get {
return boundingRadius;
}
}
public override AxisAlignedBox BoundingBox {
// cloning to prevent direct modification
get {
UpdateBounds();
return (AxisAlignedBox)abb.Clone();
}
}
public override void UpdateRenderQueue(RenderQueue queue) {
UpdateIndexBuffer();
if (indexData.indexCount > 0)
queue.AddRenderable(this, RenderQueue.DEFAULT_PRIORITY, renderQueueID);
}
public Vector4 GetCustomParameter(int index) {
if(customParams[index] == null) {
throw new Exception("A parameter was not found at the given index");
}
else {
return (Vector4)customParams[index];
}
}
public void SetCustomParameter(int index, Vector4 val) {
customParams[index] = val;
}
public void UpdateCustomGpuParameter(GpuProgramParameters.AutoConstantEntry entry, GpuProgramParameters gpuParams) {
if(customParams[entry.data] != null) {
gpuParams.SetConstant(entry.index, (Vector4)customParams[entry.data]);
}
}
public bool NormalizeNormals {
get {
return false;
}
}
#endregion IRenderable members
// Overridden members follow
protected void UpdateVertexBuffer(Camera camera) {
SetupBuffers();
HardwareVertexBuffer pBuffer = vertexData.vertexBufferBinding.GetBuffer(0);
IntPtr lockPtr = pBuffer.Lock(BufferLocking.Discard);
Vector3 camPos = camera.DerivedPosition;
Vector3 eyePos = parentNode.DerivedOrientation.Inverse() *
((camPos - parentNode.DerivedPosition) / parentNode.DerivedScale);
Vector3 chainTangent = Vector3.Zero;
unsafe {
foreach (ChainSegment seg in chainSegmentList) {
// Skip 0 or 1 element segment counts
if (seg.head != SEGMENT_EMPTY && seg.head != seg.tail) {
int laste = seg.head;
for (int e = seg.head; ; ++e) // until break
{
// Wrap forwards
if (e == maxElementsPerChain)
e = 0;
Element elem = chainElementList[e + seg.start];
Debug.Assert (((e + seg.start) * 2) < 65536, "Too many elements!");
short baseIdx = (short)((e + seg.start) * 2);
// Determine base pointer to vertex #1
byte* pBase = (byte *)lockPtr.ToPointer();
pBase += pBuffer.VertexSize * baseIdx;
// Get index of next item
int nexte = e + 1;
if (nexte == maxElementsPerChain)
nexte = 0;
if (e == seg.head)
// No laste, use next item
chainTangent = chainElementList[nexte + seg.start].position - elem.position;
else if (e == seg.tail)
// No nexte, use only last item
chainTangent = elem.position - chainElementList[laste + seg.start].position;
else
// A mid position, use tangent across both prev and next
chainTangent = chainElementList[nexte + seg.start].position - chainElementList[laste + seg.start].position;
Vector3 vP1ToEye = eyePos - elem.position;
Vector3 vPerpendicular = chainTangent.Cross(vP1ToEye);
vPerpendicular.Normalize();
vPerpendicular *= elem.width * 0.5f;
Vector3 pos0 = elem.position - vPerpendicular;
Vector3 pos1 = elem.position + vPerpendicular;
float* pFloat = (float *)pBase;
// pos1
*pFloat++ = pos0.x;
*pFloat++ = pos0.y;
*pFloat++ = pos0.z;
pBase = (byte *)pFloat;
if (useVertexColors) {
uint* pCol = (uint *)pBase;
*pCol++ = Root.Instance.ConvertColor(elem.color);
pBase = (byte *)pCol;
}
if (useTextureCoords) {
pFloat = (float *)pBase;
if (texCoordDirection == TextureCoordDirection.U) {
*pFloat++ = elem.textureCoord;
*pFloat++ = otherTexCoordRange[0];
}
else {
*pFloat++ = otherTexCoordRange[0];
*pFloat++ = elem.textureCoord;
}
pBase = (byte *)pFloat;
}
// pos2
pFloat = (float *)pBase;
*pFloat++ = pos1.x;
*pFloat++ = pos1.y;
*pFloat++ = pos1.z;
pBase = (byte *)pFloat;
if (useVertexColors) {
uint* pCol = (uint *)pBase;
*pCol++ = Root.Instance.ConvertColor(elem.color);
pBase = (byte *)pCol;
}
if (useTextureCoords) {
pFloat = (float *)pBase;
if (texCoordDirection == TextureCoordDirection.U) {
*pFloat++ = elem.textureCoord;
*pFloat++ = otherTexCoordRange[1];
}
else {
*pFloat++ = otherTexCoordRange[1];
*pFloat++ = elem.textureCoord;
}
pBase = (byte *)pFloat;
}
if (e == seg.tail)
break; // last one
laste = e;
} // element
} // segment valid?
} // each segment
} // unsafe
pBuffer.Unlock();
}
protected void UpdateIndexBuffer() {
SetupBuffers();
if (indexContentDirty) {
unsafe {
IntPtr idxPtr = indexData.indexBuffer.Lock(BufferLocking.Discard);
ushort* pShort = (ushort *)idxPtr.ToPointer();
indexData.indexCount = 0;
// indexes
foreach (ChainSegment seg in chainSegmentList) {
// Skip 0 or 1 element segment counts
if (seg.head != SEGMENT_EMPTY && seg.head != seg.tail) {
// Start from head + 1 since it's only useful in pairs
int laste = seg.head;
while(true) // until break
{
int e = laste + 1;
// Wrap forwards
if (e == maxElementsPerChain)
e = 0;
// indexes of this element are (e * 2) and (e * 2) + 1
// indexes of the last element are the same, -2
Debug.Assert (((e + seg.start) * 2) < 65536, "Too many elements!");
ushort baseIdx = (ushort)((e + seg.start) * 2);
ushort lastBaseIdx = (ushort)((laste + seg.start) * 2);
*pShort++ = lastBaseIdx;
*pShort++ = (ushort)(lastBaseIdx + 1);
*pShort++ = baseIdx;
*pShort++ = (ushort)(lastBaseIdx + 1);
*pShort++ = (ushort)(baseIdx + 1);
*pShort++ = baseIdx;
indexData.indexCount += 6;
if (e == seg.tail)
break; // last one
laste = e;
}
}
}
indexData.indexBuffer.Unlock();
}
indexContentDirty = false;
}
}
public virtual void UpdateBounds() {
if (boundsDirty) {
abb.IsNull = true;
Vector3 widthVector = Vector3.Zero;
foreach (ChainSegment seg in chainSegmentList) {
if (seg.head != SEGMENT_EMPTY) {
for(int e = seg.head; ; ++e) {
// Wrap forwards
if (e == maxElementsPerChain)
e = 0;
Element elem = chainElementList[seg.start + e];
widthVector.x = widthVector.y = widthVector.z = elem.width;
abb = AxisAlignedBox.FromDimensions(elem.position, widthVector * 2.0f);
if (e == seg.tail)
break;
}
}
}
// Set the current radius
if (abb.IsNull)
boundingRadius = 0.0f;
else
boundingRadius = (float)Math.Sqrt(Math.Max(abb.Minimum.LengthSquared, abb.Maximum.LengthSquared));
boundsDirty = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text;
using System.Globalization;
using System.Runtime;
namespace System.ServiceModel.Channels
{
internal static class DecoderHelper
{
public static void ValidateSize(int size)
{
if (size <= 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(size), size, SR.ValueMustBePositive));
}
}
}
internal struct IntDecoder
{
private int _value;
private short _index;
private const int LastIndex = 4;
public int Value
{
get
{
if (!IsValueDecoded)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FramingValueNotAvailable));
}
return _value;
}
}
public bool IsValueDecoded { get; private set; }
public void Reset()
{
_index = 0;
_value = 0;
IsValueDecoded = false;
}
public int Decode(byte[] buffer, int offset, int size)
{
DecoderHelper.ValidateSize(size);
if (IsValueDecoded)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FramingValueNotAvailable));
}
int bytesConsumed = 0;
while (bytesConsumed < size)
{
int next = buffer[offset];
_value |= (next & 0x7F) << (_index * 7);
bytesConsumed++;
if (_index == LastIndex && (next & 0xF8) != 0)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.FramingSizeTooLarge));
}
_index++;
if ((next & 0x80) == 0)
{
IsValueDecoded = true;
break;
}
offset++;
}
return bytesConsumed;
}
}
internal abstract class StringDecoder
{
private int _encodedSize;
private byte[] _encodedBytes;
private int _bytesNeeded;
private string _value;
private State _currentState;
private IntDecoder _sizeDecoder;
private int _sizeQuota;
private int _valueLengthInBytes;
public StringDecoder(int sizeQuota)
{
_sizeQuota = sizeQuota;
_sizeDecoder = new IntDecoder();
_currentState = State.ReadingSize;
Reset();
}
public bool IsValueDecoded
{
get { return _currentState == State.Done; }
}
public string Value
{
get
{
if (_currentState != State.Done)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FramingValueNotAvailable));
}
return _value;
}
}
public int Decode(byte[] buffer, int offset, int size)
{
DecoderHelper.ValidateSize(size);
int bytesConsumed;
switch (_currentState)
{
case State.ReadingSize:
bytesConsumed = _sizeDecoder.Decode(buffer, offset, size);
if (_sizeDecoder.IsValueDecoded)
{
_encodedSize = _sizeDecoder.Value;
if (_encodedSize > _sizeQuota)
{
Exception quotaExceeded = OnSizeQuotaExceeded(_encodedSize);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(quotaExceeded);
}
if (_encodedBytes == null || _encodedBytes.Length < _encodedSize)
{
_encodedBytes = Fx.AllocateByteArray(_encodedSize);
_value = null;
}
_currentState = State.ReadingBytes;
_bytesNeeded = _encodedSize;
}
break;
case State.ReadingBytes:
if (_value != null && _valueLengthInBytes == _encodedSize && _bytesNeeded == _encodedSize &&
size >= _encodedSize && CompareBuffers(_encodedBytes, buffer, offset))
{
bytesConsumed = _bytesNeeded;
OnComplete(_value);
}
else
{
bytesConsumed = _bytesNeeded;
if (size < _bytesNeeded)
{
bytesConsumed = size;
}
Buffer.BlockCopy(buffer, offset, _encodedBytes, _encodedSize - _bytesNeeded, bytesConsumed);
_bytesNeeded -= bytesConsumed;
if (_bytesNeeded == 0)
{
_value = Encoding.UTF8.GetString(_encodedBytes, 0, _encodedSize);
_valueLengthInBytes = _encodedSize;
OnComplete(_value);
}
}
break;
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.InvalidDecoderStateMachine));
}
return bytesConsumed;
}
protected virtual void OnComplete(string value)
{
_currentState = State.Done;
}
private static bool CompareBuffers(byte[] buffer1, byte[] buffer2, int offset)
{
for (int i = 0; i < buffer1.Length; i++)
{
if (buffer1[i] != buffer2[i + offset])
{
return false;
}
}
return true;
}
protected abstract Exception OnSizeQuotaExceeded(int size);
public void Reset()
{
_currentState = State.ReadingSize;
_sizeDecoder.Reset();
}
private enum State
{
ReadingSize,
ReadingBytes,
Done,
}
}
internal class ViaStringDecoder : StringDecoder
{
private Uri _via;
public ViaStringDecoder(int sizeQuota)
: base(sizeQuota)
{
}
protected override Exception OnSizeQuotaExceeded(int size)
{
Exception result = new InvalidDataException(SR.Format(SR.FramingViaTooLong, size));
FramingEncodingString.AddFaultString(result, FramingEncodingString.ViaTooLongFault);
return result;
}
protected override void OnComplete(string value)
{
try
{
_via = new Uri(value);
base.OnComplete(value);
}
catch (UriFormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataException(SR.Format(SR.FramingViaNotUri, value), exception));
}
}
public Uri ValueAsUri
{
get
{
if (!IsValueDecoded)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FramingValueNotAvailable));
}
return _via;
}
}
}
internal class FaultStringDecoder : StringDecoder
{
internal const int FaultSizeQuota = 256;
public FaultStringDecoder()
: base(FaultSizeQuota)
{
}
protected override Exception OnSizeQuotaExceeded(int size)
{
return new InvalidDataException(SR.Format(SR.FramingFaultTooLong, size));
}
public static Exception GetFaultException(string faultString, string via, string contentType)
{
if (faultString == FramingEncodingString.EndpointNotFoundFault)
{
return new EndpointNotFoundException(SR.Format(SR.EndpointNotFound, via));
}
else if (faultString == FramingEncodingString.ContentTypeInvalidFault)
{
return new ProtocolException(SR.Format(SR.FramingContentTypeMismatch, contentType, via));
}
else if (faultString == FramingEncodingString.ServiceActivationFailedFault)
{
return new ServiceActivationException(SR.Format(SR.Hosting_ServiceActivationFailed, via));
}
else if (faultString == FramingEncodingString.ConnectionDispatchFailedFault)
{
return new CommunicationException(SR.Format(SR.Sharing_ConnectionDispatchFailed, via));
}
else if (faultString == FramingEncodingString.EndpointUnavailableFault)
{
return new EndpointNotFoundException(SR.Format(SR.Sharing_EndpointUnavailable, via));
}
else if (faultString == FramingEncodingString.MaxMessageSizeExceededFault)
{
Exception inner = new QuotaExceededException(SR.FramingMaxMessageSizeExceeded);
return new CommunicationException(inner.Message, inner);
}
else if (faultString == FramingEncodingString.UnsupportedModeFault)
{
return new ProtocolException(SR.Format(SR.FramingModeNotSupportedFault, via));
}
else if (faultString == FramingEncodingString.UnsupportedVersionFault)
{
return new ProtocolException(SR.Format(SR.FramingVersionNotSupportedFault, via));
}
else if (faultString == FramingEncodingString.ContentTypeTooLongFault)
{
Exception inner = new QuotaExceededException(SR.Format(SR.FramingContentTypeTooLongFault, contentType));
return new CommunicationException(inner.Message, inner);
}
else if (faultString == FramingEncodingString.ViaTooLongFault)
{
Exception inner = new QuotaExceededException(SR.Format(SR.FramingViaTooLongFault, via));
return new CommunicationException(inner.Message, inner);
}
else if (faultString == FramingEncodingString.ServerTooBusyFault)
{
return new ServerTooBusyException(SR.Format(SR.ServerTooBusy, via));
}
else if (faultString == FramingEncodingString.UpgradeInvalidFault)
{
return new ProtocolException(SR.Format(SR.FramingUpgradeInvalid, via));
}
else
{
return new ProtocolException(SR.Format(SR.FramingFaultUnrecognized, faultString));
}
}
}
internal class ContentTypeStringDecoder : StringDecoder
{
public ContentTypeStringDecoder(int sizeQuota)
: base(sizeQuota)
{
}
protected override Exception OnSizeQuotaExceeded(int size)
{
Exception result = new InvalidDataException(SR.Format(SR.FramingContentTypeTooLong, size));
FramingEncodingString.AddFaultString(result, FramingEncodingString.ContentTypeTooLongFault);
return result;
}
public static string GetString(FramingEncodingType type)
{
switch (type)
{
case FramingEncodingType.Soap11Utf8:
return FramingEncodingString.Soap11Utf8;
case FramingEncodingType.Soap11Utf16:
return FramingEncodingString.Soap11Utf16;
case FramingEncodingType.Soap11Utf16FFFE:
return FramingEncodingString.Soap11Utf16FFFE;
case FramingEncodingType.Soap12Utf8:
return FramingEncodingString.Soap12Utf8;
case FramingEncodingType.Soap12Utf16:
return FramingEncodingString.Soap12Utf16;
case FramingEncodingType.Soap12Utf16FFFE:
return FramingEncodingString.Soap12Utf16FFFE;
case FramingEncodingType.MTOM:
return FramingEncodingString.MTOM;
case FramingEncodingType.Binary:
return FramingEncodingString.Binary;
case FramingEncodingType.BinarySession:
return FramingEncodingString.BinarySession;
default:
return "unknown" + ((int)type).ToString(CultureInfo.InvariantCulture);
}
}
}
internal abstract class FramingDecoder
{
protected FramingDecoder()
{
}
protected FramingDecoder(long streamPosition)
{
StreamPosition = streamPosition;
}
protected abstract string CurrentStateAsString { get; }
public long StreamPosition { get; set; }
protected void ValidateFramingMode(FramingMode mode)
{
switch (mode)
{
case FramingMode.Singleton:
case FramingMode.Duplex:
case FramingMode.Simplex:
case FramingMode.SingletonSized:
break;
default:
{
Exception exception = CreateException(new InvalidDataException(SR.Format(
SR.FramingModeNotSupported, mode.ToString())), FramingEncodingString.UnsupportedModeFault);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception);
}
}
}
protected void ValidateRecordType(FramingRecordType expectedType, FramingRecordType foundType)
{
if (foundType != expectedType)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidRecordTypeException(expectedType, foundType));
}
}
// special validation for Preamble Ack for usability purposes (MB#39593)
protected void ValidatePreambleAck(FramingRecordType foundType)
{
if (foundType != FramingRecordType.PreambleAck)
{
Exception inner = CreateInvalidRecordTypeException(FramingRecordType.PreambleAck, foundType);
string exceptionString;
if (((byte)foundType == 'h') || ((byte)foundType == 'H'))
{
exceptionString = SR.PreambleAckIncorrectMaybeHttp;
}
else
{
exceptionString = SR.PreambleAckIncorrect;
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(exceptionString, inner));
}
}
private Exception CreateInvalidRecordTypeException(FramingRecordType expectedType, FramingRecordType foundType)
{
return new InvalidDataException(SR.Format(SR.FramingRecordTypeMismatch, expectedType.ToString(), foundType.ToString()));
}
protected void ValidateMajorVersion(int majorVersion)
{
if (majorVersion != FramingVersion.Major)
{
Exception exception = CreateException(new InvalidDataException(SR.Format(
SR.FramingVersionNotSupported, majorVersion)), FramingEncodingString.UnsupportedVersionFault);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exception);
}
}
public Exception CreatePrematureEOFException()
{
return CreateException(new InvalidDataException(SR.FramingPrematureEOF));
}
protected Exception CreateException(InvalidDataException innerException, string framingFault)
{
Exception result = CreateException(innerException);
FramingEncodingString.AddFaultString(result, framingFault);
return result;
}
protected Exception CreateException(InvalidDataException innerException)
{
return new ProtocolException(SR.Format(SR.FramingError, StreamPosition, CurrentStateAsString),
innerException);
}
}
internal class SingletonMessageDecoder : FramingDecoder
{
private IntDecoder _sizeDecoder;
private int _chunkBytesNeeded;
private int _chunkSize;
public SingletonMessageDecoder(long streamPosition)
: base(streamPosition)
{
_sizeDecoder = new IntDecoder();
CurrentState = State.ChunkStart;
}
public void Reset()
{
CurrentState = State.ChunkStart;
}
public State CurrentState { get; private set; }
protected override string CurrentStateAsString
{
get { return CurrentState.ToString(); }
}
public int ChunkSize
{
get
{
if (CurrentState < State.ChunkStart)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FramingValueNotAvailable));
}
return _chunkSize;
}
}
public int Decode(byte[] bytes, int offset, int size)
{
DecoderHelper.ValidateSize(size);
try
{
int bytesConsumed;
switch (CurrentState)
{
case State.ReadingEnvelopeChunkSize:
bytesConsumed = _sizeDecoder.Decode(bytes, offset, size);
if (_sizeDecoder.IsValueDecoded)
{
_chunkSize = _sizeDecoder.Value;
_sizeDecoder.Reset();
if (_chunkSize == 0)
{
CurrentState = State.EnvelopeEnd;
}
else
{
CurrentState = State.ChunkStart;
_chunkBytesNeeded = _chunkSize;
}
}
break;
case State.ChunkStart:
bytesConsumed = 0;
CurrentState = State.ReadingEnvelopeBytes;
break;
case State.ReadingEnvelopeBytes:
bytesConsumed = size;
if (bytesConsumed > _chunkBytesNeeded)
{
bytesConsumed = _chunkBytesNeeded;
}
_chunkBytesNeeded -= bytesConsumed;
if (_chunkBytesNeeded == 0)
{
CurrentState = State.ChunkEnd;
}
break;
case State.ChunkEnd:
bytesConsumed = 0;
CurrentState = State.ReadingEnvelopeChunkSize;
break;
case State.EnvelopeEnd:
ValidateRecordType(FramingRecordType.End, (FramingRecordType)bytes[offset]);
bytesConsumed = 1;
CurrentState = State.End;
break;
case State.End:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
CreateException(new InvalidDataException(SR.FramingAtEnd)));
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
CreateException(new InvalidDataException(SR.InvalidDecoderStateMachine)));
}
StreamPosition += bytesConsumed;
return bytesConsumed;
}
catch (InvalidDataException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateException(e));
}
}
public enum State
{
ReadingEnvelopeChunkSize,
ChunkStart,
ReadingEnvelopeBytes,
ChunkEnd,
EnvelopeEnd,
End,
}
}
// common set of states used on the client-side.
internal enum ClientFramingDecoderState
{
ReadingUpgradeRecord,
ReadingUpgradeMode,
UpgradeResponse,
ReadingAckRecord,
Start,
ReadingFault,
ReadingFaultString,
Fault,
ReadingEnvelopeRecord,
ReadingEnvelopeSize,
EnvelopeStart,
ReadingEnvelopeBytes,
EnvelopeEnd,
ReadingEndRecord,
End,
}
internal abstract class ClientFramingDecoder : FramingDecoder
{
protected ClientFramingDecoder(long streamPosition)
: base(streamPosition)
{
CurrentState = ClientFramingDecoderState.ReadingUpgradeRecord;
}
public ClientFramingDecoderState CurrentState { get; protected set; }
protected override string CurrentStateAsString
{
get { return CurrentState.ToString(); }
}
public abstract string Fault
{
get;
}
public abstract int Decode(byte[] bytes, int offset, int size);
}
// Pattern:
// (UpgradeResponse, upgrade-bytes)*, (Ack | Fault),
// ((EnvelopeStart, ReadingEnvelopeBytes*, EnvelopeEnd) | Fault)*,
// End
internal class ClientDuplexDecoder : ClientFramingDecoder
{
private IntDecoder _sizeDecoder;
private FaultStringDecoder _faultDecoder;
private int _envelopeBytesNeeded;
private int _envelopeSize;
public ClientDuplexDecoder(long streamPosition)
: base(streamPosition)
{
_sizeDecoder = new IntDecoder();
}
public int EnvelopeSize
{
get
{
if (CurrentState < ClientFramingDecoderState.EnvelopeStart)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FramingValueNotAvailable));
}
return _envelopeSize;
}
}
public override string Fault
{
get
{
if (CurrentState < ClientFramingDecoderState.Fault)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FramingValueNotAvailable));
}
return _faultDecoder.Value;
}
}
public override int Decode(byte[] bytes, int offset, int size)
{
DecoderHelper.ValidateSize(size);
try
{
int bytesConsumed;
FramingRecordType recordType;
switch (CurrentState)
{
case ClientFramingDecoderState.ReadingUpgradeRecord:
recordType = (FramingRecordType)bytes[offset];
if (recordType == FramingRecordType.UpgradeResponse)
{
bytesConsumed = 1;
base.CurrentState = ClientFramingDecoderState.UpgradeResponse;
}
else
{
bytesConsumed = 0;
base.CurrentState = ClientFramingDecoderState.ReadingAckRecord;
}
break;
case ClientFramingDecoderState.UpgradeResponse:
bytesConsumed = 0;
base.CurrentState = ClientFramingDecoderState.ReadingUpgradeRecord;
break;
case ClientFramingDecoderState.ReadingAckRecord:
recordType = (FramingRecordType)bytes[offset];
if (recordType == FramingRecordType.Fault)
{
bytesConsumed = 1;
_faultDecoder = new FaultStringDecoder();
base.CurrentState = ClientFramingDecoderState.ReadingFaultString;
break;
}
ValidatePreambleAck(recordType);
bytesConsumed = 1;
base.CurrentState = ClientFramingDecoderState.Start;
break;
case ClientFramingDecoderState.Start:
bytesConsumed = 0;
base.CurrentState = ClientFramingDecoderState.ReadingEnvelopeRecord;
break;
case ClientFramingDecoderState.ReadingEnvelopeRecord:
recordType = (FramingRecordType)bytes[offset];
if (recordType == FramingRecordType.End)
{
bytesConsumed = 1;
base.CurrentState = ClientFramingDecoderState.End;
break;
}
else if (recordType == FramingRecordType.Fault)
{
bytesConsumed = 1;
_faultDecoder = new FaultStringDecoder();
base.CurrentState = ClientFramingDecoderState.ReadingFaultString;
break;
}
ValidateRecordType(FramingRecordType.SizedEnvelope, recordType);
bytesConsumed = 1;
base.CurrentState = ClientFramingDecoderState.ReadingEnvelopeSize;
_sizeDecoder.Reset();
break;
case ClientFramingDecoderState.ReadingEnvelopeSize:
bytesConsumed = _sizeDecoder.Decode(bytes, offset, size);
if (_sizeDecoder.IsValueDecoded)
{
base.CurrentState = ClientFramingDecoderState.EnvelopeStart;
_envelopeSize = _sizeDecoder.Value;
_envelopeBytesNeeded = _envelopeSize;
}
break;
case ClientFramingDecoderState.EnvelopeStart:
bytesConsumed = 0;
base.CurrentState = ClientFramingDecoderState.ReadingEnvelopeBytes;
break;
case ClientFramingDecoderState.ReadingEnvelopeBytes:
bytesConsumed = size;
if (bytesConsumed > _envelopeBytesNeeded)
{
bytesConsumed = _envelopeBytesNeeded;
}
_envelopeBytesNeeded -= bytesConsumed;
if (_envelopeBytesNeeded == 0)
{
base.CurrentState = ClientFramingDecoderState.EnvelopeEnd;
}
break;
case ClientFramingDecoderState.EnvelopeEnd:
bytesConsumed = 0;
base.CurrentState = ClientFramingDecoderState.ReadingEnvelopeRecord;
break;
case ClientFramingDecoderState.ReadingFaultString:
bytesConsumed = _faultDecoder.Decode(bytes, offset, size);
if (_faultDecoder.IsValueDecoded)
{
base.CurrentState = ClientFramingDecoderState.Fault;
}
break;
case ClientFramingDecoderState.Fault:
bytesConsumed = 0;
base.CurrentState = ClientFramingDecoderState.ReadingEndRecord;
break;
case ClientFramingDecoderState.ReadingEndRecord:
ValidateRecordType(FramingRecordType.End, (FramingRecordType)bytes[offset]);
bytesConsumed = 1;
base.CurrentState = ClientFramingDecoderState.End;
break;
case ClientFramingDecoderState.End:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
CreateException(new InvalidDataException(SR.FramingAtEnd)));
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
CreateException(new InvalidDataException(SR.InvalidDecoderStateMachine)));
}
StreamPosition += bytesConsumed;
return bytesConsumed;
}
catch (InvalidDataException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateException(e));
}
}
}
// Pattern:
// (UpgradeResponse, upgrade-bytes)*, (Ack | Fault),
// End
internal class ClientSingletonDecoder : ClientFramingDecoder
{
private FaultStringDecoder _faultDecoder;
public ClientSingletonDecoder(long streamPosition)
: base(streamPosition)
{
}
public override string Fault
{
get
{
if (CurrentState < ClientFramingDecoderState.Fault)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.FramingValueNotAvailable));
}
return _faultDecoder.Value;
}
}
public override int Decode(byte[] bytes, int offset, int size)
{
DecoderHelper.ValidateSize(size);
try
{
int bytesConsumed;
FramingRecordType recordType;
switch (CurrentState)
{
case ClientFramingDecoderState.ReadingUpgradeRecord:
recordType = (FramingRecordType)bytes[offset];
if (recordType == FramingRecordType.UpgradeResponse)
{
bytesConsumed = 1;
base.CurrentState = ClientFramingDecoderState.UpgradeResponse;
}
else
{
bytesConsumed = 0;
base.CurrentState = ClientFramingDecoderState.ReadingAckRecord;
}
break;
case ClientFramingDecoderState.UpgradeResponse:
bytesConsumed = 0;
base.CurrentState = ClientFramingDecoderState.ReadingUpgradeRecord;
break;
case ClientFramingDecoderState.ReadingAckRecord:
recordType = (FramingRecordType)bytes[offset];
if (recordType == FramingRecordType.Fault)
{
bytesConsumed = 1;
_faultDecoder = new FaultStringDecoder();
base.CurrentState = ClientFramingDecoderState.ReadingFaultString;
break;
}
ValidatePreambleAck(recordType);
bytesConsumed = 1;
base.CurrentState = ClientFramingDecoderState.Start;
break;
case ClientFramingDecoderState.Start:
bytesConsumed = 0;
base.CurrentState = ClientFramingDecoderState.ReadingEnvelopeRecord;
break;
case ClientFramingDecoderState.ReadingEnvelopeRecord:
recordType = (FramingRecordType)bytes[offset];
if (recordType == FramingRecordType.End)
{
bytesConsumed = 1;
base.CurrentState = ClientFramingDecoderState.End;
break;
}
else if (recordType == FramingRecordType.Fault)
{
bytesConsumed = 0;
base.CurrentState = ClientFramingDecoderState.ReadingFault;
break;
}
ValidateRecordType(FramingRecordType.UnsizedEnvelope, recordType);
bytesConsumed = 1;
base.CurrentState = ClientFramingDecoderState.EnvelopeStart;
break;
case ClientFramingDecoderState.EnvelopeStart:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
CreateException(new InvalidDataException(SR.FramingAtEnd)));
case ClientFramingDecoderState.ReadingFault:
recordType = (FramingRecordType)bytes[offset];
ValidateRecordType(FramingRecordType.Fault, recordType);
bytesConsumed = 1;
_faultDecoder = new FaultStringDecoder();
base.CurrentState = ClientFramingDecoderState.ReadingFaultString;
break;
case ClientFramingDecoderState.ReadingFaultString:
bytesConsumed = _faultDecoder.Decode(bytes, offset, size);
if (_faultDecoder.IsValueDecoded)
{
base.CurrentState = ClientFramingDecoderState.Fault;
}
break;
case ClientFramingDecoderState.Fault:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
CreateException(new InvalidDataException(SR.FramingAtEnd)));
default:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
CreateException(new InvalidDataException(SR.InvalidDecoderStateMachine)));
}
StreamPosition += bytesConsumed;
return bytesConsumed;
}
catch (InvalidDataException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateException(e));
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
using System;
using System.Diagnostics;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Graphics;
using Axiom.Media;
namespace Axiom.SceneManagers.Multiverse
{
/// <summary>
/// Summary description for Page.
///
/// Terminology:
///
/// A page a square region of terrain, of constant size across the
/// world, typically 256 meters on a side. An entire page
/// uses the same material, and usually the adjacent pages as
/// well.
///
/// A subpage is the smallest square power-of-2 division of a
/// page that has its own meters-per-sample.
///
/// A tile is a square power-of-2 division of a page which in
/// the existing implementation is the unit of rendering. The
/// smallest tile is a subpage; the largest tile is a page,
/// and the tile size is chosen based on the distance from the
/// camera, based on the ILODSpec method
/// int TilesPerPage(int pagesFromCamera)
///
/// </summary>
public class Page
{
// size of the page in "meters", this is the length of the (square) page along one axis
protected int size;
// how many pages from this one to the page containing the camera
protected int pagesFromCamera;
// index of this page in the TerrainManager's page array
protected int indexX;
protected int indexZ;
// location of the page in world space, relative to the page containing the camera
protected Vector3 relativeLocation;
protected SceneNode sceneNode;
// number of tiles (per side) on this page
protected int numTiles;
// size of a tile in "sample space"
protected int tileSize;
// tiles for this page
protected Tile [,] tiles;
protected Page neighborNorth;
protected Page neighborSouth;
protected Page neighborEast;
protected Page neighborWest;
protected bool neighborsAttached;
protected static Texture shadeMask;
protected TerrainPage terrainPage;
/// <summary>
/// Page Constructor
/// </summary>
/// <param name="relativeLocation">The location of the page in world space, relative to the page containing the camera</param>
/// <param name="indexX">index into the TerrainManager's page array</param>
/// <param name="indexZ">index into the TerrainManager's page array</param>
public Page(Vector3 relativeLocation, int indexX, int indexZ)
{
size = TerrainManager.Instance.PageSize;
this.relativeLocation = relativeLocation;
this.indexX = indexX;
this.indexZ = indexZ;
// Figure out which page the camera is in
PageCoord cameraPageCoord = new PageCoord(TerrainManager.Instance.VisPageRadius, TerrainManager.Instance.VisPageRadius);
// compute the distance (in pages) from this page to the camera page
pagesFromCamera = cameraPageCoord.Distance(new PageCoord(indexX, indexZ));
// create a scene node for this page
String nodeName = String.Format("Page[{0},{1}]", indexX, indexZ);
sceneNode = TerrainManager.Instance.WorldRootSceneNode.CreateChildSceneNode(nodeName);
sceneNode.Position = relativeLocation;
// ask the world manager how many tiles we need in this page based on the distance from the camera
numTiles = TerrainManager.Instance.TilesPerPage(pagesFromCamera);
// compute size of a tile in sample space
tileSize = size / numTiles;
// allocate the array of tiles
tiles = new Tile[numTiles,numTiles];
// this is the size of the tile in "world space"
float tileWorldSize = tileSize * TerrainManager.oneMeter;
// create the tiles for this page
for ( int tilex = 0; tilex < numTiles; tilex++ )
{
float tileWorldX = tilex * tileWorldSize + relativeLocation.x;
for ( int tilez = 0; tilez < numTiles; tilez++ )
{
float tileWorldZ = tilez * tileWorldSize + relativeLocation.z;
Tile t = new Tile(new Vector3(tileWorldX, 0, tileWorldZ), tileSize, this, tilex, tilez);
tiles[tilex, tilez] = t;
}
}
}
static byte GetSample(byte[] mask, int pageSize, int x, int y)
{
if (x < 0)
{
x = 0;
}
if (x >= pageSize)
{
x = pageSize - 1;
}
if (y < 0)
{
y = 0;
}
if (y >= pageSize)
{
y = pageSize - 1;
}
return mask[x + y * pageSize];
}
static byte [] FilterShadeMask(byte[] sourceMask, int pageSize)
{
byte[] retMask = new byte[pageSize * pageSize];
for (int x = 0; x < pageSize; x++)
{
for (int y = 0; y < pageSize; y++)
{
int val = 0;
for (int i = -1; i <= 1; i++)
{
for (int j = -1; j <= 1; j++)
{
val += GetSample(sourceMask, pageSize, x + i, y + j);
}
}
retMask[x + y * pageSize] = (byte)(val / 9);
}
}
return retMask;
}
static void BuildShadeMask()
{
int pageSize = TerrainManager.Instance.PageSize;
byte[] byteMask = new byte[pageSize * pageSize];
// fill the mask with 128, which is the 100% value
for (int i = 0; i < pageSize * pageSize; i++)
{
byteMask[i] = 128;
}
// create the random number generator
Random rand = new Random(1234);
// create a number of "blobs"
for (int i = 0; i < 200; i++)
{
// starting point for this blob
int x = rand.Next(pageSize);
int y = rand.Next(pageSize);
// value for this blob
int valueRange = 32;
byte value = (byte)rand.Next(128-valueRange, 128+valueRange);
// number of points in this blob
int n = rand.Next(10, 500);
while (n >= 0)
{
if (byteMask[x + y * pageSize] == 128)
{
n--;
byteMask[x + y * pageSize] = value;
}
// move in a random direction
int dir = rand.Next(8);
switch (dir)
{
case 0:
x++;
break;
case 1:
x--;
break;
case 2:
y++;
break;
case 3:
y--;
break;
case 4:
x++;
y++;
break;
case 5:
x++;
y--;
break;
case 6:
x--;
y++;
break;
case 7:
x--;
y--;
break;
}
// clamp x and y to the page
if (x < 0)
{
x = 0;
}
if (x > pageSize - 1)
{
x = pageSize - 1;
}
if (y < 0)
{
y = 0;
}
if (y > pageSize - 1)
{
y = pageSize - 1;
}
}
}
// simple box filter on the shade mask
byteMask = FilterShadeMask(byteMask, pageSize);
// generate a texture from the mask
Image maskImage = Image.FromDynamicImage(byteMask, pageSize, pageSize, PixelFormat.A8);
String texName = "PageShadeMask";
shadeMask = TextureManager.Instance.LoadImage(texName, maskImage);
}
public static void SetShadeMask(Material mat, int texunit)
{
if (shadeMask == null)
{
BuildShadeMask();
}
mat.GetTechnique(0).GetPass(0).GetTextureUnitState(texunit).SetTextureName(shadeMask.Name);
}
/// <summary>
/// Set the neighbor pointers for this page. Must be done after all the pages
/// in the TerrainManager pages array have been constructed.
/// </summary>
public void AttachNeighbors()
{
if ( indexX > 0 )
{
neighborWest = TerrainManager.Instance.LookupPage(indexX - 1, indexZ);
}
else
{
neighborWest = null;
}
if ( indexX < ( TerrainManager.Instance.PageArraySize - 1 ) )
{
neighborEast = TerrainManager.Instance.LookupPage(indexX + 1, indexZ);
}
else
{
neighborEast = null;
}
if ( indexZ > 0 )
{
neighborNorth = TerrainManager.Instance.LookupPage(indexX, indexZ - 1);
}
else
{
neighborNorth = null;
}
if ( indexZ < ( TerrainManager.Instance.PageArraySize - 1 ) )
{
neighborSouth = TerrainManager.Instance.LookupPage(indexX, indexZ + 1);
}
else
{
neighborSouth = null;
}
neighborsAttached = true;
return;
}
public void AttachTiles()
{
Debug.Assert(neighborsAttached, "Trying to attach tiles when pages haven't been attached");
foreach ( Tile t in tiles )
{
t.AttachNeighbors();
}
}
public int NumTiles
{
get
{
return numTiles;
}
}
public Vector3 Location
{
get
{
return relativeLocation + TerrainManager.Instance.CameraPageLocation;
}
}
public int IndexX
{
get
{
return indexX;
}
}
public int IndexZ
{
get
{
return indexZ;
}
}
public TerrainPage TerrainPage
{
get
{
return terrainPage;
}
set
{
terrainPage = value;
if (terrainPage != null)
{
Debug.Assert(Location == terrainPage.Location, "assigning terrainPage to page with different location");
}
}
}
/// <summary>
/// This method is called whenever the camera moves, so that the page can update itself.
/// </summary>
/// <param name="camera">the camera for this scene. used to supply the current camera location</param>
public void UpdateCamera(Camera camera)
{
}
/// <summary>
/// Find the tile for a given location
/// </summary>
/// <param name="location"></param>
/// <returns>Returns the tile. Will raise an array bounds exception if the location is not in this page</returns>
public Tile LookupTile(Vector3 location)
{
PageCoord locPageCoord = new PageCoord(location, size / numTiles);
PageCoord tilePageCoord = new PageCoord(Location, size / numTiles);
PageCoord tileOffset = locPageCoord - tilePageCoord;
return tiles[tileOffset.X, tileOffset.Z];
}
public Tile LookupTile(int x, int z)
{
return tiles[x,z];
}
public Page FindNeighbor(Direction dir)
{
Page p = null;
switch (dir)
{
case Direction.North:
p = neighborNorth;
break;
case Direction.South:
p = neighborSouth;
break;
case Direction.East:
p = neighborEast;
break;
case Direction.West:
p = neighborWest;
break;
}
return p;
}
}
}
| |
//-----------------------------------------------------------------------------
// Filename: SIPURI.cs
//
// Description: SIP URI.
//
// History:
// 09 Apr 2006 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 (aaron@sipsorcery.com), 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.Specialized;
using System.Net;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using SIPSorcery.Sys;
using log4net;
namespace SIPSorcery.SIP
{
/// <summary>
/// Implements the the absoluteURI structure from the SIP RFC (incomplete as at 17 nov 2006, AC).
/// </summary>
/// <bnf>
/// absoluteURI = scheme ":" ( hier-part / opaque-part )
/// hier-part = ( net-path / abs-path ) [ "?" query ]
/// net-path = "//" authority [ abs-path ]
/// abs-path = "/" path-segments
///
/// opaque-part = uric-no-slash *uric
/// uric = reserved / unreserved / escaped
/// uric-no-slash = unreserved / escaped / ";" / "?" / ":" / "@" / "&" / "=" / "+" / "$" / ","
/// path-segments = segment *( "/" segment )
/// segment = *pchar *( ";" param )
/// param = *pchar
/// pchar = unreserved / escaped / ":" / "@" / "&" / "=" / "+" / "$" / ","
/// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
/// authority = srvr / reg-name
/// srvr = [ [ userinfo "@" ] hostport ]
/// reg-name = 1*( unreserved / escaped / "$" / "," / ";" / ":" / "@" / "&" / "=" / "+" )
/// query = *uric
///
/// SIP-URI = "sip:" [ userinfo ] hostport uri-parameters [ headers ]
/// SIPS-URI = "sips:" [ userinfo ] hostport uri-parameters [ headers ]
/// userinfo = ( user / telephone-subscriber ) [ ":" password ] "@"
/// user = 1*( unreserved / escaped / user-unreserved )
/// user-unreserved = "&" / "=" / "+" / "$" / "," / ";" / "?" / "/"
/// password = *( unreserved / escaped / "&" / "=" / "+" / "$" / "," )
/// hostport = host [ ":" port ]
/// host = hostname / IPv4address / IPv6reference
/// hostname = *( domainlabel "." ) toplabel [ "." ]
/// domainlabel = alphanum / alphanum *( alphanum / "-" ) alphanum
/// toplabel = ALPHA / ALPHA *( alphanum / "-" ) alphanum
/// IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
/// IPv6reference = "[" IPv6address "]"
/// IPv6address = hexpart [ ":" IPv4address ]
/// hexpart = hexseq / hexseq "::" [ hexseq ] / "::" [ hexseq ]
/// hexseq = hex4 *( ":" hex4)
/// hex4 = 1*4HEXDIG
/// port = 1*DIGIT
///
/// The BNF for telephone-subscriber can be found in RFC 2806 [9]. Note,
/// however, that any characters allowed there that are not allowed in
/// the user part of the SIP URI MUST be escaped.
///
/// uri-parameters = *( ";" uri-parameter)
/// uri-parameter = transport-param / user-param / method-param / ttl-param / maddr-param / lr-param / other-param
/// transport-param = "transport=" ( "udp" / "tcp" / "sctp" / "tls" / other-transport)
/// other-transport = token
/// user-param = "user=" ( "phone" / "ip" / other-user)
/// other-user = token
/// method-param = "method=" Method
/// ttl-param = "ttl=" ttl
/// maddr-param = "maddr=" host
/// lr-param = "lr"
/// other-param = pname [ "=" pvalue ]
/// pname = 1*paramchar
/// pvalue = 1*paramchar
/// paramchar = param-unreserved / unreserved / escaped
/// param-unreserved = "[" / "]" / "/" / ":" / "&" / "+" / "$"
///
/// headers = "?" header *( "&" header )
/// header = hname "=" hvalue
/// hname = 1*( hnv-unreserved / unreserved / escaped )
/// hvalue = *( hnv-unreserved / unreserved / escaped )
/// hnv-unreserved = "[" / "]" / "/" / "?" / ":" / "+" / "$"
/// </bnf>
/// <remarks>
/// Specific parameters for URIs: transport, maddr, ttl, user, method, lr.
/// </remarks>
[DataContract]
public class SIPURI
{
public const int DNS_RESOLUTION_TIMEOUT = 2000; // Timeout for resolving DNS hosts in milliseconds.
public const char SCHEME_ADDR_SEPARATOR = ':';
public const char USER_HOST_SEPARATOR = '@';
public const char PARAM_TAG_DELIMITER = ';';
public const char HEADER_START_DELIMITER = '?';
private const char HEADER_TAG_DELIMITER = '&';
private const char TAG_NAME_VALUE_SEPERATOR = '=';
private static ILog logger = AssemblyState.logger;
private static char[] m_invalidSIPHostChars = new char[] { ',', '"' };
private static SIPProtocolsEnum m_defaultSIPTransport = SIPProtocolsEnum.udp;
private static SIPSchemesEnum m_defaultSIPScheme = SIPSchemesEnum.sip;
private static int m_defaultSIPPort = SIPConstants.DEFAULT_SIP_PORT;
private static int m_defaultSIPTLSPort = SIPConstants.DEFAULT_SIP_TLS_PORT;
private static string m_sipRegisterRemoveAll = SIPConstants.SIP_REGISTER_REMOVEALL;
private static string m_uriParamTransportKey = SIPHeaderAncillary.SIP_HEADERANC_TRANSPORT;
[DataMember]
public SIPSchemesEnum Scheme = m_defaultSIPScheme;
[DataMember]
public string User;
[DataMember]
public string Host;
[DataMember]
public SIPParameters Parameters = new SIPParameters(null, PARAM_TAG_DELIMITER);
[DataMember]
public SIPParameters Headers = new SIPParameters(null, HEADER_TAG_DELIMITER);
/// <summary>
/// The protocol for a SIP URI is dicatated by the scheme of the URI and then by the transport parameter and finally by the
/// use fo a default protocol. If the URI is a sips one then the protocol must be TLS. After that if there is a transport
/// parameter specified for the URI it dictates the protocol for the URI. Finally if there is no transport parameter for a sip
/// URI then the default UDP transport is used.
/// </summary>
public SIPProtocolsEnum Protocol
{
get
{
if (Scheme == SIPSchemesEnum.sips)
{
return SIPProtocolsEnum.tls;
}
else
{
if (Parameters != null && Parameters.Has(m_uriParamTransportKey))
{
if (SIPProtocolsType.IsAllowedProtocol(Parameters.Get(m_uriParamTransportKey)))
{
return SIPProtocolsType.GetProtocolType(Parameters.Get(m_uriParamTransportKey));
}
}
return m_defaultSIPTransport;
}
}
set
{
if (value == SIPProtocolsEnum.udp)
{
Scheme = SIPSchemesEnum.sip;
if (Parameters != null && Parameters.Has(m_uriParamTransportKey))
{
Parameters.Remove(m_uriParamTransportKey);
}
}
else
{
Parameters.Set(m_uriParamTransportKey, value.ToString());
}
}
}
/// <summary>
/// Returns a string that can be used to compare SIP URI addresses.
/// </summary>
public string CanonicalAddress
{
get
{
string canonicalAddress = Scheme + ":";
canonicalAddress += (User != null && User.Trim().Length > 0) ? User + "@" : null;
if (Host.IndexOf(':') != -1)
{
canonicalAddress += Host;
}
else
{
canonicalAddress += Host + ":" + m_defaultSIPPort;
}
return canonicalAddress;
}
}
public string UnescapedUser
{
get
{
return (User.IsNullOrBlank()) ? User : SIPEscape.SIPURIUserUnescape(User);
}
}
private SIPURI()
{ }
public SIPURI(string user, string host, string paramsAndHeaders)
{
User = user;
Host = host;
ParseParamsAndHeaders(paramsAndHeaders);
}
public SIPURI(string user, string host, string paramsAndHeaders, SIPSchemesEnum scheme)
{
User = user;
Host = host;
ParseParamsAndHeaders(paramsAndHeaders);
Scheme = scheme;
}
public SIPURI(string user, string host, string paramsAndHeaders, SIPSchemesEnum scheme, SIPProtocolsEnum protocol)
{
User = user;
Host = host;
ParseParamsAndHeaders(paramsAndHeaders);
Scheme = scheme;
if (protocol != SIPProtocolsEnum.udp)
{
Parameters.Set(m_uriParamTransportKey, protocol.ToString());
}
}
public SIPURI(SIPSchemesEnum scheme, SIPEndPoint sipEndPoint)
{
Scheme = scheme;
Host = sipEndPoint.GetIPEndPoint().ToString();
if (sipEndPoint.Protocol != SIPProtocolsEnum.udp)
{
Parameters.Set(m_uriParamTransportKey, sipEndPoint.Protocol.ToString());
}
}
public static SIPURI ParseSIPURI(string uri)
{
try
{
SIPURI sipURI = new SIPURI();
if (uri == null || uri.Trim().Length == 0)
{
throw new SIPValidationException(SIPValidationFieldsEnum.URI, "A SIP URI cannot be parsed from an empty string.");
}
else
{
if (uri == m_sipRegisterRemoveAll)
{
sipURI.Host = m_sipRegisterRemoveAll;
}
else
{
int colonPosn = uri.IndexOf(SCHEME_ADDR_SEPARATOR);
if (colonPosn == -1)
{
throw new SIPValidationException(SIPValidationFieldsEnum.URI, "SIP URI did not contain compulsory colon");
}
else
{
try
{
sipURI.Scheme = SIPSchemesType.GetSchemeType(uri.Substring(0, colonPosn));
}
catch
{
throw new SIPValidationException(SIPValidationFieldsEnum.URI, SIPResponseStatusCodesEnum.UnsupportedURIScheme, "SIP scheme " + uri.Substring(0, colonPosn) + " was not understood");
}
string uriHostPortion = uri.Substring(colonPosn + 1);
int ampPosn = uriHostPortion.IndexOf(USER_HOST_SEPARATOR);
int paramHeaderPosn = -1;
if (ampPosn != -1)
{
paramHeaderPosn = uriHostPortion.IndexOfAny(new char[] { PARAM_TAG_DELIMITER, HEADER_START_DELIMITER }, ampPosn);
}
else
{
// Host only SIP URI.
paramHeaderPosn = uriHostPortion.IndexOfAny(new char[] { PARAM_TAG_DELIMITER, HEADER_START_DELIMITER });
}
if (ampPosn != -1 && paramHeaderPosn != -1)
{
sipURI.User = uriHostPortion.Substring(0, ampPosn);
sipURI.Host = uriHostPortion.Substring(ampPosn + 1, paramHeaderPosn - ampPosn - 1);
string paramsAndHeaders = uriHostPortion.Substring(paramHeaderPosn);
sipURI.ParseParamsAndHeaders(paramsAndHeaders);
}
else if (ampPosn == -1 && paramHeaderPosn == 0)
{
throw new SIPValidationException(SIPValidationFieldsEnum.URI, "No Host portion in SIP URI");
}
else if (ampPosn == -1 && paramHeaderPosn != -1)
{
sipURI.Host = uriHostPortion.Substring(0, paramHeaderPosn);
string paramsAndHeaders = uriHostPortion.Substring(paramHeaderPosn);
sipURI.ParseParamsAndHeaders(paramsAndHeaders);
}
else if (ampPosn != -1)
{
sipURI.User = uriHostPortion.Substring(0, ampPosn);
sipURI.Host = uriHostPortion.Substring(ampPosn + 1, uriHostPortion.Length - ampPosn - 1);
}
else
{
sipURI.Host = uriHostPortion;
}
if (sipURI.Host.IndexOfAny(m_invalidSIPHostChars) != -1)
{
throw new SIPValidationException(SIPValidationFieldsEnum.URI, "The SIP URI host portion contained an invalid character.");
}
}
}
return sipURI;
}
}
catch (SIPValidationException)
{
throw;
}
catch (Exception excp)
{
logger.Error("Exception ParseSIPURI (URI=" + uri + "). " + excp.Message);
throw new SIPValidationException(SIPValidationFieldsEnum.URI, "Unknown error parsing SIP URI.");
}
}
public static SIPURI ParseSIPURIRelaxed(string partialURI)
{
if (partialURI == null || partialURI.Trim().Length == 0)
{
return null;
}
else
{
string regexSchemePattern = "^(" + SIPSchemesEnum.sip + "|" + SIPSchemesEnum.sips + "):";
if (Regex.Match(partialURI, regexSchemePattern + @"\S+").Success)
{
// The partial uri is already valid.
return SIPURI.ParseSIPURI(partialURI);
}
else
{
// The partial URI is missing the scheme.
return SIPURI.ParseSIPURI(m_defaultSIPScheme.ToString() + SCHEME_ADDR_SEPARATOR.ToString() + partialURI);
}
}
}
public static bool TryParse(string uri)
{
try
{
ParseSIPURIRelaxed(uri);
return true;
}
catch
{
return false;
}
}
public new string ToString()
{
try
{
string uriStr = Scheme.ToString() + SCHEME_ADDR_SEPARATOR;
uriStr = (User != null) ? uriStr + User + USER_HOST_SEPARATOR + Host : uriStr + Host;
if (Parameters != null && Parameters.Count > 0)
{
uriStr += Parameters.ToString();
}
// If the URI's protocol is not implied already set the transport parameter.
if (Scheme != SIPSchemesEnum.sips && Protocol != SIPProtocolsEnum.udp && !Parameters.Has(m_uriParamTransportKey))
{
uriStr += PARAM_TAG_DELIMITER + m_uriParamTransportKey + TAG_NAME_VALUE_SEPERATOR + Protocol.ToString();
}
if (Headers != null && Headers.Count > 0)
{
string headerStr = Headers.ToString();
uriStr += HEADER_START_DELIMITER + headerStr.Substring(1);
}
return uriStr;
}
catch (Exception excp)
{
logger.Error("Exception SIPURI ToString. " + excp.Message);
throw excp;
}
}
/// <summary>
/// Returns a string representation of the URI with any parameter and headers ommitted except for the transport
/// parameter. The string returned by this function is used amonst other things to match Route headers set by this
/// SIP agent.
/// </summary>
/// <returns>A string represenation of the URI with headers and parameteres ommitted except for the trnaport parameter if it is required.</returns>
public string ToParameterlessString()
{
try
{
string uriStr = Scheme.ToString() + SCHEME_ADDR_SEPARATOR;
uriStr = (User != null) ? uriStr + User + USER_HOST_SEPARATOR + Host : uriStr + Host;
// If the URI's protocol is not implied already set the transport parameter.
if (Scheme != SIPSchemesEnum.sips && Protocol != SIPProtocolsEnum.udp && !Parameters.Has(m_uriParamTransportKey))
{
uriStr += PARAM_TAG_DELIMITER + m_uriParamTransportKey + TAG_NAME_VALUE_SEPERATOR + Protocol.ToString();
}
return uriStr;
}
catch (Exception excp)
{
logger.Error("Exception SIPURI ToParamaterlessString. " + excp.Message);
throw excp;
}
}
/// <summary>
/// Returns an address of record for the SIP URI which is a string in the format user@host.
/// </summary>
/// <returns>A string representing the address of record for the URI.</returns>
public string ToAOR()
{
return User + USER_HOST_SEPARATOR + Host;
}
public SIPEndPoint ToSIPEndPoint()
{
if (IPSocket.IsIPSocket(Host) || IPSocket.IsIPAddress(Host))
{
if (Host.IndexOf(":") != -1)
{
return new SIPEndPoint(Protocol, IPSocket.GetIPEndPoint(Host));
}
else
{
if(Protocol == SIPProtocolsEnum.tls)
{
return new SIPEndPoint(Protocol, IPSocket.GetIPEndPoint(Host + ":" + m_defaultSIPTLSPort));
}
else
{
return new SIPEndPoint(Protocol, IPSocket.GetIPEndPoint(Host + ":" + m_defaultSIPPort));
}
}
}
else
{
return null;
}
}
public static bool AreEqual(SIPURI uri1, SIPURI uri2)
{
return uri1 == uri2;
}
private void ParseParamsAndHeaders(string paramsAndHeaders)
{
if (paramsAndHeaders != null && paramsAndHeaders.Trim().Length > 0)
{
int headerDelimPosn = paramsAndHeaders.IndexOf(HEADER_START_DELIMITER);
if (headerDelimPosn == -1)
{
Parameters = new SIPParameters(paramsAndHeaders, PARAM_TAG_DELIMITER);
}
else
{
Parameters = new SIPParameters(paramsAndHeaders.Substring(0, headerDelimPosn), PARAM_TAG_DELIMITER);
Headers = new SIPParameters(paramsAndHeaders.Substring(headerDelimPosn + 1), HEADER_TAG_DELIMITER);
}
}
}
public override bool Equals(object obj)
{
return AreEqual(this, (SIPURI)obj);
}
public static bool operator ==(SIPURI uri1, SIPURI uri2)
{
if ((object)uri1 == null && (object)uri2 == null)
//if (uri1 == null && uri2 == null)
{
return true;
}
else if ((object)uri1 == null || (object)uri2 == null)
//if (uri1 == null || uri2 == null)
{
return false;
}
else if (uri1.Host == null || uri2.Host == null)
{
return false;
}
else if (uri1.CanonicalAddress != uri2.CanonicalAddress)
{
return false;
}
else
{
// Compare parameters.
if (uri1.Parameters.Count != uri2.Parameters.Count)
{
return false;
}
else
{
string[] uri1Keys = uri1.Parameters.GetKeys();
if (uri1Keys != null && uri1Keys.Length > 0)
{
foreach (string key in uri1Keys)
{
if (uri1.Parameters.Get(key) != uri2.Parameters.Get(key))
{
return false;
}
}
}
}
// Compare headers.
if (uri1.Headers.Count != uri2.Headers.Count)
{
return false;
}
else
{
string[] uri1Keys = uri1.Headers.GetKeys();
if (uri1Keys != null && uri1Keys.Length > 0)
{
foreach (string key in uri1Keys)
{
if (uri1.Headers.Get(key) != uri2.Headers.Get(key))
{
return false;
}
}
}
}
}
return true;
}
public static bool operator !=(SIPURI x, SIPURI y)
{
return !(x == y);
}
public override int GetHashCode()
{
return CanonicalAddress.GetHashCode() + Parameters.GetHashCode() + Headers.GetHashCode();
}
public SIPURI CopyOf()
{
SIPURI copy = new SIPURI();
copy.Scheme = Scheme;
copy.Host = Host;
copy.User = User;
if (Parameters.Count > 0)
{
copy.Parameters = Parameters.CopyOf();
}
if (Headers.Count > 0)
{
copy.Headers = Headers.CopyOf();
}
return copy;
}
}
}
| |
/*******************************************************************************
*
* Copyright (C) 2013-2014 Frozen North Computing
*
* 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.Drawing;
#if FN2D_WIN
using OpenTK.Graphics.OpenGL;
#elif FN2D_IOS || FN2D_AND
using OpenTK.Graphics;
using OpenTK.Graphics.ES11;
using BeginMode = OpenTK.Graphics.ES11.All;
#endif
namespace FrozenNorth.OpenGL.FN2D
{
public class FN2DLine : IDisposable
{
// instance variables
protected Point p1, p2;
protected float width;
protected Color color;
protected FN2DArrays lineArrays = FN2DArrays.Create(BeginMode.TriangleStrip, 8);
protected FN2DArrays cap1Arrays = FN2DArrays.Create(BeginMode.TriangleStrip, 4);
protected FN2DArrays cap2Arrays = FN2DArrays.Create(BeginMode.TriangleStrip, 4);
public FN2DLine(Point p1, Point p2, float width, Color color)
{
// save the parameters
this.p1 = p1;
this.p2 = p2;
this.width = width;
this.color = color;
// get the arrays
Refresh();
}
/// <summary>
/// Gets or sets the first point.
/// </summary>
public Point Point1
{
get { return p1; }
set
{
p1 = value;
Refresh();
}
}
/// <summary>
/// Gets or sets the second point.
/// </summary>
public Point Point2
{
get { return p2; }
set
{
p2 = value;
Refresh();
}
}
/// <summary>
/// Gets or sets the width.
/// </summary>
public float Width
{
get { return width; }
set
{
width = (value > 0) ? value : 1;
Refresh();
}
}
/// <summary>
/// Gets or sets the color.
/// </summary>
public Color Color
{
get { return color; }
set
{
color = value;
Refresh();
}
}
/// <summary>
/// Refreshes the arrays when something changes.
/// </summary>
private void Refresh()
{
float t, R = 1.08f;
float f = width - (int)width;
float alpha = color.A / 255f;
// determine parameters t,R
if (width >= 0 && width < 1)
{
t = 0.05f;
R = 0.48f + f * 0.32f;
alpha *= f;
}
else if (width >= 1 && width < 2)
{
t = 0.05f + f * 0.33f;
R = 0.768f + f * 0.312f;
}
else if (width >= 2 && width < 3)
{
t = 0.38f + f * 0.58f;
}
else if (width >= 3 && width < 4)
{
t = 0.96f + f * 0.48f;
}
else if (width >= 4 && width < 5)
{
t = 1.44f + f * 0.46f;
}
else if (width >= 5 && width < 6)
{
t = 1.9f + f * 0.6f;
}
else
{
t = 2.5f + (width - 6) * 0.5f;
}
// determine angle of the line to horizontal
float tx = 0, ty = 0; //core thinkness of a line
float Rx = 0, Ry = 0; //fading edge of a line
float cx = 0, cy = 0; //cap of a line
float ALW = 0.01f;
float dx = p2.X - p1.X;
float dy = p2.Y - p1.Y;
if (Math.Abs(dx) < ALW)
{
// vertical
tx = t;
Rx = R;
if (width > 0 && width < 1)
tx *= 8;
else if (width == 1)
tx *= 10;
}
else if (Math.Abs(dy) < ALW)
{
// horizontal
ty = t;
Ry = R;
if (width > 0 && width < 1)
ty *= 8;
else if (width == 1)
ty *= 10;
}
else
{
// approximate to make things even faster
if (width < 3)
{
float m = dy / dx;
// calculate tx,ty,Rx,Ry
if (m > -0.4142f && m <= 0.4142f)
{
// -22.5< angle <= 22.5, approximate to 0 (degree)
tx = t * 0.1f; ty = t;
Rx = R * 0.6f; Ry = R;
}
else if (m > 0.4142f && m <= 2.4142f)
{
// 22.5< angle <= 67.5, approximate to 45 (degree)
tx = t * -0.7071f; ty = t * 0.7071f;
Rx = R * -0.7071f; Ry = R * 0.7071f;
}
else if (m > 2.4142f || m <= -2.4142f)
{
// 67.5 < angle <=112.5, approximate to 90 (degree)
tx = t; ty = t * 0.1f;
Rx = R; Ry = R * 0.6f;
}
else if (m > -2.4142f && m < -0.4142f)
{
// 112.5 < angle < 157.5, approximate to 135 (degree)
tx = t * 0.7071f; ty = t * 0.7071f;
Rx = R * 0.7071f; Ry = R * 0.7071f;
}
else
{
// error in determining angle
//printf( "error in determining angle: m=%.4f\n",m);
}
}
// calculate to exact
else
{
dx = p1.Y - p2.Y;
dy = p2.X - p1.X;
float L = (float)Math.Sqrt(dx * dx + dy * dy);
dx /= L;
dy /= L;
cx = -0.6f * dy; cy = 0.6f * dx;
tx = t * dx; ty = t * dy;
Rx = R * dx; Ry = R * dy;
}
}
// clear the arrays
lineArrays.Clear();
cap1Arrays.Clear();
cap2Arrays.Clear();
// create the colors
Color color0 = Color.FromArgb(0, color);
Color colorA = Color.FromArgb((int)(alpha * 255), color);
// create the line vertices
lineArrays.AddVertex(p1.X - tx - Rx, p1.Y - ty - Ry, color0); // fading edge1
lineArrays.AddVertex(p2.X - tx - Rx, p2.Y - ty - Ry, color0);
lineArrays.AddVertex(p1.X - tx, p1.Y - ty, colorA); // core
lineArrays.AddVertex(p2.X - tx, p2.Y - ty, colorA);
lineArrays.AddVertex(p1.X + tx, p1.Y + ty, colorA);
lineArrays.AddVertex(p2.X + tx, p2.Y + ty, colorA);
if (!(Math.Abs(dx) < ALW || Math.Abs(dy) < ALW) || width > 1)
{
lineArrays.AddVertex(p1.X + tx + Rx, p1.Y + ty + Ry, color0); // fading edge2
lineArrays.AddVertex(p2.X + tx + Rx, p2.Y + ty + Ry, color0);
}
// create the cap vertices
if (width >= 3)
{
cap1Arrays.AddVertex(p1.X - Rx + cx, p1.Y - Ry + cy, color0);
cap1Arrays.AddVertex(p1.X + Rx + cx, p1.Y + Ry + cy, color0);
cap1Arrays.AddVertex(p1.X - tx - Rx, p1.Y - ty - Ry, colorA);
cap1Arrays.AddVertex(p1.X + tx + Rx, p1.Y + ty + Ry, colorA);
cap2Arrays.AddVertex(p2.X - Rx - cx, p2.Y - Ry - cy, color0);
cap2Arrays.AddVertex(p2.X + Rx - cx, p2.Y + Ry - cy, color0);
cap2Arrays.AddVertex(p2.X - tx - Rx, p2.Y - ty - Ry, colorA);
cap2Arrays.AddVertex(p2.X + tx + Rx, p2.Y + ty + Ry, colorA);
}
//lineArrays.Dump("lines");
//cap1Arrays.Dump("cap1");
//cap2Arrays.Dump("cap2");
}
/// <summary>
/// Destructor - Calls Dispose().
/// </summary>
~FN2DLine()
{
Dispose(false);
}
/// <summary>
/// Releases all resource used by the object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Frees unmanaged resources and calls Dispose() on the member objects.
/// </summary>
protected virtual void Dispose(bool disposing)
{
// if we got here via Dispose(), call Dispose() on the member objects
if (disposing)
{
if (lineArrays != null) lineArrays.Dispose();
if (cap1Arrays != null) cap1Arrays.Dispose();
if (cap2Arrays != null) cap2Arrays.Dispose();
}
// clear the object references
lineArrays = null;
cap1Arrays = null;
cap2Arrays = null;
}
/// <summary>
/// Draws the line.
/// </summary>
public void Draw()
{
lineArrays.Draw();
cap1Arrays.Draw();
cap2Arrays.Draw();
}
}
}
| |
/**
*
* **This is the MICRO version of throttling controller**
* Three clusters scheme described in the paper that always perform cluster scheduling without any trigger.
* There's a single netutil target to used as for throttle rate adjustment. The throttle rate is applied to
* both high(RR) clusters and the always throttled cluster. The controller can used either filling up total mpki
* or single app mpki thresh to decide which app to be put into the low intensity cluster. The RR clusters
* has a threshold value to choose which apps to be selected. If an app's mpki is greater than the threshold,
* it's put into the always throttled cluster.
*
* Always throttled cluster can be disabled, so is total mpki filling for low intensity cluster.
*
**/
//#define DEBUG_NETUTIL
//#define DEBUG_CLUSTER
//#define DEBUG_CLUSTER2
using System;
using System.Collections.Generic;
namespace ICSimulator
{
public class Controller_Three_Level_Cluster_NoTrig: Controller_Global_Batch
{
//nodes in these clusters are always throttled without given it a free injection slot!
public static Cluster throttled_cluster;
public static Cluster low_intensity_cluster;
string getName(int ID)
{
return Simulator.network.workload.getName(ID);
}
void writeNode(int ID)
{
Console.Write("{0} ({1}) ", ID, getName(ID));
}
public Controller_Three_Level_Cluster_NoTrig()
{
for (int i = 0; i < Config.N; i++)
{
MPKI[i]=0.0;
num_ins_last_epoch[i]=0;
m_isThrottled[i]=false;
L1misses[i]=0;
lastNetUtil = 0;
}
throttled_cluster=new Cluster();
low_intensity_cluster=new Cluster();
cluster_pool=new BatchClusterPool(Config.cluster_MPKI_threshold);
}
public override void doThrottling()
{
//All nodes in the low intensity can alway freely inject.
int [] low_nodes=low_intensity_cluster.allNodes();
if(low_nodes.Length>0)
{
#if DEBUG_CLUSTER2
Console.WriteLine("\n:: cycle {0} ::", Simulator.CurrentRound);
Console.Write("\nLow nodes *NOT* throttled: ");
#endif
foreach (int node in low_nodes)
{
#if DEBUG_CLUSTER2
writeNode(node);
#endif
setThrottleRate(node,false);
m_nodeStates[node] = NodeState.Low;
}
}
//Throttle all the high other nodes
int [] high_nodes=cluster_pool.allNodes();
#if DEBUG_CLUSTER2
Console.Write("\nAll high other nodes: ");
#endif
foreach (int node in high_nodes)
{
#if DEBUG_CLUSTER2
writeNode(node);
#endif
setThrottleRate(node,true);
m_nodeStates[node] = NodeState.HighOther;
}
//Unthrottle all the nodes in the free-injecting cluster
int [] nodes=cluster_pool.nodesInNextCluster();
#if DEBUG_CLUSTER2
Console.Write("\nUnthrottling cluster nodes: ");
#endif
if(nodes.Length>0)
{
foreach (int node in nodes)
{
setThrottleRate(node,false);
m_nodeStates[node] = NodeState.HighGolden;
Simulator.stats.throttle_time_bysrc[node].Add();
#if DEBUG_CLUSTER2
writeNode(node);
#endif
}
}
/* Throttle nodes in always throttled mode. */
int [] throttled_nodes=throttled_cluster.allNodes();
if(throttled_nodes.Length>0)
{
#if DEBUG_CLUSTER2
Console.Write("\nAlways Throttled nodes: ");
#endif
foreach (int node in throttled_nodes)
{
setThrottleRate(node,true);
//TODO: need another state for throttled throttled_nodes
m_nodeStates[node] = NodeState.AlwaysThrottled;
Simulator.stats.always_throttle_time_bysrc[node].Add();
#if DEBUG_CLUSTER2
writeNode(node);
#endif
}
}
#if DEBUG_CLUSTER2
Console.Write("\n*NOT* Throttled nodes: ");
for(int i=0;i<Config.N;i++)
if(!m_isThrottled[i])
writeNode(i);
Console.Write("\n");
#endif
}
/* Need to have a better dostep function along with RR monitor phase.
* Also need to change setthrottle and dothrottle*/
public override void doStep()
{
//sampling period: Examine the network state and determine whether to throttle or not
if ( (Simulator.CurrentRound % (ulong)Config.throttle_sampling_period) == 0)
{
setThrottling();
lastNetUtil = Simulator.stats.netutil.Total;
resetStat();
}
//once throttle mode is turned on. Let each cluster run for a certain time interval
//to ensure fairness. Otherwise it's throttled most of the time.
if ((Simulator.CurrentRound % (ulong)Config.interval_length) == 0)
doThrottling();
}
public override void resetStat()
{
for (int i = 0; i < Config.N; i++)
{
num_ins_last_epoch[i] = (ulong)Simulator.stats.every_insns_persrc[i].Count;
L1misses[i]=0;
}
}
public override void setThrottling()
{
#if DEBUG_NETUTIL
Console.Write("\n:: cycle {0} ::",
Simulator.CurrentRound);
#endif
//get the MPKI value
for (int i = 0; i < Config.N; i++)
{
prev_MPKI[i]=MPKI[i];
if(num_ins_last_epoch[i]==0)
MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.every_insns_persrc[i].Count);
else
{
if(Simulator.stats.every_insns_persrc[i].Count-num_ins_last_epoch[i]>0)
MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.every_insns_persrc[i].Count-num_ins_last_epoch[i]);
else if(Simulator.stats.every_insns_persrc[i].Count-num_ins_last_epoch[i]==0)
MPKI[i]=0;
else
throw new Exception("MPKI error!");
}
}
recordStats();
double netutil=((double)(Simulator.stats.netutil.Total-lastNetUtil)/(double)Config.throttle_sampling_period);
#if DEBUG_NETUTIL
Console.WriteLine("\n*****avg netUtil = {0} TARGET at {1}",
netutil,Config.netutil_throttling_target);
#endif
/*
* 1.If the netutil remains high, lower the threshold value for each cluster
* to reduce the netutil further more and create a new pool/schedule for
* all the clusters. How to raise it back?
* Worst case: 1 app per cluster.
*
* 2.Find the difference b/w the current netutil and the threshold.
* Then increase the throttle rate for each cluster based on that difference.
*
* 3.maybe add stalling clusters?
* */
//un-throttle the network
for(int i=0;i<Config.N;i++)
setThrottleRate(i,false);
//Clear all the clusters
/*#if DEBUG_CLUSTER
Console.WriteLine("cycle {0} ___Clear clusters___",Simulator.CurrentRound);
#endif
cluster_pool.removeAllClusters();
throttled_cluster.removeAllNodes();
low_intensity_cluster.removeAllNodes();*/
double th_rate=Config.RR_throttle_rate;
double adjust_rate=0;
if(th_rate>=0 && th_rate<0.7)
adjust_rate=0.1;//10%
else if(th_rate<0.90)
adjust_rate=0.02;//2%
else
adjust_rate=0.01;//1%
if(netutil<Config.netutil_throttling_target)
{
if((th_rate-adjust_rate)>=0)
Config.RR_throttle_rate-=adjust_rate;
else
Config.RR_throttle_rate=0;
}
else
{
if((th_rate+adjust_rate)<=Config.max_throttle_rate)
Config.RR_throttle_rate+=adjust_rate;
else
Config.RR_throttle_rate=Config.max_throttle_rate;
}
if(Config.RR_throttle_rate<0 || Config.RR_throttle_rate>Config.max_throttle_rate)
throw new Exception("Throttle rate out of range (0 , max value)!!");
#if DEBUG_NETUTIL
Console.WriteLine("*****Adjusted throttle rate: {0}",Config.RR_throttle_rate);
#endif
Simulator.stats.total_th_rate.Add(Config.RR_throttle_rate);
#if DEBUG_CLUSTER
Console.WriteLine("cycle {0} ___Clear clusters___",Simulator.CurrentRound);
#endif
cluster_pool.removeAllClusters();
throttled_cluster.removeAllNodes();
low_intensity_cluster.removeAllNodes();
List<int> sortedList = new List<int>();
double total_mpki=0.0;
double small_mpki=0.0;
double current_allow=0.0;
int total_high=0;
for(int i=0;i<Config.N;i++)
{
sortedList.Add(i);
total_mpki+=MPKI[i];
//stats recording-see what's the total mpki composed by low/med apps
if(MPKI[i]<=30)
small_mpki+=MPKI[i];
}
//sort by mpki
sortedList.Sort(CompareByMpki);
#if DEBUG_CLUSTER
for(int i=0;i<Config.N;i++)
{
writeNode(sortedList[i]);
Console.WriteLine("-->MPKI:{0}",MPKI[sortedList[i]]);
}
Console.WriteLine("*****total MPKI: {0}",total_mpki);
Console.WriteLine("*****total MPKIs of apps with MPKI<30: {0}\n",small_mpki);
#endif
//find the first few apps that will be allowed to run freely without being throttled
for(int list_index=0;list_index<Config.N;list_index++)
{
int node_id=sortedList[list_index];
writeNode(node_id);
/*
* Low intensity cluster conditions:
* 1. filling enabled, then fill the low cluster up til free_total_mpki.
* 2. if filling not enabled, then apps with mpki lower than 'low_apps_mpki_thresh' will be put into the cluster.
* */
if((Config.free_total_MPKI>0 && (current_allow+MPKI[node_id]<=Config.free_total_MPKI) && Config.low_cluster_filling_enabled) ||
(!Config.low_cluster_filling_enabled && MPKI[node_id]<=Config.low_apps_mpki_thresh))
{
#if DEBUG_CLUSTER
Console.WriteLine("->Low node: {0}",node_id);
#endif
low_intensity_cluster.addNode(node_id,MPKI[node_id]);
current_allow+=MPKI[node_id];
Simulator.stats.low_cluster[node_id].Add();
continue;
}
else if(MPKI[node_id]>Config.cluster_MPKI_threshold && Config.always_cluster_enabled)
{
//If an application doesn't fit into one cluster, it will always be throttled
#if DEBUG_CLUSTER
Console.WriteLine("->Throttled node: {0}",node_id);
#endif
throttled_cluster.addNode(node_id,MPKI[node_id]);
Simulator.stats.high_cluster[node_id].Add();
total_high++;
}
else
{
#if DEBUG_CLUSTER
Console.WriteLine("->High node: {0}",node_id);
#endif
cluster_pool.addNewNode(node_id,MPKI[node_id]);
Simulator.stats.rr_cluster[node_id].Add();
total_high++;
}
}
//randomly start a cluster to begin with instead of always the first one
cluster_pool.randClusterId();
#if DEBUG_CLUSTER
Console.WriteLine("total high: {0}",total_high);
Console.WriteLine("-->low cluster mpki: {0}",current_allow);
#endif
//STATS
Simulator.stats.allowed_sum_mpki.Add(current_allow);
Simulator.stats.total_sum_mpki.Add(total_mpki);
sortedList.Clear();
#if DEBUG_CLUSTER
cluster_pool.printClusterPool();
#endif
}
public int CompareByMpki(int x,int y)
{
if(MPKI[x]-MPKI[y]>0.0) return 1;
else if(MPKI[x]-MPKI[y]<0.0) return -1;
return 0;
}
}
//TODO;
public class HighAloneClusterPool: BatchClusterPool
{
public static double high_mpki_thresh=50;
public HighAloneClusterPool(double mpki_threshold)
:base(mpki_threshold)
{
_mpki_threshold=mpki_threshold;
q=new List<Cluster>();
nodes_pool=new List<int>();
_cluster_id=0;
}
public void addNewNodeUniform(int id, double mpki)
{
//TODO: add nodes to clusters. However, prevent
//app with mpki higher than high_mpki_thresh
//get into a cluster with ohter med/low apps.
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// Test class that verifies the integration with APM (Task => APM) section 2.5.11 in the TPL spec
// "Asynchronous Programming Model", or the "Begin/End" pattern
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using Xunit;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.Threading.Tasks.Tests
{
/// <summary>
/// A class that implements the APM pattern to ensure that TPL can support APM pattern
/// </summary>
public sealed class TaskAPMTests : IDisposable
{
/// <summary>
/// Used to indicate whether to test TPL's Task or Future functionality for the APM pattern
/// </summary>
private bool _hasReturnType;
/// <summary>
/// Used to synchronize between Main thread and async thread, by blocking the main thread until
/// the thread that invokes the TaskCompleted method via AsyncCallback finishes
/// </summary>
private ManualResetEvent _mre = new ManualResetEvent(false);
/// <summary>
/// The input value to LongTask<int>.DoTask/BeginDoTask
/// </summary>
private const int IntInput = 1000;
/// <summary>
/// The constant that defines the number of milliseconds to spinwait (to simulate work) in the LongTask class
/// </summary>
private const int LongTaskMilliseconds = 100;
[Theory]
[OuterLoop]
[InlineData(true)]
[InlineData(false)]
public void WaitUntilCompleteTechnique(bool hasReturnType)
{
_hasReturnType = hasReturnType;
LongTask longTask;
if (_hasReturnType)
longTask = new LongTask<int>(LongTaskMilliseconds);
else
longTask = new LongTask(LongTaskMilliseconds);
// Prove that the Wait-until-done technique works
IAsyncResult asyncResult = longTask.BeginDoTask(null, null);
longTask.EndDoTask(asyncResult);
AssertTaskCompleted(asyncResult);
Assert.False(asyncResult.CompletedSynchronously, "Should not have completed synchronously.");
}
[Theory]
[OuterLoop]
[InlineData(true)]
[InlineData(false)]
public void PollUntilCompleteTechnique(bool hasReturnType)
{
_hasReturnType = hasReturnType;
LongTask longTask;
if (_hasReturnType)
longTask = new LongTask<int>(LongTaskMilliseconds);
else
longTask = new LongTask(LongTaskMilliseconds);
IAsyncResult asyncResult = longTask.BeginDoTask(null, null);
var mres = new ManualResetEventSlim();
while (!asyncResult.IsCompleted)
{
mres.Wait(1);
}
AssertTaskCompleted(asyncResult);
Assert.False(asyncResult.CompletedSynchronously, "Should not have completed synchronously.");
}
[Theory]
[OuterLoop]
[InlineData(true)]
[InlineData(false)]
public void WaitOnAsyncWaitHandleTechnique(bool hasReturnType)
{
_hasReturnType = hasReturnType;
LongTask longTask;
if (_hasReturnType)
longTask = new LongTask<int>(LongTaskMilliseconds);
else
longTask = new LongTask(LongTaskMilliseconds);
IAsyncResult asyncResult = longTask.BeginDoTask(null, null);
asyncResult.AsyncWaitHandle.WaitOne();
AssertTaskCompleted(asyncResult);
Assert.False(asyncResult.CompletedSynchronously, "Should not have completed synchronously.");
}
[Theory]
[OuterLoop]
[InlineData(true)]
[InlineData(false)]
public void CallbackTechnique(bool hasReturnType)
{
_hasReturnType = hasReturnType;
LongTask longTask;
if (_hasReturnType)
longTask = new LongTask<int>(LongTaskMilliseconds);
else
longTask = new LongTask(LongTaskMilliseconds);
IAsyncResult asyncResult;
if (_hasReturnType)
asyncResult = ((LongTask<int>)longTask).BeginDoTask(IntInput, TaskCompleted, longTask);
else
asyncResult = longTask.BeginDoTask(TaskCompleted, longTask);
_mre.WaitOne(); //Block the main thread until async thread finishes executing the call back
AssertTaskCompleted(asyncResult);
Assert.False(asyncResult.CompletedSynchronously, "Should not have completed synchronously.");
}
/// <summary>
/// Method used by the callback implementation by the APM
/// </summary>
/// <param name="ar"></param>
private void TaskCompleted(IAsyncResult ar)
{
if (_hasReturnType)
{
LongTask<int> lt = (LongTask<int>)ar.AsyncState;
int retValue = lt.EndDoTask(ar);
if (retValue != IntInput)
Assert.True(false, string.Format("Mismatch: Return = {0} vs Expect = {1}", retValue, IntInput));
}
else
{
LongTask lt = (LongTask)ar.AsyncState;
lt.EndDoTask(ar);
}
_mre.Set();
}
/// <summary>
/// Assert that the IAsyncResult represent a completed Task
/// </summary>
private void AssertTaskCompleted(IAsyncResult ar)
{
Assert.True(ar.IsCompleted);
Assert.Equal(TaskStatus.RanToCompletion, ((Task)ar).Status);
}
public void Dispose()
{
_mre.Dispose();
}
}
/// <summary>
/// A dummy class that simulates a long running task that implements IAsyncResult methods
/// </summary>
public class LongTask
{
// Amount of time to SpinWait, in milliseconds.
protected readonly int _msWaitDuration;
public LongTask(int milliseconds)
{
_msWaitDuration = milliseconds;
}
// Synchronous version of time-consuming method
public void DoTask()
{
// Simulate time-consuming task
SpinWait.SpinUntil(() => false, _msWaitDuration);
}
// Asynchronous version of time-consuming method (Begin part)
public IAsyncResult BeginDoTask(AsyncCallback callback, object state)
{
// Create IAsyncResult object identifying the asynchronous operation
Task task = Task.Factory.StartNew(
delegate
{
DoTask(); //simulates workload
},
state);
if (callback != null)
{
task.ContinueWith(delegate
{
callback(task);
});
}
return task; // Return the IAsyncResult to the caller
}
// Asynchronous version of time-consuming method (End part)
public void EndDoTask(IAsyncResult asyncResult)
{
// We know that the IAsyncResult is really a Task object
Task task = (Task)asyncResult;
// Wait for operation to complete
task.Wait();
}
}
/// <summary>
/// A dummy class that simulates a long running Future that implements IAsyncResult methods
/// </summary>
public sealed class LongTask<T> : LongTask
{
public LongTask(int milliseconds)
: base(milliseconds)
{
}
// Synchronous version of time-consuming method
public T DoTask(T input)
{
SpinWait.SpinUntil(() => false, _msWaitDuration); // Simulate time-consuming task
return input; // Return some result, for now, just return the input
}
public IAsyncResult BeginDoTask(T input, AsyncCallback callback, object state)
{
// Create IAsyncResult object identifying the asynchronous operation
Task<T> task = Task<T>.Factory.StartNew(
delegate
{
return DoTask(input);
},
state);
task.ContinueWith(delegate
{
callback(task);
});
return task; // Return the IAsyncResult to the caller
}
// Asynchronous version of time-consuming method (End part)
public new T EndDoTask(IAsyncResult asyncResult)
{
// We know that the IAsyncResult is really a Task object
Task<T> task = (Task<T>)asyncResult;
// Return the result
return task.Result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace UnicornHack.Utils
{
/// <summary>
/// Implementation of a xorshift pseudo-random number generator with period 2^32-1.
/// </summary>
public class SimpleRandom : NotificationEntity
{
private const float IntToFloat = 1.0f / int.MaxValue;
public uint Seed { get; set; } = 1;
public int Roll(int diceCount, int diceSides)
{
var result = 0;
for (var i = 0; i < diceCount; i++)
{
result += Next(minValue: 0, maxValue: diceSides) + 1;
}
return result;
}
public TInput Pick<TInput>(IReadOnlyList<TInput> items) => items[Next(0, items.Count)];
public TInput Pick<TInput>(IReadOnlyList<TInput> items, Func<TInput, bool> condition) =>
!TryPick(items, condition, out var item)
? throw new InvalidOperationException("No elements meet the condition")
: item;
public TInput TryPick<TInput>(IReadOnlyList<TInput> items) => items[Next(0, items.Count)];
public bool TryPick<TInput>(IReadOnlyList<TInput> items, Func<TInput, bool> condition, out TInput item)
{
var index = Next(0, items.Count);
for (var i = index; i < items.Count; i++)
{
item = items[i];
if (condition(item))
{
return true;
}
}
for (var i = 0; i < index; i++)
{
item = items[i];
if (condition(item))
{
return true;
}
}
item = default;
return false;
}
public TInput Pick<TInput>(IReadOnlyList<TInput> items, Func<TInput, float> getWeight) =>
WeightedOrder(items, getWeight).First();
public TResult Pick<TInput, TResult>(IReadOnlyList<TInput> items, Func<TInput, float> getWeight,
Func<TInput, int, TResult> selector) => WeightedOrder(items, getWeight, selector).First();
public IEnumerable<TInput> WeightedOrder<TInput>(IReadOnlyList<TInput> items,
Func<TInput, float> getWeight) => WeightedOrder(items, getWeight, (item, index) => item);
public IEnumerable<TResult> WeightedOrder<TInput, TResult>(IReadOnlyList<TInput> items,
Func<TInput, float> getWeight, Func<TInput, int, TResult> selector)
{
if (items == null || items.Count == 0)
{
yield break;
}
var cumulativeWeights = new float[items.Count];
var sum = 0f;
var indexToProcess = 0;
while (true)
{
var selectedIndex = -1;
for (; indexToProcess < items.Count; indexToProcess++)
{
var item = items[indexToProcess];
var weight = getWeight(item);
if (float.IsPositiveInfinity(weight))
{
selectedIndex = indexToProcess;
break;
}
if (weight < 0)
{
weight = 0;
}
sum += weight;
cumulativeWeights[indexToProcess] = sum;
}
if (selectedIndex == -1)
{
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (sum == 0)
{
yield break;
}
selectedIndex = BinarySearch(cumulativeWeights, Next(0, sum));
}
yield return selector(items[selectedIndex], selectedIndex);
var selectedWeight = cumulativeWeights[selectedIndex];
if (selectedIndex > 0)
{
selectedWeight = selectedWeight - cumulativeWeights[selectedIndex - 1];
}
if (selectedIndex == indexToProcess)
{
cumulativeWeights[indexToProcess] = sum;
indexToProcess++;
}
else
{
for (var i = selectedIndex; i < items.Count; i++)
{
cumulativeWeights[i] -= selectedWeight;
}
}
sum -= selectedWeight;
}
}
private static int BinarySearch(float[] numbers, float target)
{
Debug.Assert(numbers.Length > 0);
var first = 0;
var last = numbers.Length - 1;
while (first < last)
{
var midPoint = (first + last) / 2;
var midValue = numbers[midPoint];
// ReSharper disable once CompareOfFloatsByEqualityOperator
if (target > midValue)
{
first = midPoint + 1;
}
else if (target < midValue)
{
last = midPoint;
}
else
{
break;
}
}
// ReSharper disable once CompareOfFloatsByEqualityOperator
while (first < numbers.Length && numbers[first] == 0)
{
first++;
}
// ReSharper disable once CompareOfFloatsByEqualityOperator
while (first > 0 && target == numbers[first - 1])
{
first--;
}
return first == numbers.Length ? first - 1 : first;
}
/// <summary>
/// Returns a random number in the range [0, <paramref name="maxValue" />)
/// </summary>
public int Next(int maxValue) => Next(minValue: 0, maxValue);
/// <summary>
/// Returns a random number in the range [<paramref name="minValue" />, <paramref name="maxValue" />)
/// </summary>
public int Next(int minValue, int maxValue) => (int)Next(minValue, (float)maxValue);
public float Next(float minValue, float maxValue)
{
if (minValue >= maxValue)
{
throw new ArgumentOutOfRangeException();
}
var range = maxValue - minValue;
if (range > int.MaxValue || range < 0)
{
throw new ArgumentOutOfRangeException($"Don't use this generator for ranges over {int.MaxValue}");
}
if (range == 0)
{
return minValue;
}
return minValue + IntToFloat * NextInt() * range;
}
private int NextInt() => (int)(int.MaxValue & NextUInt());
/// <summary>
/// Generates <paramref name="n" /> random numbers and returns how many of them were smaller than <paramref name="p" />
/// </summary>
/// <param name="p"> A number between 0 and 1 </param>
/// <param name="n"> The number of numbers to generate </param>
/// <returns></returns>
public int NextBinomial(float p, int n)
{
var successes = 0;
for (var i = 0; i < n; i++)
{
if (Next(0, 1f) <= p)
{
successes++;
}
}
return successes;
}
private uint NextUInt()
{
Seed ^= Seed << 13;
Seed ^= Seed >> 17;
Seed ^= Seed << 5;
return Seed;
}
public bool NextBool() => (0x80000000 & NextUInt()) == 0;
private const int BoolSeedMask = 0x000000FF;
private const int PositiveStreakShift = 8;
private const int PositiveStreakMask = 0x0000FF00;
private const int NegativeStreakShift = 16;
private const int NegativeStreakMask = 0x00FF0000;
private const int InitializedFlag = 0x01000000;
/// <summary>
/// Returns a random bool with the given <paramref name="successProbability" /> without any streaks
/// longer than ((100 / p) - 1) * 2 and with no predictable order.
/// </summary>
/// <param name="successProbability">Percent of expected <c>true</c> results.</param>
/// <param name="entropyState">State for streak-breaking.</param>
/// <returns> A random bool. </returns>
public virtual bool NextBool(int successProbability, ref int entropyState)
{
if (successProbability < 0
|| successProbability > 100)
{
throw new ArgumentOutOfRangeException(nameof(successProbability));
}
switch (successProbability)
{
case 0:
return false;
case 100:
return true;
}
var positiveStreak = (entropyState & PositiveStreakMask) >> PositiveStreakShift;
var negativeStreak = (entropyState & NegativeStreakMask) >> NegativeStreakShift;
var seed = entropyState & BoolSeedMask;
if (entropyState == 0)
{
positiveStreak = Next(100);
negativeStreak = Next(100);
seed = Next(100);
}
if (positiveStreak < 100)
{
positiveStreak += successProbability;
}
if (negativeStreak < 100)
{
negativeStreak += 100 - successProbability;
}
seed += successProbability;
var result = seed >= 100;
if (positiveStreak >= 100
&& negativeStreak >= 100)
{
positiveStreak = 0;
negativeStreak = 0;
seed = Next(100);
}
else if (result)
{
seed -= 100;
}
entropyState = seed
| (positiveStreak << PositiveStreakShift)
| (negativeStreak << NegativeStreakShift)
| InitializedFlag;
return result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using Funq;
using NUnit.Framework;
using ServiceStack.Common.Web;
using ServiceStack.ServiceClient.Web;
using ServiceStack.FluentValidation;
using ServiceStack.Service;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using ServiceStack.ServiceInterface.ServiceModel;
using ServiceStack.ServiceInterface.Validation;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints;
using ServiceStack.WebHost.Endpoints.Support;
using ServiceStack.WebHost.Endpoints.Tests;
using ServiceStack.WebHost.Endpoints.Tests.Support;
using ServiceStack.WebHost.Endpoints.Tests.Support.Host;
namespace ServiceStack.WebHost.IntegrationTests.Services
{
[Route("/customers")]
[Route("/customers/{Id}")]
public class Customers
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
public decimal Discount { get; set; }
public string Address { get; set; }
public string Postcode { get; set; }
public bool HasDiscount { get; set; }
}
public interface IAddressValidator
{
bool ValidAddress(string address);
}
public class AddressValidator : IAddressValidator
{
public bool ValidAddress(string address)
{
return address != null
&& address.Length >= 20
&& address.Length <= 250;
}
}
public class CustomersValidator : AbstractValidator<Customers>
{
public IAddressValidator AddressValidator { get; set; }
public CustomersValidator()
{
RuleFor(x => x.Id).NotEqual(default(int));
RuleSet(ApplyTo.Post | ApplyTo.Put, () => {
RuleFor(x => x.LastName).NotEmpty().WithErrorCode("ShouldNotBeEmpty");
RuleFor(x => x.FirstName).NotEmpty().WithMessage("Please specify a first name");
RuleFor(x => x.Company).NotNull();
RuleFor(x => x.Discount).NotEqual(0).When(x => x.HasDiscount);
RuleFor(x => x.Address).Must(x => AddressValidator.ValidAddress(x));
RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
});
}
static readonly Regex UsPostCodeRegEx = new Regex(@"^\d{5}(-\d{4})?$", RegexOptions.Compiled);
private bool BeAValidPostcode(string postcode)
{
return !string.IsNullOrEmpty(postcode) && UsPostCodeRegEx.IsMatch(postcode);
}
}
public class CustomersResponse
{
public Customers Result { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
[DefaultRequest(typeof(Customers))]
public class CustomerService : ServiceInterface.Service
{
public object Get(Customers request)
{
return new CustomersResponse { Result = request };
}
public object Post(Customers request)
{
return new CustomersResponse { Result = request };
}
public object Put(Customers request)
{
return new CustomersResponse { Result = request };
}
public object Delete(Customers request)
{
return new CustomersResponse { Result = request };
}
}
[TestFixture]
public class CustomerServiceValidationTests
{
private const string ListeningOn = "http://localhost:82/";
public class ValidationAppHostHttpListener
: AppHostHttpListenerBase
{
public ValidationAppHostHttpListener()
: base("Validation Tests", typeof(CustomerService).Assembly) { }
public override void Configure(Container container)
{
Plugins.Add(new ValidationFeature());
container.Register<IAddressValidator>(new AddressValidator());
container.RegisterValidators(typeof(CustomersValidator).Assembly);
}
}
ValidationAppHostHttpListener appHost;
[TestFixtureSetUp]
public void OnTestFixtureSetUp()
{
appHost = new ValidationAppHostHttpListener();
appHost.Init();
appHost.Start(ListeningOn);
}
[TestFixtureTearDown]
public void OnTestFixtureTearDown()
{
appHost.Dispose();
EndpointHandlerBase.ServiceManager = null;
}
private static List<ResponseError> GetValidationFieldErrors(string httpMethod, Customers request)
{
var validator = (IValidator)new CustomersValidator {
AddressValidator = new AddressValidator()
};
var validationResult = validator.Validate(
new ValidationContext(request, null, new MultiRuleSetValidatorSelector(httpMethod)));
var responseStatus = validationResult.ToErrorResult().ToResponseStatus();
var errorFields = responseStatus.Errors;
return errorFields ?? new List<ResponseError>();
}
private string[] ExpectedPostErrorFields = new[] {
"Id",
"LastName",
"FirstName",
"Company",
"Address",
"Postcode",
};
private string[] ExpectedPostErrorCodes = new[] {
"NotEqual",
"ShouldNotBeEmpty",
"NotEmpty",
"NotNull",
"Predicate",
"Predicate",
};
Customers validRequest;
[SetUp]
public void SetUp()
{
validRequest = new Customers {
Id = 1,
FirstName = "FirstName",
LastName = "LastName",
Address = "12345 Address St, New York",
Company = "Company",
Discount = 10,
HasDiscount = true,
Postcode = "11215",
};
}
[Test]
public void ValidationFeature_add_request_filter_once()
{
var old = appHost.RequestFilters.Count;
appHost.LoadPlugin(new ValidationFeature());
Assert.That(old, Is.EqualTo(appHost.RequestFilters.Count));
}
[Test]
public void Validates_ValidRequest_request_on_Post()
{
var errorFields = GetValidationFieldErrors(HttpMethods.Post, validRequest);
Assert.That(errorFields.Count, Is.EqualTo(0));
}
[Test]
public void Validates_ValidRequest_request_on_Get()
{
var errorFields = GetValidationFieldErrors(HttpMethods.Get, validRequest);
Assert.That(errorFields.Count, Is.EqualTo(0));
}
[Test]
public void Validates_Conditional_Request_request_on_Post()
{
validRequest.Discount = 0;
validRequest.HasDiscount = true;
var errorFields = GetValidationFieldErrors(HttpMethods.Post, validRequest);
Assert.That(errorFields.Count, Is.EqualTo(1));
Assert.That(errorFields[0].FieldName, Is.EqualTo("Discount"));
}
[Test]
public void Validates_empty_request_on_Post()
{
var request = new Customers();
var errorFields = GetValidationFieldErrors(HttpMethods.Post, request);
var fieldNames = errorFields.Select(x => x.FieldName).ToArray();
var fieldErrorCodes = errorFields.Select(x => x.ErrorCode).ToArray();
Assert.That(errorFields.Count, Is.EqualTo(ExpectedPostErrorFields.Length));
Assert.That(fieldNames, Is.EquivalentTo(ExpectedPostErrorFields));
Assert.That(fieldErrorCodes, Is.EquivalentTo(ExpectedPostErrorCodes));
}
[Test]
public void Validates_empty_request_on_Put()
{
var request = new Customers();
var errorFields = GetValidationFieldErrors(HttpMethods.Put, request);
var fieldNames = errorFields.Select(x => x.FieldName).ToArray();
var fieldErrorCodes = errorFields.Select(x => x.ErrorCode).ToArray();
Assert.That(errorFields.Count, Is.EqualTo(ExpectedPostErrorFields.Length));
Assert.That(fieldNames, Is.EquivalentTo(ExpectedPostErrorFields));
Assert.That(fieldErrorCodes, Is.EquivalentTo(ExpectedPostErrorCodes));
}
[Test]
public void Validates_empty_request_on_Get()
{
var request = new Customers();
var errorFields = GetValidationFieldErrors(HttpMethods.Get, request);
Assert.That(errorFields.Count, Is.EqualTo(1));
Assert.That(errorFields[0].ErrorCode, Is.EqualTo("NotEqual"));
Assert.That(errorFields[0].FieldName, Is.EqualTo("Id"));
}
[Test]
public void Validates_empty_request_on_Delete()
{
var request = new Customers();
var errorFields = GetValidationFieldErrors(HttpMethods.Delete, request);
Assert.That(errorFields.Count, Is.EqualTo(1));
Assert.That(errorFields[0].ErrorCode, Is.EqualTo("NotEqual"));
Assert.That(errorFields[0].FieldName, Is.EqualTo("Id"));
}
protected static IServiceClient UnitTestServiceClient()
{
EndpointHandlerBase.ServiceManager = new ServiceManager(typeof(SecureService).Assembly).Init();
return new DirectServiceClient(EndpointHandlerBase.ServiceManager);
}
public static IEnumerable ServiceClients
{
get
{
//Seriously retarded workaround for some devs idea who thought this should
//be run for all test fixtures, not just this one.
return new Func<IServiceClient>[] {
() => UnitTestServiceClient(),
() => new JsonServiceClient(ListeningOn),
() => new JsvServiceClient(ListeningOn),
() => new XmlServiceClient(ListeningOn),
};
}
}
[Test, TestCaseSource(typeof(CustomerServiceValidationTests), "ServiceClients")]
public void Post_empty_request_throws_validation_exception(Func<IServiceClient> factory)
{
try
{
var client = factory();
var response = client.Send<CustomersResponse>(new Customers());
Assert.Fail("Should throw Validation Exception");
}
catch (WebServiceException ex)
{
var response = (CustomersResponse)ex.ResponseDto;
var errorFields = response.ResponseStatus.Errors;
var fieldNames = errorFields.Select(x => x.FieldName).ToArray();
var fieldErrorCodes = errorFields.Select(x => x.ErrorCode).ToArray();
Assert.That(ex.StatusCode, Is.EqualTo((int)HttpStatusCode.BadRequest));
Assert.That(errorFields.Count, Is.EqualTo(ExpectedPostErrorFields.Length));
Assert.That(fieldNames, Is.EquivalentTo(ExpectedPostErrorFields));
Assert.That(fieldErrorCodes, Is.EquivalentTo(ExpectedPostErrorCodes));
}
}
[Test, TestCaseSource(typeof(CustomerServiceValidationTests), "ServiceClients")]
public void Get_empty_request_throws_validation_exception(Func<IServiceClient> factory)
{
try
{
var client = (IRestClient)factory();
var response = client.Get<CustomersResponse>("Customers");
Assert.Fail("Should throw Validation Exception");
}
catch (WebServiceException ex)
{
var response = (CustomersResponse)ex.ResponseDto;
var errorFields = response.ResponseStatus.Errors;
Assert.That(ex.StatusCode, Is.EqualTo((int)HttpStatusCode.BadRequest));
Assert.That(errorFields.Count, Is.EqualTo(1));
Assert.That(errorFields[0].ErrorCode, Is.EqualTo("NotEqual"));
Assert.That(errorFields[0].FieldName, Is.EqualTo("Id"));
}
}
[Test, TestCaseSource(typeof(CustomerServiceValidationTests), "ServiceClients")]
public void Post_ValidRequest_succeeds(Func<IServiceClient> factory)
{
var client = factory();
var response = client.Send<CustomersResponse>(validRequest);
Assert.That(response.ResponseStatus, Is.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.Runtime;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System
{
public static class Buffer
{
public static unsafe void BlockCopy(Array src, int srcOffset,
Array dst, int dstOffset,
int count)
{
if (src == null)
throw new ArgumentNullException("src");
if (dst == null)
throw new ArgumentNullException("dst");
RuntimeImports.RhCorElementTypeInfo srcCorElementTypeInfo = src.ElementEEType.CorElementTypeInfo;
nuint uSrcLen = ((nuint)src.Length) << srcCorElementTypeInfo.Log2OfSize;
nuint uDstLen = uSrcLen;
if (!srcCorElementTypeInfo.IsPrimitive)
throw new ArgumentException(SR.Arg_MustBePrimArray, "src");
if (src != dst)
{
RuntimeImports.RhCorElementTypeInfo dstCorElementTypeInfo = dst.ElementEEType.CorElementTypeInfo;
if (!dstCorElementTypeInfo.IsPrimitive)
throw new ArgumentException(SR.Arg_MustBePrimArray, "dst");
uDstLen = ((nuint)dst.Length) << dstCorElementTypeInfo.Log2OfSize;
}
if (srcOffset < 0)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_MustBeNonNegInt32, "srcOffset");
if (dstOffset < 0)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_MustBeNonNegInt32, "dstOffset");
if (count < 0)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_MustBeNonNegInt32, "count");
nuint uCount = (nuint)count;
if (uSrcLen < ((nuint)srcOffset) + uCount)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (uDstLen < ((nuint)dstOffset) + uCount)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (uCount == 0)
return;
fixed (IntPtr* pSrcObj = &src.m_pEEType, pDstObj = &dst.m_pEEType)
{
byte* pSrc = (byte*)Array.GetAddrOfPinnedArrayFromEETypeField(pSrcObj) + srcOffset;
byte* pDst = (byte*)Array.GetAddrOfPinnedArrayFromEETypeField(pDstObj) + dstOffset;
Buffer.Memmove(pDst, pSrc, uCount);
}
}
// This is ported from the optimized CRT assembly in memchr.asm. The JIT generates
// pretty good code here and this ends up being within a couple % of the CRT asm.
// It is however cross platform as the CRT hasn't ported their fast version to 64-bit
// platforms.
//
internal unsafe static int IndexOfByte(byte* src, byte value, int index, int count)
{
byte* pByte = src + index;
// Align up the pointer to sizeof(int).
while (((int)pByte & 3) != 0)
{
if (count == 0)
return -1;
else if (*pByte == value)
return (int)(pByte - src);
count--;
pByte++;
}
// Fill comparer with value byte for comparisons
//
// comparer = 0/0/value/value
uint comparer = (((uint)value << 8) + (uint)value);
// comparer = value/value/value/value
comparer = (comparer << 16) + comparer;
// Run through buffer until we hit a 4-byte section which contains
// the byte we're looking for or until we exhaust the buffer.
while (count > 3)
{
// Test the buffer for presence of value. comparer contains the byte
// replicated 4 times.
uint t1 = *(uint*)pByte;
t1 = t1 ^ comparer;
uint t2 = 0x7efefeff + t1;
t1 = t1 ^ 0xffffffff;
t1 = t1 ^ t2;
t1 = t1 & 0x81010100;
// if t1 is zero then these 4-bytes don't contain a match
if (t1 != 0)
{
// We've found a match for value, figure out which position it's in.
int foundIndex = (int)(pByte - src);
if (pByte[0] == value)
return foundIndex;
else if (pByte[1] == value)
return foundIndex + 1;
else if (pByte[2] == value)
return foundIndex + 2;
else if (pByte[3] == value)
return foundIndex + 3;
}
count -= 4;
pByte += 4;
}
// Catch any bytes that might be left at the tail of the buffer
while (count > 0)
{
if (*pByte == value)
return (int)(pByte - src);
count--;
pByte++;
}
// If we don't have a match return -1;
return -1;
}
internal unsafe static void ZeroMemory(byte* src, long len)
{
while (len-- > 0)
*(src + len) = 0;
}
public static int ByteLength(Array array)
{
// Is the array present?
if (array == null)
throw new ArgumentNullException("array");
// Is it of primitive types?
if (!array.ElementEEType.IsPrimitive)
throw new ArgumentException(SR.Arg_MustBePrimArray, "array");
return _ByteLength(array);
}
private static unsafe int _ByteLength(Array array)
{
return checked(array.Length * array.EETypePtr.ComponentSize);
}
public static unsafe byte GetByte(Array array, int index)
{
// Is the array present?
if (array == null)
throw new ArgumentNullException("array");
// Is it of primitive types?
if (!array.ElementEEType.IsPrimitive)
throw new ArgumentException(SR.Arg_MustBePrimArray, "array");
// Is the index in valid range of the array?
if (index < 0 || index >= _ByteLength(array))
throw new ArgumentOutOfRangeException("index");
fixed (IntPtr* pObj = &array.m_pEEType)
{
byte* pByte = (byte*)Array.GetAddrOfPinnedArrayFromEETypeField(pObj) + index;
return *pByte;
}
}
public static unsafe void SetByte(Array array, int index, byte value)
{
// Is the array present?
if (array == null)
throw new ArgumentNullException("array");
// Is it of primitive types?
if (!array.ElementEEType.IsPrimitive)
throw new ArgumentException(SR.Arg_MustBePrimArray, "array");
// Is the index in valid range of the array?
if (index < 0 || index >= _ByteLength(array))
throw new ArgumentOutOfRangeException("index");
fixed (IntPtr* pObj = &array.m_pEEType)
{
byte* pByte = (byte*)Array.GetAddrOfPinnedArrayFromEETypeField(pObj) + index;
*pByte = value;
}
}
// The attributes on this method are chosen for best JIT performance.
// Please do not edit unless intentional.
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
[CLSCompliant(false)]
public static unsafe void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy)
{
if (sourceBytesToCopy > destinationSizeInBytes)
{
throw new ArgumentOutOfRangeException("sourceBytesToCopy");
}
Memmove((byte*)destination, (byte*)source, checked((nuint)sourceBytesToCopy));
}
// The attributes on this method are chosen for best JIT performance.
// Please do not edit unless intentional.
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
[CLSCompliant(false)]
public static unsafe void MemoryCopy(void* source, void* destination, ulong destinationSizeInBytes, ulong sourceBytesToCopy)
{
if (sourceBytesToCopy > destinationSizeInBytes)
{
throw new ArgumentOutOfRangeException("sourceBytesToCopy");
}
Memmove((byte*)destination, (byte*)source, checked((nuint)sourceBytesToCopy));
}
internal unsafe static void Memmove(byte* dest, byte* src, nuint len)
{
// P/Invoke into the native version when the buffers are overlapping and the copy needs to be performed backwards
// This check can produce false positives for lengths greater than Int32.MaxInt. It is fine because we want to use PInvoke path for the large lengths anyway.
if ((nuint)dest - (nuint)src < len)
{
_Memmove(dest, src, len);
return;
}
//
// This is portable version of memcpy. It mirrors what the hand optimized assembly versions of memcpy typically do.
//
#if ALIGN_ACCESS
#error Needs porting for ALIGN_ACCESS (https://github.com/dotnet/corert/issues/430)
#else // ALIGN_ACCESS
switch (len)
{
case 0:
return;
case 1:
*dest = *src;
return;
case 2:
*(short*)dest = *(short*)src;
return;
case 3:
*(short*)dest = *(short*)src;
*(dest + 2) = *(src + 2);
return;
case 4:
*(int*)dest = *(int*)src;
return;
case 5:
*(int*)dest = *(int*)src;
*(dest + 4) = *(src + 4);
return;
case 6:
*(int*)dest = *(int*)src;
*(short*)(dest + 4) = *(short*)(src + 4);
return;
case 7:
*(int*)dest = *(int*)src;
*(short*)(dest + 4) = *(short*)(src + 4);
*(dest + 6) = *(src + 6);
return;
case 8:
#if BIT64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
return;
case 9:
#if BIT64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(dest + 8) = *(src + 8);
return;
case 10:
#if BIT64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(short*)(dest + 8) = *(short*)(src + 8);
return;
case 11:
#if BIT64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(short*)(dest + 8) = *(short*)(src + 8);
*(dest + 10) = *(src + 10);
return;
case 12:
#if BIT64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(int*)(dest + 8) = *(int*)(src + 8);
return;
case 13:
#if BIT64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(int*)(dest + 8) = *(int*)(src + 8);
*(dest + 12) = *(src + 12);
return;
case 14:
#if BIT64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(int*)(dest + 8) = *(int*)(src + 8);
*(short*)(dest + 12) = *(short*)(src + 12);
return;
case 15:
#if BIT64
*(long*)dest = *(long*)src;
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
#endif
*(int*)(dest + 8) = *(int*)(src + 8);
*(short*)(dest + 12) = *(short*)(src + 12);
*(dest + 14) = *(src + 14);
return;
case 16:
#if BIT64
*(long*)dest = *(long*)src;
*(long*)(dest + 8) = *(long*)(src + 8);
#else
*(int*)dest = *(int*)src;
*(int*)(dest + 4) = *(int*)(src + 4);
*(int*)(dest + 8) = *(int*)(src + 8);
*(int*)(dest + 12) = *(int*)(src + 12);
#endif
return;
default:
break;
}
// P/Invoke into the native version for large lengths.
if (len >= 200)
{
_Memmove(dest, src, len);
return;
}
if (((int)dest & 3) != 0)
{
if (((int)dest & 1) != 0)
{
*dest = *src;
src++;
dest++;
len--;
if (((int)dest & 2) == 0)
goto Aligned;
}
*(short*)dest = *(short*)src;
src += 2;
dest += 2;
len -= 2;
Aligned:;
}
#if BIT64
if (((int)dest & 4) != 0)
{
*(int*)dest = *(int*)src;
src += 4;
dest += 4;
len -= 4;
}
#endif
nuint count = len / 16;
while (count > 0)
{
#if BIT64
((long*)dest)[0] = ((long*)src)[0];
((long*)dest)[1] = ((long*)src)[1];
#else
((int*)dest)[0] = ((int*)src)[0];
((int*)dest)[1] = ((int*)src)[1];
((int*)dest)[2] = ((int*)src)[2];
((int*)dest)[3] = ((int*)src)[3];
#endif
dest += 16;
src += 16;
count--;
}
if ((len & 8) != 0)
{
#if BIT64
((long*)dest)[0] = ((long*)src)[0];
#else
((int*)dest)[0] = ((int*)src)[0];
((int*)dest)[1] = ((int*)src)[1];
#endif
dest += 8;
src += 8;
}
if ((len & 4) != 0)
{
((int*)dest)[0] = ((int*)src)[0];
dest += 4;
src += 4;
}
if ((len & 2) != 0)
{
((short*)dest)[0] = ((short*)src)[0];
dest += 2;
src += 2;
}
if ((len & 1) != 0)
*dest = *src;
#endif // ALIGN_ACCESS
}
// Non-inlinable wrapper around the QCall that avoids poluting the fast path
// with P/Invoke prolog/epilog.
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private unsafe static void _Memmove(byte* dest, byte* src, nuint len)
{
RuntimeImports.memmove(dest, src, len);
}
}
}
| |
// 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.Globalization;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.IO;
using Microsoft.Build.Internal;
using Microsoft.Build.Shared;
using BuildParameters = Microsoft.Build.Execution.BuildParameters;
using NodeEngineShutdownReason = Microsoft.Build.Execution.NodeEngineShutdownReason;
namespace Microsoft.Build.BackEnd
{
/// <summary>
/// An implementation of a node provider for in-proc nodes.
/// </summary>
internal class NodeProviderInProc : INodeProvider, INodePacketFactory, IDisposable
{
#region Private Data
/// <summary>
/// The invalid in-proc node id
/// </summary>
private const int InvalidInProcNodeId = 0;
/// <summary>
/// Flag indicating we have disposed.
/// </summary>
private bool _disposed = false;
/// <summary>
/// Value used to ensure multiple in-proc nodes which save the operating environment are not created.
/// </summary>
private static Semaphore InProcNodeOwningOperatingEnvironment;
/// <summary>
/// The component host.
/// </summary>
private IBuildComponentHost _componentHost;
/// <summary>
/// The in-proc node.
/// </summary>
private INode _inProcNode;
/// <summary>
/// The in-proc node endpoint.
/// </summary>
private INodeEndpoint _inProcNodeEndpoint;
/// <summary>
/// The packet factory used to route packets from the node.
/// </summary>
private INodePacketFactory _packetFactory;
/// <summary>
/// The in-proc node thread.
/// </summary>
private Thread _inProcNodeThread;
/// <summary>
/// Event which is raised when the in-proc endpoint is connected.
/// </summary>
private AutoResetEvent _endpointConnectedEvent;
/// <summary>
/// The ID of the in-proc node.
/// </summary>
private int _inProcNodeId = InvalidInProcNodeId;
/// <summary>
/// Check to allow the inproc node to have exclusive ownership of the operating environment
/// </summary>
private bool _exclusiveOperatingEnvironment = false;
#endregion
#region Constructor
/// <summary>
/// Initializes the node provider.
/// </summary>
public NodeProviderInProc()
{
_endpointConnectedEvent = new AutoResetEvent(false);
}
#endregion
/// <summary>
/// Finalizer
/// </summary>
~NodeProviderInProc()
{
Dispose(false /* disposing */);
}
/// <summary>
/// Returns the type of nodes managed by this provider.
/// </summary>
public NodeProviderType ProviderType
{
get { return NodeProviderType.InProc; }
}
/// <summary>
/// Returns the number of nodes available to create on this provider.
/// </summary>
public int AvailableNodes
{
get
{
if (_inProcNodeId != InvalidInProcNodeId)
{
return 0;
}
return 1;
}
}
#region IBuildComponent Members
/// <summary>
/// Sets the build component host.
/// </summary>
/// <param name="host">The component host.</param>
public void InitializeComponent(IBuildComponentHost host)
{
_componentHost = host;
}
/// <summary>
/// Shuts down this component.
/// </summary>
public void ShutdownComponent()
{
_componentHost = null;
_inProcNode = null;
}
#endregion
#region INodeProvider Members
/// <summary>
/// Sends data to the specified node.
/// </summary>
/// <param name="nodeId">The node to which data should be sent.</param>
/// <param name="packet">The data to send.</param>
public void SendData(int nodeId, INodePacket packet)
{
ErrorUtilities.VerifyThrowArgumentOutOfRange(nodeId == _inProcNodeId, "node");
ErrorUtilities.VerifyThrowArgumentNull(packet, "packet");
if (null == _inProcNode)
{
return;
}
_inProcNodeEndpoint.SendData(packet);
}
/// <summary>
/// Causes all connected nodes to be shut down.
/// </summary>
/// <param name="enableReuse">Flag indicating if the nodes should prepare for reuse.</param>
public void ShutdownConnectedNodes(bool enableReuse)
{
if (null != _inProcNode)
{
_inProcNodeEndpoint.SendData(new NodeBuildComplete(enableReuse));
}
}
/// <summary>
/// Causes all nodes to be shut down permanently - for InProc nodes it is the same as ShutdownConnectedNodes
/// with enableReuse = false
/// </summary>
public void ShutdownAllNodes()
{
ShutdownConnectedNodes(false /* no node reuse */);
}
/// <summary>
/// Requests that a node be created on the specified machine.
/// </summary>
/// <param name="nodeId">The id of the node to create.</param>
/// <param name="factory">The factory to use to create packets from this node.</param>
/// <param name="configuration">The configuration for the node.</param>
public bool CreateNode(int nodeId, INodePacketFactory factory, NodeConfiguration configuration)
{
ErrorUtilities.VerifyThrow(nodeId != InvalidInProcNodeId, "Cannot create in-proc node.");
// Attempt to get the operating environment semaphore if requested.
if (_componentHost.BuildParameters.SaveOperatingEnvironment)
{
// We can only create additional in-proc nodes if we have decided not to save the operating environment. This is the global
// DTAR case in Visual Studio, but other clients might enable this as well under certain special circumstances.
if (Environment.GetEnvironmentVariable("MSBUILDINPROCENVCHECK") == "1")
{
_exclusiveOperatingEnvironment = true;
}
if (_exclusiveOperatingEnvironment)
{
if (InProcNodeOwningOperatingEnvironment == null)
{
InProcNodeOwningOperatingEnvironment = new Semaphore(1, 1);
}
if (!InProcNodeOwningOperatingEnvironment.WaitOne(0))
{
// Can't take the operating environment.
return false;
}
}
}
// If it doesn't already exist, create it.
if (_inProcNode == null)
{
if (!InstantiateNode(factory))
{
return false;
}
}
_inProcNodeEndpoint.SendData(configuration);
_inProcNodeId = nodeId;
return true;
}
#endregion
#region INodePacketFactory Members
/// <summary>
/// Registers a packet handler. Not used in the in-proc node.
/// </summary>
public void RegisterPacketHandler(NodePacketType packetType, NodePacketFactoryMethod factory, INodePacketHandler handler)
{
// Not used
ErrorUtilities.ThrowInternalErrorUnreachable();
}
/// <summary>
/// Unregisters a packet handler. Not used in the in-proc node.
/// </summary>
public void UnregisterPacketHandler(NodePacketType packetType)
{
// Not used
ErrorUtilities.ThrowInternalErrorUnreachable();
}
/// <summary>
/// Deserializes and routes a packet. Not used in the in-proc node.
/// </summary>
public void DeserializeAndRoutePacket(int nodeId, NodePacketType packetType, ITranslator translator)
{
// Not used
ErrorUtilities.ThrowInternalErrorUnreachable();
}
/// <summary>
/// Routes a packet.
/// </summary>
/// <param name="nodeId">The id of the node from which the packet is being routed.</param>
/// <param name="packet">The packet to route.</param>
public void RoutePacket(int nodeId, INodePacket packet)
{
INodePacketFactory factory = _packetFactory;
if (_inProcNodeId != InvalidInProcNodeId)
{
// If this was a shutdown packet, we are done with the node. Release all context associated with it. Do this here, rather
// than after we route the packet, because otherwise callbacks to the NodeManager to determine if we have available nodes
// will report that the in-proc node is still in use when it has actually shut down.
int savedInProcNodeId = _inProcNodeId;
if (packet.Type == NodePacketType.NodeShutdown)
{
_inProcNodeId = InvalidInProcNodeId;
// Release the operating environment semaphore if we were holding it.
if ((_componentHost.BuildParameters.SaveOperatingEnvironment) &&
(InProcNodeOwningOperatingEnvironment != null))
{
InProcNodeOwningOperatingEnvironment.Release();
InProcNodeOwningOperatingEnvironment.Dispose();
InProcNodeOwningOperatingEnvironment = null;
}
if (!_componentHost.BuildParameters.EnableNodeReuse)
{
_inProcNode = null;
_inProcNodeEndpoint = null;
_inProcNodeThread = null;
_packetFactory = null;
}
}
// Route the packet back to the NodeManager.
factory.RoutePacket(savedInProcNodeId, packet);
}
}
#endregion
/// <summary>
/// IDisposable implementation
/// </summary>
public void Dispose()
{
Dispose(true /* disposing */);
GC.SuppressFinalize(this);
}
/// <summary>
/// Factory for component creation.
/// </summary>
static internal IBuildComponent CreateComponent(BuildComponentType type)
{
ErrorUtilities.VerifyThrow(type == BuildComponentType.InProcNodeProvider, "Cannot create component of type {0}", type);
return new NodeProviderInProc();
}
#region Private Methods
/// <summary>
/// Creates a new in-proc node.
/// </summary>
private bool InstantiateNode(INodePacketFactory factory)
{
ErrorUtilities.VerifyThrow(null == _inProcNode, "In Proc node already instantiated.");
ErrorUtilities.VerifyThrow(null == _inProcNodeEndpoint, "In Proc node endpoint already instantiated.");
NodeEndpointInProc.EndpointPair endpoints = NodeEndpointInProc.CreateInProcEndpoints(NodeEndpointInProc.EndpointMode.Synchronous, _componentHost);
_inProcNodeEndpoint = endpoints.ManagerEndpoint;
_inProcNodeEndpoint.OnLinkStatusChanged += new LinkStatusChangedDelegate(InProcNodeEndpoint_OnLinkStatusChanged);
_packetFactory = factory;
_inProcNode = new InProcNode(_componentHost, endpoints.NodeEndpoint);
#if FEATURE_THREAD_CULTURE
_inProcNodeThread = new Thread(InProcNodeThreadProc, BuildParameters.ThreadStackSize);
#else
CultureInfo culture = _componentHost.BuildParameters.Culture;
CultureInfo uiCulture = _componentHost.BuildParameters.UICulture;
_inProcNodeThread = new Thread(() =>
{
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = uiCulture;
InProcNodeThreadProc();
});
#endif
_inProcNodeThread.Name = String.Format(CultureInfo.CurrentCulture, "In-proc Node ({0})", _componentHost.Name);
_inProcNodeThread.IsBackground = true;
#if FEATURE_THREAD_CULTURE
_inProcNodeThread.CurrentCulture = _componentHost.BuildParameters.Culture;
_inProcNodeThread.CurrentUICulture = _componentHost.BuildParameters.UICulture;
#endif
_inProcNodeThread.Start();
_inProcNodeEndpoint.Connect(this);
int connectionTimeout = CommunicationsUtilities.NodeConnectionTimeout;
bool connected = _endpointConnectedEvent.WaitOne(connectionTimeout);
ErrorUtilities.VerifyThrow(connected, "In-proc node failed to start up within {0}ms", connectionTimeout);
return true;
}
/// <summary>
/// Thread proc which runs the in-proc node.
/// </summary>
private void InProcNodeThreadProc()
{
Exception e;
NodeEngineShutdownReason reason = _inProcNode.Run(out e);
InProcNodeShutdown(reason, e);
}
/// <summary>
/// Callback invoked when the link status of the endpoint has changed.
/// </summary>
/// <param name="endpoint">The endpoint whose status has changed.</param>
/// <param name="status">The new link status.</param>
private void InProcNodeEndpoint_OnLinkStatusChanged(INodeEndpoint endpoint, LinkStatus status)
{
if (status == LinkStatus.Active)
{
// We don't verify this outside of the 'if' because we don't care about the link going down, which will occur
// after we have cleared the inProcNodeEndpoint due to shutting down the node.
ErrorUtilities.VerifyThrow(endpoint == _inProcNodeEndpoint, "Received link status event for a node other than our peer.");
_endpointConnectedEvent.Set();
}
}
/// <summary>
/// Callback invoked when the endpoint shuts down.
/// </summary>
/// <param name="reason">The reason the endpoint is shutting down.</param>
/// <param name="e">Any exception which was raised that caused the endpoint to shut down.</param>
private void InProcNodeShutdown(NodeEngineShutdownReason reason, Exception e)
{
switch (reason)
{
case NodeEngineShutdownReason.BuildComplete:
case NodeEngineShutdownReason.BuildCompleteReuse:
case NodeEngineShutdownReason.Error:
break;
case NodeEngineShutdownReason.ConnectionFailed:
ErrorUtilities.ThrowInternalError("Unexpected shutdown code {0} received.", reason);
break;
}
}
/// <summary>
/// Dispose implementation.
/// </summary>
private void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_endpointConnectedEvent != null)
{
_endpointConnectedEvent.Dispose();
_endpointConnectedEvent = null;
}
}
_disposed = true;
}
}
#endregion
}
}
| |
// <copyright file="XmlMappingParser.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using BeanIO.Builder;
using BeanIO.Config;
using BeanIO.Internal.Config.Annotation;
using BeanIO.Internal.Util;
using BeanIO.Stream;
using JetBrains.Annotations;
namespace BeanIO.Internal.Config.Xml
{
/// <summary>
/// Parses a mapping file into <see cref="BeanIOConfig"/> objects
/// </summary>
/// <remarks>
/// <para>A <see cref="BeanIOConfig"/> is produced for each mapping file imported by the
/// mapping file being parsed, and the entire collection is returned from <see cref="LoadConfiguration"/></para>
/// <para>This class is not thread safe and a new instance should be created for parsing
/// each input stream.</para>
/// </remarks>
internal class XmlMappingParser : IPropertySource
{
private static readonly bool _propertySubstitutionEnabled = Settings.Instance.GetBoolean(Settings.PROPERTY_SUBSTITUTION_ENABLED);
/// <summary>
/// used to read XML into a DOM object
/// </summary>
private readonly XmlMappingReader _reader;
private readonly Stack<Include> _includes = new Stack<Include>();
/// <summary>
/// custom Properties provided by the client for property expansion
/// </summary>
private Properties _properties;
/// <summary>
/// the mapping currently being parsed
/// </summary>
private XmlMapping _mapping;
/// <summary>
/// a Dictionary of all loaded mappings (including the root)
/// </summary>
private Dictionary<Uri, XmlMapping> _mappings;
/// <summary>
/// whether the current record class was annotated
/// </summary>
private bool _annotatedRecord = false;
/// <summary>
/// Initializes a new instance of the <see cref="XmlMappingParser"/> class.
/// </summary>
/// <param name="reader">the XML mapping reader for reading XML mapping files into a DOM object</param>
public XmlMappingParser([NotNull] XmlMappingReader reader)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
_reader = reader;
}
/// <summary>
/// Gets the mapping file information actively being parsed, which may change
/// when one mapping file imports another.
/// </summary>
protected XmlMapping Mapping => _mapping;
/// <summary>
/// Gets the amount to offset a field position, which is calculated
/// according to included template offset configurations.
/// </summary>
protected int PositionOffset
{
get
{
if (_includes.Count == 0)
return 0;
return _includes.Peek().Offset;
}
}
/// <summary>
/// Reads a mapping file input stream and returns a collection of BeanIO
/// configurations, one for the input stream and one for each imported
/// mapping file (if specified).
/// </summary>
/// <param name="input">the input stream to read from</param>
/// <param name="properties">the <see cref="Properties"/> to use for property substitution</param>
/// <returns>the collection of parsed BeanIO configuration objects</returns>
public ICollection<BeanIOConfig> LoadConfiguration([NotNull] System.IO.Stream input, [CanBeNull] Properties properties)
{
_properties = properties;
_mapping = new XmlMapping();
_mappings = new Dictionary<Uri, XmlMapping>
{
{ new Uri("root:"), _mapping },
};
try
{
LoadMapping(input);
}
catch (BeanIOConfigurationException ex) when (_mapping.Location != null)
{
throw new BeanIOConfigurationException($"Invalid mapping file '{_mapping.Name}': {ex.Message}", ex);
}
var configList = new List<BeanIOConfig>(_mappings.Count);
foreach (var mapping in _mappings.Values)
{
var config = mapping.Configuration.Clone();
// global type handlers are the only elements that need to be imported
// from other mapping files
var handlers = new List<TypeHandlerConfig>();
mapping.AddTypeHandlersTo(handlers);
config.TypeHandlerConfigurations = handlers;
configList.Add(config);
}
return configList;
}
/// <summary>
/// Returns the property value for a given key
/// </summary>
/// <param name="key">the property key</param>
/// <returns>the property value</returns>
public string GetProperty(string key)
{
string value = null;
if (_properties != null)
{
value = _properties[key];
}
if (value == null)
{
var mappingProperties = _mapping.Properties;
if (mappingProperties != null)
{
value = mappingProperties[key];
}
}
return value;
}
/// <summary>
/// Includes a template
/// </summary>
/// <param name="config">the parent bean configuration</param>
/// <param name="element">the <code>include</code> DOM element to parse</param>
public void IncludeTemplate(ComponentConfig config, XElement element)
{
var template = GetAttribute(element, "template");
var offset = GetIntAttribute(element, "offset") ?? 0;
IncludeTemplate(config, template, offset);
}
/// <summary>
/// Includes a template
/// </summary>
/// <param name="config">the parent bean configuration</param>
/// <param name="template">the name of the template to include</param>
/// <param name="offset">the value to offset configured positions by</param>
public void IncludeTemplate(ComponentConfig config, string template, int offset)
{
var element = _mapping.FindTemplate(template);
// validate the template was declared
if (element == null)
throw new BeanIOConfigurationException($"Template '{template}' not found");
// validate there is no circular reference
foreach (var include in _includes)
{
if (string.Equals(template, include.Template, StringComparison.Ordinal))
throw new BeanIOConfigurationException($"Circular reference detected in template '{template}'");
}
// adjust the configured offset by any previous offset
offset += PositionOffset;
Include inc = new Include(template, offset);
_includes.Push(inc);
AddProperties(config, element);
_includes.Pop();
}
/// <summary>
/// Initiates the parsing of an imported mapping file
/// </summary>
/// <remarks>
/// After parsing completes, <see cref="Pop"/> must be invoked before continuing
/// </remarks>
/// <param name="name">the name of the imported mapping file</param>
/// <param name="location">the location of the imported mapping file
/// (this should be an absolute URL so that importing the
/// same mapping more than once can be detected)</param>
/// <returns>the new Mapping object pushed onto the stack
/// (this can also be accessed by calling <see cref="Mapping"/></returns>
protected XmlMapping Push(string name, Uri location)
{
var m = new XmlMapping(name, location, _mapping);
_mappings[location] = m;
_mapping.AddImport(m);
_mapping = m;
return _mapping;
}
/// <summary>
/// Completes the parsing of an imported mapping file
/// </summary>
/// <seealso cref="Push"/>
protected void Pop()
{
_mapping = _mapping.Parent;
}
/// <summary>
/// Loads a mapping file from an input stream
/// </summary>
/// <param name="input">the input stream to read from</param>
protected virtual void LoadMapping(System.IO.Stream input)
{
var doc = _reader.LoadDocument(input);
LoadMapping(doc.Root);
}
/// <summary>
/// Parses a BeanIO configuration from a DOM element
/// </summary>
/// <param name="element">the root <code>beanio</code> DOM element to parse</param>
protected virtual void LoadMapping(XElement element)
{
var config = _mapping.Configuration;
foreach (var child in element.Elements())
{
var name = child.Name.LocalName;
switch (name)
{
case "import":
ImportConfiguration(child);
break;
case "property":
{
var key = GetAttribute(child, "name");
var value = GetAttribute(child, "value");
_mapping.SetProperty(key, value);
}
break;
case "typeHandler":
{
TypeHandlerConfig handler = CreateHandlerConfig(child);
if (handler.Name != null && _mapping.IsDeclaredGlobalTypeHandler(handler.Name))
throw new BeanIOConfigurationException($"Duplicate global type handler named '{handler.Name}'");
config.Add(handler);
}
break;
case "template":
CreateTemplate(child);
break;
case "stream":
config.Add(CreateStreamConfig(child));
break;
}
}
}
/// <summary>
/// Parses an <code>import</code> DOM element and loads its mapping file
/// </summary>
/// <param name="element">the <code>import</code> DOM element</param>
/// <returns>a new <see cref="XmlMapping"/> for the imported resource or file</returns>
protected XmlMapping ImportConfiguration(XElement element)
{
var resource = GetAttribute(element, "resource");
var name = resource;
var colonIndex = resource.IndexOf(':');
if (colonIndex == -1)
throw new BeanIOConfigurationException($"No scheme specified for resource '{resource}'");
var url = new Uri(resource);
var handler = Settings.Instance.GetSchemeHandler(url, false);
if (handler == null)
{
throw new BeanIOConfigurationException(
$"Scheme of import resource name {resource} must one of: {string.Join(", ", Settings.Instance.SchemeHandlers.Keys.Select(x => $"'{x}'"))}");
}
if (_mapping.IsLoading(url))
throw new BeanIOConfigurationException($"Failed to import resource '{name}': Circular reference(s) detected");
// check to see if the mapping file has already been loaded
XmlMapping m;
if (_mappings.TryGetValue(url, out m))
{
_mapping.AddImport(m);
return m;
}
try
{
using (var input = handler.Open(url))
{
if (input == null)
throw new BeanIOConfigurationException($"Resource '{name}' not found in classpath for import");
// push a new Mapping instance onto the stack for this url
Push(name, url).Configuration.Source = name;
LoadMapping(input);
// this is purposely not put in a finally block so that
// calling methods can know the mapping file that errored
// if a BeanIOConfigurationException is thrown
Pop();
return _mapping;
}
}
catch (IOException ex)
{
throw new BeanIOConfigurationException($"Failed to import mapping file '{name}'", ex);
}
}
/// <summary>
/// Parses a <see cref="TypeHandlerConfig"/> from a DOM element
/// </summary>
/// <param name="element">the DOM element to parse</param>
/// <returns>the new <see cref="TypeHandlerConfig"/></returns>
protected virtual TypeHandlerConfig CreateHandlerConfig(XElement element)
{
var config = new TypeHandlerConfig
{
Name = GetAttribute(element, "name"),
Type = GetAttribute(element, "type"),
ClassName = GetAttribute(element, "class"),
Format = GetAttribute(element, "format"),
Properties = CreateProperties(element),
};
return config;
}
/// <summary>
/// Adds a template to the active mapping
/// </summary>
/// <param name="element">the DOM element that defines the template</param>
protected virtual void CreateTemplate(XElement element)
{
var templateName = GetAttribute(element, "name");
if (!_mapping.AddTemplate(templateName, element))
throw new BeanIOConfigurationException($"Duplicate template named '{templateName}'");
}
/// <summary>
/// Parses a <code>Bean</code> from a DOM element
/// </summary>
/// <typeparam name="T">the bean type</typeparam>
/// <param name="element">the DOM element to parse</param>
/// <returns>the new <code>Bean</code></returns>
protected BeanConfig<T> CreateBeanFactory<T>(XElement element)
{
return new BeanConfig<T>()
{
ClassName = GetAttribute(element, "class"),
Properties = CreateProperties(element),
};
}
/// <summary>
/// Parses <see cref="Properties"/> from a DOM element
/// </summary>
/// <param name="element">the DOM element to parse</param>
/// <returns>the new <see cref="Properties"/></returns>
protected Properties CreateProperties(XElement element)
{
var props = new Dictionary<string, string>();
foreach (var child in element.Elements())
{
switch (child.Name.LocalName)
{
case "property":
{
var name = GetAttribute(child, "name");
var value = GetAttribute(child, "value");
props[name] = value ?? string.Empty;
}
break;
}
}
return new Properties(props);
}
/// <summary>
/// Parses a field configuration from a DOM element
/// </summary>
/// <param name="element">the <code>field</code> DOM element to parse</param>
/// <returns>the parsed field configuration</returns>
protected FieldConfig CreateFieldConfig(XElement element)
{
var config = new FieldConfig()
{
MinLength = GetIntAttribute(element, "minLength"),
MaxLength = GetUnboundedIntAttribute(element, "maxLength"),
RegEx = GetAttribute(element, "regex"),
Literal = GetAttribute(element, "literal"),
TypeHandler = GetTypeHandler(element, "typeHandler"),
Type = GetAttribute(element, "type"),
Format = GetAttribute(element, "format"),
DefaultValue = GetOptionalAttribute(element, "default"),
Length = GetUnboundedIntAttribute(element, "length", -1),
Padding = GetCharacterAttribute(element, "padding"),
XmlType = GetEnumAttribute<XmlNodeType>(element, "xmlType"),
XmlName = GetAttribute(element, "xmlName"),
XmlNamespace = GetOptionalAttribute(element, "xmlNamespace"),
XmlPrefix = GetOptionalAttribute(element, "xmlPrefix")
};
PopulatePropertyConfig(config, element);
var position = GetIntAttribute(element, "at");
if (position == null)
{
position = GetIntAttribute(element, "position");
}
else if (HasAttribute(element, "position"))
{
throw new BeanIOConfigurationException("Only one of 'position' or 'at' can be configured");
}
if (position != null)
{
if (position >= 0)
position += PositionOffset;
config.Position = position;
}
config.Until = GetIntAttribute(element, "until");
config.IsRequired = GetBoolAttribute(element, "required") ?? config.IsRequired;
config.IsTrim = GetBoolAttribute(element, "trim") ?? config.IsTrim;
config.IsLazy = GetBoolAttribute(element, "lazy") ?? config.IsLazy;
config.IsIdentifier = GetBoolAttribute(element, "rid") ?? config.IsIdentifier;
config.IsBound = !(GetBoolAttribute(element, "ignore") ?? false);
config.KeepPadding = GetBoolAttribute(element, "keepPadding") ?? config.KeepPadding;
config.IsLenientPadding = GetBoolAttribute(element, "lenientPadding") ?? config.IsLenientPadding;
config.IsNillable = GetBoolAttribute(element, "nillable") ?? config.IsNillable;
config.ParseDefault = GetBoolAttribute(element, "parseDefault") ?? config.ParseDefault;
if (HasAttribute(element, "justify"))
{
if (HasAttribute(element, "align"))
throw new BeanIOConfigurationException("Only one of 'align' or 'justify' can be configured");
config.Justify = GetEnumAttribute<Align>(element, "justify") ?? Align.Left;
}
else
{
config.Justify = GetEnumAttribute<Align>(element, "align") ?? Align.Left;
}
return config;
}
/// <summary>
/// Parses a constant component configuration from a DOM element
/// </summary>
/// <param name="element">the <code>property</code> DOM element to parse</param>
/// <returns>the parsed constant configuration</returns>
protected ConstantConfig CreateConstantConfig(XElement element)
{
var name = GetAttribute(element, "name");
try
{
var config = new ConstantConfig()
{
Name = GetAttribute(element, "name"),
Getter = GetAttribute(element, "getter"),
Setter = GetAttribute(element, "setter"),
Type = GetAttribute(element, "type"),
TypeHandler = GetTypeHandler(element, "typeHandler"),
Format = GetAttribute(element, "format"),
Value = GetAttribute(element, "value"),
};
config.IsIdentifier = GetBoolAttribute(element, "rid") ?? config.IsIdentifier;
return config;
}
catch (Exception ex)
{
throw new BeanIOConfigurationException($"Invalid '{name}' property definition: {ex.Message}", ex);
}
}
/// <summary>
/// Parses a <see cref="StreamConfig"/> from a DOM element
/// </summary>
/// <param name="element">the <code>stream</code> DOM element to parse</param>
/// <returns>the new <see cref="StreamConfig"/></returns>
protected StreamConfig CreateStreamConfig(XElement element)
{
var config = new StreamConfig()
{
Name = GetAttribute(element, "name"),
Format = GetAttribute(element, "format"),
Mode = GetEnumAttribute<AccessMode>(element, "mode"),
ValidateOnMarshal = GetBoolAttribute(element, "validateOnMarshal"),
XmlName = GetAttribute(element, "xmlName"),
XmlNamespace = GetOptionalAttribute(element, "xmlNamespace"),
XmlPrefix = GetOptionalAttribute(element, "xmlPrefix"),
XmlType = GetOptionalEnumAttribute<XmlNodeType>(element, "xmlType"),
ResourceBundle = GetAttribute(element, "resourceBundle"),
};
config.IsStrict = GetBoolAttribute(element, "strict") ?? config.IsStrict;
config.IgnoreUnidentifiedRecords = GetBoolAttribute(element, "ignoreUnidentifiedRecords") ?? config.IgnoreUnidentifiedRecords;
PopulatePropertyConfigOccurs(config, element);
foreach (var child in element.Elements())
{
switch (child.Name.LocalName)
{
case "typeHandler":
config.AddHandler(CreateHandlerConfig(child));
break;
case "parser":
config.ParserFactory = CreateBeanFactory<IRecordParserFactory>(child);
break;
case "record":
config.Add(CreateRecordConfig(child));
break;
case "group":
config.Add(CreateGroupConfig(child));
break;
}
}
return config;
}
/// <summary>
/// Parses a group configuration from a DOM element
/// </summary>
/// <param name="element">the <code>group</code> DOM element to parse</param>
/// <returns>the parsed group configuration</returns>
protected GroupConfig CreateGroupConfig(XElement element)
{
var typeName = GetAttribute(element, "class");
var config = AnnotationParser.CreateGroupConfig(typeName);
if (config != null)
return config;
config = new GroupConfig()
{
Type = typeName,
Order = GetIntAttribute(element, "order"),
Target = GetAttribute(element, "value"),
XmlName = GetAttribute(element, "xmlName"),
XmlNamespace = GetOptionalAttribute(element, "xmlNamespace"),
XmlPrefix = GetOptionalAttribute(element, "xmlPrefix"),
XmlType = GetOptionalEnumAttribute<XmlNodeType>(element, "xmlType"),
};
PopulatePropertyConfig(config, element);
config.SetKey(GetAttribute(element, "key"));
foreach (var child in element.Elements())
{
switch (child.Name.LocalName)
{
case "record":
config.Add(CreateRecordConfig(child));
break;
case "group":
config.Add(CreateGroupConfig(child));
break;
}
}
return config;
}
/// <summary>
/// Parses a record configuration from the given DOM element
/// </summary>
/// <param name="element">the <code>record</code> DOM element to parse</param>
/// <returns>the parsed record configuration</returns>
protected RecordConfig CreateRecordConfig(XElement element)
{
var typeName = GetAttribute(element, "class");
var config = AnnotationParser.CreateRecordConfig(typeName);
if (config != null)
return config;
config = new RecordConfig()
{
Type = typeName,
Order = GetIntAttribute(element, "order"),
MinLength = GetIntAttribute(element, "minLength"),
MaxLength = GetUnboundedIntAttribute(element, "maxLength", int.MaxValue),
XmlName = GetAttribute(element, "xmlName"),
XmlNamespace = GetOptionalAttribute(element, "xmlNamespace"),
XmlPrefix = GetOptionalAttribute(element, "xmlPrefix"),
XmlType = GetOptionalEnumAttribute<XmlNodeType>(element, "xmlType"),
};
PopulatePropertyConfig(config, element);
config.SetKey(GetAttribute(element, "key"));
config.IsLazy = GetBoolAttribute(element, "lazy") ?? config.IsLazy;
if (HasAttribute(element, "value"))
{
config.Target = GetAttribute(element, "value");
if (HasAttribute(element, "target"))
throw new BeanIOConfigurationException("Only one 'value' or 'target' can be configured");
}
else
{
config.Target = GetAttribute(element, "target");
}
var range = GetRangeAttribute(element, "ridLength");
if (range != null)
{
config.MinMatchLength = range.Min;
config.MaxMatchLength = range.Max;
}
var template = GetOptionalAttribute(element, "template");
if (template != null)
IncludeTemplate(config, template, 0);
AddProperties(config, element);
return config;
}
/// <summary>
/// Parses a segment component configuration from a DOM element
/// </summary>
/// <param name="element">the <code>segment</code> DOM element to parse</param>
/// <returns>the parsed segment configuration</returns>
protected SegmentConfig CreateSegmentConfig(XElement element)
{
var config = new SegmentConfig()
{
Type = GetAttribute(element, "class"),
XmlName = GetAttribute(element, "xmlName"),
XmlNamespace = GetOptionalAttribute(element, "xmlNamespace"),
XmlPrefix = GetOptionalAttribute(element, "xmlPrefix"),
XmlType = GetOptionalEnumAttribute<XmlNodeType>(element, "xmlType"),
};
PopulatePropertyConfig(config, element);
config.SetKey(GetAttribute(element, "key"));
config.IsLazy = GetBoolAttribute(element, "lazy") ?? config.IsLazy;
config.IsNillable = GetBoolAttribute(element, "nillable") ?? config.IsLazy;
var template = GetOptionalAttribute(element, "template");
if (template != null)
IncludeTemplate(config, template, 0);
AddProperties(config, element);
if (HasAttribute(element, "value"))
{
config.Target = GetAttribute(element, "value");
if (HasAttribute(element, "target"))
throw new BeanIOConfigurationException("Only one of 'value' or 'target' can be configured");
}
else
{
config.Target = GetAttribute(element, "target");
}
return config;
}
/// <summary>
/// Parses bean properties from the given DOM element
/// </summary>
/// <param name="config">the enclosing bean configuration to add the properties to</param>
/// <param name="element">the <code>bean</code> or <code>record</code> DOM element to parse</param>
protected void AddProperties(ComponentConfig config, XElement element)
{
foreach (var child in element.Elements())
{
if (_annotatedRecord && config.ComponentType == ComponentType.Record)
throw new BeanIOConfigurationException("Annotated classes may not contain child componennts in a mapping file");
switch (child.Name.LocalName)
{
case "field":
config.Add(CreateFieldConfig(child));
break;
case "segment":
config.Add(CreateSegmentConfig(child));
break;
case "property":
config.Add(CreateConstantConfig(child));
break;
case "include":
IncludeTemplate(config, child);
break;
}
}
}
private string GetTypeHandler(XElement element, string name)
{
var handler = GetAttribute(element, name);
/*
if (handler != null && !mapping.isName(Mapping.TYPE_HANDLER_NAMESPACE, handler)) {
throw new BeanIOConfigurationException("Unresolved type handler named '" + handler + "'");
}
*/
return handler;
}
private string DoPropertySubstitution(string text)
{
try
{
return _propertySubstitutionEnabled ? StringUtil.DoPropertySubstitution(text, this) : text;
}
catch (ArgumentException ex)
{
throw new BeanIOConfigurationException(ex.Message, ex);
}
}
private string GetOptionalAttribute(XElement element, string name)
{
var attr = element.Attribute(name);
if (attr == null)
return null;
return DoPropertySubstitution(attr.Value);
}
private bool HasAttribute(XElement element, string name)
{
return element.Attribute(name) != null;
}
private string GetAttribute(XElement element, string name)
{
var attr = element.Attribute(name);
string value;
if (attr == null)
value = null;
else if (string.IsNullOrEmpty(attr.Value))
value = null;
else
value = attr.Value;
return DoPropertySubstitution(value);
}
private int? GetIntAttribute(XElement element, string name)
{
var text = GetAttribute(element, name);
if (string.IsNullOrEmpty(text))
return null;
return int.Parse(text);
}
private int? GetUnboundedIntAttribute(XElement element, string name, int? unboundedValue = null)
{
var text = GetAttribute(element, name);
if (string.IsNullOrEmpty(text))
return null;
if (text == "unbounded")
return unboundedValue;
return int.Parse(text);
}
private char? GetCharacterAttribute(XElement element, string name)
{
var text = GetAttribute(element, name);
if (string.IsNullOrEmpty(text))
return null;
return text[0];
}
private bool? GetBoolAttribute(XElement element, string name)
{
var text = GetAttribute(element, name);
if (string.IsNullOrEmpty(text))
return null;
return XmlConvert.ToBoolean(text);
}
private T? GetEnumAttribute<T>(XElement element, string name)
where T : struct
{
var text = GetAttribute(element, name);
if (string.IsNullOrEmpty(text))
return null;
T result;
if (Enum.TryParse(text, true, out result))
return result;
throw new BeanIOConfigurationException(string.Format("Invalid {1} '{0}'", text, name));
}
private T? GetOptionalEnumAttribute<T>(XElement element, string name)
where T : struct
{
var text = GetOptionalAttribute(element, name);
if (string.IsNullOrEmpty(text))
return null;
return (T)Enum.Parse(typeof(T), text, true);
}
private Range GetRangeAttribute(XElement element, string name)
{
// parse occurs (e.g. '1', '0-1', '0+', '1+' etc)
var range = GetAttribute(element, name);
if (range == null)
return null;
try
{
int? min;
int? max;
if (range.EndsWith("+", StringComparison.Ordinal))
{
min = int.Parse(range.Substring(0, range.Length - 1));
max = int.MaxValue;
}
else
{
int n = range.IndexOf('-');
if (n == -1)
{
min = max = int.Parse(range);
}
else
{
min = int.Parse(range.Substring(0, n));
max = int.Parse(range.Substring(n + 1));
}
}
return new Range(min, max);
}
catch (FormatException ex)
{
throw new BeanIOConfigurationException($"Invalid {name} '{range}'", ex);
}
}
private void PopulatePropertyConfig(PropertyConfig config, XElement element)
{
config.Name = GetAttribute(element, "name");
config.ValidateOnMarshal = GetBoolAttribute(element, "validateOnMarshal");
config.Getter = GetAttribute(element, "getter");
config.Setter = GetAttribute(element, "setter");
config.Collection = GetAttribute(element, "collection");
PopulatePropertyConfigOccurs(config, element);
}
private void PopulatePropertyConfigOccurs(PropertyConfig config, XElement element)
{
config.OccursRef = GetAttribute(element, "occursRef");
var hasOccurs = HasAttribute(element, "occurs");
if (hasOccurs)
{
if (HasAttribute(element, "minOccurs") || HasAttribute(element, "maxOccurs"))
throw new BeanIOConfigurationException("occurs cannot be used with minOccurs or maxOccurs");
var range = GetRangeAttribute(element, "occurs");
if (range != null)
{
config.MinOccurs = range.Min;
config.MaxOccurs = range.Max;
}
}
else
{
config.MinOccurs = GetIntAttribute(element, "minOccurs");
config.MaxOccurs = GetUnboundedIntAttribute(element, "maxOccurs", int.MaxValue);
}
}
private class Include
{
public Include(string template, int offset)
{
Template = template;
Offset = offset;
}
public string Template { get; }
public int Offset { get; }
}
private class Range
{
public Range(int? min, int? max)
{
Min = min;
Max = max;
}
public int? Min { get; }
public int? Max { get; }
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B05_SubContinent_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="B05_SubContinent_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="B04_SubContinent"/> collection.
/// </remarks>
[Serializable]
public partial class B05_SubContinent_ReChild : BusinessBase<B05_SubContinent_ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int subContinent_ID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SubContinent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Sub Continent Child Name");
/// <summary>
/// Gets or sets the Sub Continent Child Name.
/// </summary>
/// <value>The Sub Continent Child Name.</value>
public string SubContinent_Child_Name
{
get { return GetProperty(SubContinent_Child_NameProperty); }
set { SetProperty(SubContinent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B05_SubContinent_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="B05_SubContinent_ReChild"/> object.</returns>
internal static B05_SubContinent_ReChild NewB05_SubContinent_ReChild()
{
return DataPortal.CreateChild<B05_SubContinent_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="B05_SubContinent_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="B05_SubContinent_ReChild"/> object.</returns>
internal static B05_SubContinent_ReChild GetB05_SubContinent_ReChild(SafeDataReader dr)
{
B05_SubContinent_ReChild obj = new B05_SubContinent_ReChild();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B05_SubContinent_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public B05_SubContinent_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="B05_SubContinent_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="B05_SubContinent_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name"));
// parent properties
subContinent_ID2 = dr.GetInt32("SubContinent_ID2");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="B05_SubContinent_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(B04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddB05_SubContinent_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID2", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="B05_SubContinent_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(B04_SubContinent parent)
{
if (!IsDirty)
return;
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateB05_SubContinent_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID2", parent.SubContinent_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@SubContinent_Child_Name", ReadProperty(SubContinent_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="B05_SubContinent_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(B04_SubContinent parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteB05_SubContinent_ReChild", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@SubContinent_ID2", parent.SubContinent_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Owin;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk;
namespace Adxstudio.Xrm.AspNet.Cms
{
public class CrmWebsiteSetting
{
public virtual Entity Entity { get; private set; }
public virtual string Name { get { return Entity.GetAttributeValue<string>("adx_name"); } }
public virtual string Value { get { return Entity.GetAttributeValue<string>("adx_value"); } }
public CrmWebsiteSetting(Entity entity)
{
Entity = entity;
}
}
public class CrmWebsiteBinding
{
public virtual Entity Entity { get; private set; }
public virtual string Name { get { return Entity.GetAttributeValue<string>("adx_name"); } }
public virtual string SiteName { get { return Entity.GetAttributeValue<string>("adx_sitename"); } }
public virtual string VirtualPath { get { return Entity.GetAttributeValue<string>("adx_virtualpath"); } }
public virtual DateTime? ReleaseDate { get { return Entity.GetAttributeValue<DateTime?>("adx_releasedate"); } }
public virtual DateTime? ExpirationDate { get { return Entity.GetAttributeValue<DateTime?>("adx_expirationdate"); } }
public CrmWebsiteBinding(Entity entity)
{
Entity = entity;
}
}
public class CrmWebsiteSettingCollection : List<CrmWebsiteSetting>
{
public CrmWebsiteSettingCollection(IEnumerable<CrmWebsiteSetting> collection)
: base(collection)
{
}
public T Get<T>(string name)
{
var setting = this.FirstOrDefault(s => s.Name.ToLower() == name.ToLower());
if (setting == null) return default(T);
var value = setting.Value;
return GetValue<T>(value);
}
public T? GetEnum<T>(string name) where T : struct
{
var setting = this.FirstOrDefault(s => s.Name.ToLower() == name.ToLower());
if (setting == null) return null;
var value = setting.Value;
T result;
if (Enum.TryParse(value, out result))
{
return result;
}
return null;
}
protected virtual T GetValue<T>(string value)
{
var type = typeof(T);
if (type.IsA(typeof(string)))
{
return (T)(object)value;
}
if (type.IsA(typeof(bool)) || type.IsA(typeof(bool?)))
{
bool result;
if (bool.TryParse(value, out result))
{
return (T)(object)result;
}
}
if (type.IsA(typeof(int)) || type.IsA(typeof(int?)))
{
int result;
if (int.TryParse(value, out result))
{
return (T)(object)result;
}
}
if (type.IsA(typeof(TimeSpan)) || type.IsA(typeof(TimeSpan?)))
{
TimeSpan result;
if (TimeSpan.TryParse(value, out result))
{
return (T)(object)result;
}
}
if (type.IsA(typeof(PathString)) || type.IsA(typeof(PathString?)))
{
return (T)(object)new PathString(value);
}
return default(T);
}
}
public class CrmWebsite : CrmWebsite<Guid>, IDisposable
{
public CrmWebsite()
{
}
public CrmWebsite(Entity entity)
: base(entity)
{
}
void IDisposable.Dispose() { }
}
public class CrmWebsite<TKey> : CrmModel<TKey>
{
private readonly Lazy<CrmWebsiteSettingCollection> _settings;
public virtual CrmWebsiteSettingCollection Settings
{
get { return _settings.Value; }
}
private Lazy<IEnumerable<CrmWebsiteBinding>> _bindings;
public virtual IEnumerable<CrmWebsiteBinding> Bindings
{
get { return _bindings.Value; }
}
/// <summary>
/// The lcid of the language for the website
/// </summary>
public virtual int Language
{
get { return Entity.GetAttributeValue<int>("adx_website_language"); }
}
public virtual EntityReference DefaultLanguage
{
get { return Entity.GetAttributeValue<EntityReference>("adx_defaultlanguage"); }
}
public virtual EntityReference ParentWebsiteId
{
get { return Entity.GetAttributeValue<EntityReference>("adx_parentwebsiteid"); }
set { Entity.SetAttributeValue("adx_parentwebsiteid", value); }
}
public virtual string PrimaryDomainName
{
get { return Entity.GetAttributeValue<string>("adx_primarydomainname"); }
set { Entity.SetAttributeValue("adx_primarydomainname", value); }
}
public CrmWebsite()
: this(null)
{
}
public CrmWebsite(Entity entity)
: base("adx_website", "adx_name", entity)
{
_settings = new Lazy<CrmWebsiteSettingCollection>(GetWebsiteSettings);
_bindings = new Lazy<IEnumerable<CrmWebsiteBinding>>(GetWebsiteBindings);
}
protected virtual CrmWebsiteSettingCollection GetWebsiteSettings()
{
return new CrmWebsiteSettingCollection(GetRelatedEntities(WebsiteConstants.WebsiteSiteSettingRelationship).Select(ToSetting));
}
protected virtual CrmWebsiteSetting ToSetting(Entity entity)
{
return new CrmWebsiteSetting(entity);
}
protected virtual IEnumerable<CrmWebsiteBinding> GetWebsiteBindings()
{
return GetRelatedEntities(WebsiteConstants.WebsiteBindingRelationship).Select(ToBinding).ToList();
}
protected virtual CrmWebsiteBinding ToBinding(Entity entity)
{
return new CrmWebsiteBinding(entity);
}
protected virtual void RefreshWebsiteBindings()
{
_bindings = new Lazy<IEnumerable<CrmWebsiteBinding>>(GetWebsiteBindings);
}
public CrmWebsiteBinding AddWebsiteBinding(PortalHostingEnvironment environment)
{
var websiteBinding = new Entity("adx_websitebinding");
websiteBinding.SetAttributeValue<string>("adx_name", "Binding: {0}".FormatWith(environment.SiteName));
websiteBinding.SetAttributeValue<EntityReference>("adx_websiteid", this.Entity.ToEntityReference());
websiteBinding.SetAttributeValue<string>("adx_sitename", environment.SiteName);
if (this.Entity.RelatedEntities.ContainsKey(WebsiteConstants.WebsiteBindingRelationship))
{
this.Entity.RelatedEntities[WebsiteConstants.WebsiteBindingRelationship].Entities.Add(websiteBinding);
}
else
{
this.Entity.RelatedEntities.Add(WebsiteConstants.WebsiteBindingRelationship, new EntityCollection(new[] { websiteBinding }));
}
// reset binding collection
this.RefreshWebsiteBindings();
return this.ToBinding(websiteBinding);
}
public bool RemoveWebsiteBinding(CrmWebsiteBinding websiteBinding)
{
if (this.Entity.RelatedEntities.ContainsKey(WebsiteConstants.WebsiteBindingRelationship))
{
if (this.Entity.RelatedEntities[WebsiteConstants.WebsiteBindingRelationship].Entities.Remove(websiteBinding.Entity))
{
// reset binding collection
this.RefreshWebsiteBindings();
}
}
return false;
}
}
}
| |
/*
* Muhimbi PDF
*
* Convert, Merge, Watermark, Secure and OCR files.
*
* OpenAPI spec version: 9.15
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace Muhimbi.PDF.Online.Client.Model
{
/// <summary>
/// Response data for split operation
/// </summary>
[DataContract]
public partial class SplitOperationResponse : IEquatable<SplitOperationResponse>, IValidatableObject
{
/// <summary>
/// Operation result code.
/// </summary>
/// <value>Operation result code.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum ResultCodeEnum
{
/// <summary>
/// Enum Success for "Success"
/// </summary>
[EnumMember(Value = "Success")]
Success,
/// <summary>
/// Enum ProcessingError for "ProcessingError"
/// </summary>
[EnumMember(Value = "ProcessingError")]
ProcessingError,
/// <summary>
/// Enum SubscriptionNotFound for "SubscriptionNotFound"
/// </summary>
[EnumMember(Value = "SubscriptionNotFound")]
SubscriptionNotFound,
/// <summary>
/// Enum SubscriptionExpired for "SubscriptionExpired"
/// </summary>
[EnumMember(Value = "SubscriptionExpired")]
SubscriptionExpired,
/// <summary>
/// Enum ActivationPending for "ActivationPending"
/// </summary>
[EnumMember(Value = "ActivationPending")]
ActivationPending,
/// <summary>
/// Enum TrialExpired for "TrialExpired"
/// </summary>
[EnumMember(Value = "TrialExpired")]
TrialExpired,
/// <summary>
/// Enum OperationSizeExceeded for "OperationSizeExceeded"
/// </summary>
[EnumMember(Value = "OperationSizeExceeded")]
OperationSizeExceeded,
/// <summary>
/// Enum OperationsExceeded for "OperationsExceeded"
/// </summary>
[EnumMember(Value = "OperationsExceeded")]
OperationsExceeded,
/// <summary>
/// Enum InputFileTypeNotSupported for "InputFileTypeNotSupported"
/// </summary>
[EnumMember(Value = "InputFileTypeNotSupported")]
InputFileTypeNotSupported,
/// <summary>
/// Enum OutputFileTypeNotSupported for "OutputFileTypeNotSupported"
/// </summary>
[EnumMember(Value = "OutputFileTypeNotSupported")]
OutputFileTypeNotSupported,
/// <summary>
/// Enum OperationNotSupported for "OperationNotSupported"
/// </summary>
[EnumMember(Value = "OperationNotSupported")]
OperationNotSupported,
/// <summary>
/// Enum Accepted for "Accepted"
/// </summary>
[EnumMember(Value = "Accepted")]
Accepted,
/// <summary>
/// Enum AccessDenied for "AccessDenied"
/// </summary>
[EnumMember(Value = "AccessDenied")]
AccessDenied,
/// <summary>
/// Enum InvalidExtension for "InvalidExtension"
/// </summary>
[EnumMember(Value = "InvalidExtension")]
InvalidExtension
}
/// <summary>
/// Operation result code.
/// </summary>
/// <value>Operation result code.</value>
[DataMember(Name="result_code", EmitDefaultValue=false)]
public ResultCodeEnum? ResultCode { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="SplitOperationResponse" /> class.
/// </summary>
/// <param name="ProcessedFiles">Files generated by the Muhimbi converter..</param>
/// <param name="ResultCode">Operation result code..</param>
/// <param name="ResultDetails">Operation result details..</param>
public SplitOperationResponse(List<ProcessedFiles> ProcessedFiles = default(List<ProcessedFiles>), ResultCodeEnum? ResultCode = default(ResultCodeEnum?), string ResultDetails = default(string))
{
this.ProcessedFiles = ProcessedFiles;
this.ResultCode = ResultCode;
this.ResultDetails = ResultDetails;
}
/// <summary>
/// Files generated by the Muhimbi converter.
/// </summary>
/// <value>Files generated by the Muhimbi converter.</value>
[DataMember(Name="processed_files", EmitDefaultValue=false)]
public List<ProcessedFiles> ProcessedFiles { get; set; }
/// <summary>
/// Operation result details.
/// </summary>
/// <value>Operation result details.</value>
[DataMember(Name="result_details", EmitDefaultValue=false)]
public string ResultDetails { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class SplitOperationResponse {\n");
sb.Append(" ProcessedFiles: ").Append(ProcessedFiles).Append("\n");
sb.Append(" ResultCode: ").Append(ResultCode).Append("\n");
sb.Append(" ResultDetails: ").Append(ResultDetails).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as SplitOperationResponse);
}
/// <summary>
/// Returns true if SplitOperationResponse instances are equal
/// </summary>
/// <param name="other">Instance of SplitOperationResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(SplitOperationResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ProcessedFiles == other.ProcessedFiles ||
this.ProcessedFiles != null &&
this.ProcessedFiles.SequenceEqual(other.ProcessedFiles)
) &&
(
this.ResultCode == other.ResultCode ||
this.ResultCode != null &&
this.ResultCode.Equals(other.ResultCode)
) &&
(
this.ResultDetails == other.ResultDetails ||
this.ResultDetails != null &&
this.ResultDetails.Equals(other.ResultDetails)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ProcessedFiles != null)
hash = hash * 59 + this.ProcessedFiles.GetHashCode();
if (this.ResultCode != null)
hash = hash * 59 + this.ResultCode.GetHashCode();
if (this.ResultDetails != null)
hash = hash * 59 + this.ResultDetails.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
* Copyright (C) 2012, 2013 OUYA, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using UnityEngine;
public class OuyaShowUnityInput : MonoBehaviour,
OuyaSDK.IJoystickCalibrationListener,
OuyaSDK.IPauseListener, OuyaSDK.IResumeListener,
OuyaSDK.IMenuButtonUpListener,
OuyaSDK.IMenuAppearingListener
{
#region Model reference fields
public Material ControllerMaterial;
public MeshRenderer RendererAxisLeft = null;
public MeshRenderer RendererAxisRight = null;
public MeshRenderer RendererButtonA = null;
public MeshRenderer RendererButtonO = null;
public MeshRenderer RendererButtonU = null;
public MeshRenderer RendererButtonY = null;
public MeshRenderer RendererDpadDown = null;
public MeshRenderer RendererDpadLeft = null;
public MeshRenderer RendererDpadRight = null;
public MeshRenderer RendererDpadUp = null;
public MeshRenderer RendererLB = null;
public MeshRenderer RendererLT = null;
public MeshRenderer RendererRB = null;
public MeshRenderer RendererRT = null;
#endregion
private bool m_showCursor = true;
#region Thumbstick plots
public Camera ThumbstickPlotCamera = null;
#endregion
#region New Input API - in progress
private bool m_useSDKForInput = false;
#endregion
void Awake()
{
OuyaSDK.registerJoystickCalibrationListener(this);
OuyaSDK.registerMenuButtonUpListener(this);
OuyaSDK.registerMenuAppearingListener(this);
OuyaSDK.registerPauseListener(this);
OuyaSDK.registerResumeListener(this);
}
void OnDestroy()
{
OuyaSDK.unregisterJoystickCalibrationListener(this);
OuyaSDK.unregisterMenuButtonUpListener(this);
OuyaSDK.unregisterMenuAppearingListener(this);
OuyaSDK.unregisterPauseListener(this);
OuyaSDK.unregisterResumeListener(this);
}
private void Start()
{
UpdatePlayerButtons();
Input.ResetInputAxes();
}
public void SetPlayer1()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player1;
UpdatePlayerButtons();
}
public void SetPlayer2()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player2;
UpdatePlayerButtons();
}
public void SetPlayer3()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player3;
UpdatePlayerButtons();
}
public void SetPlayer4()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player4;
UpdatePlayerButtons();
}
public void SetPlayer5()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player5;
UpdatePlayerButtons();
}
public void SetPlayer6()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player6;
UpdatePlayerButtons();
}
public void SetPlayer7()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player7;
UpdatePlayerButtons();
}
public void SetPlayer8()
{
OuyaExampleCommon.Player = OuyaSDK.OuyaPlayer.player8;
UpdatePlayerButtons();
}
public void OuyaMenuButtonUp()
{
Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString());
m_showCursor = !m_showCursor;
Debug.Log(string.Format("OuyaMenuButtonUp: m_showCursor: {0}", m_showCursor));
OuyaSDK.OuyaJava.JavaShowCursor(m_showCursor);
}
public void OuyaMenuAppearing()
{
Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString());
}
public void OuyaOnPause()
{
Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString());
}
public void OuyaOnResume()
{
Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString());
}
public void OuyaOnJoystickCalibration()
{
Debug.Log(System.Reflection.MethodBase.GetCurrentMethod().ToString());
}
#region Presentation
private void UpdateLabels()
{
try
{
OuyaNGUIHandler nguiHandler = GameObject.Find("_NGUIHandler").GetComponent<OuyaNGUIHandler>();
if (nguiHandler != null &&
null != OuyaSDK.Joysticks)
{
for (int i = 0; i < OuyaSDK.Joysticks.Length || i < 8; i++)
{
string joyName = "N/A";
if (i < OuyaSDK.Joysticks.Length)
{
joyName = OuyaSDK.Joysticks[i];
}
switch (i)
{
case 0:
nguiHandler.controller1.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player1 ? string.Format("*{0}", joyName) : joyName;
break;
case 1:
nguiHandler.controller2.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player2 ? string.Format("*{0}", joyName) : joyName;
break;
case 2:
nguiHandler.controller3.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player3 ? string.Format("*{0}", joyName) : joyName;
break;
case 3:
nguiHandler.controller4.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player4 ? string.Format("*{0}", joyName) : joyName;
break;
case 4:
nguiHandler.controller5.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player5 ? string.Format("*{0}", joyName) : joyName;
break;
case 5:
nguiHandler.controller6.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player6 ? string.Format("*{0}", joyName) : joyName;
break;
case 6:
nguiHandler.controller7.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player7 ? string.Format("*{0}", joyName) : joyName;
break;
case 7:
nguiHandler.controller8.text = OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player8 ? string.Format("*{0}", joyName) : joyName;
break;
}
}
nguiHandler.button1.text = OuyaExampleCommon.GetButton(0, OuyaExampleCommon.Player).ToString();
nguiHandler.button2.text = OuyaExampleCommon.GetButton(1, OuyaExampleCommon.Player).ToString();
nguiHandler.button3.text = OuyaExampleCommon.GetButton(2, OuyaExampleCommon.Player).ToString();
nguiHandler.button4.text = OuyaExampleCommon.GetButton(3, OuyaExampleCommon.Player).ToString();
nguiHandler.button5.text = OuyaExampleCommon.GetButton(4, OuyaExampleCommon.Player).ToString();
nguiHandler.button6.text = OuyaExampleCommon.GetButton(5, OuyaExampleCommon.Player).ToString();
nguiHandler.button7.text = OuyaExampleCommon.GetButton(6, OuyaExampleCommon.Player).ToString();
nguiHandler.button8.text = OuyaExampleCommon.GetButton(7, OuyaExampleCommon.Player).ToString();
nguiHandler.button9.text = OuyaExampleCommon.GetButton(8, OuyaExampleCommon.Player).ToString();
nguiHandler.button10.text = OuyaExampleCommon.GetButton(9, OuyaExampleCommon.Player).ToString();
nguiHandler.button11.text = OuyaExampleCommon.GetButton(10, OuyaExampleCommon.Player).ToString();
nguiHandler.button12.text = OuyaExampleCommon.GetButton(11, OuyaExampleCommon.Player).ToString();
nguiHandler.button13.text = OuyaExampleCommon.GetButton(12, OuyaExampleCommon.Player).ToString();
nguiHandler.button14.text = OuyaExampleCommon.GetButton(13, OuyaExampleCommon.Player).ToString();
nguiHandler.button15.text = OuyaExampleCommon.GetButton(14, OuyaExampleCommon.Player).ToString();
nguiHandler.button16.text = OuyaExampleCommon.GetButton(15, OuyaExampleCommon.Player).ToString();
nguiHandler.button17.text = OuyaExampleCommon.GetButton(16, OuyaExampleCommon.Player).ToString();
nguiHandler.button18.text = OuyaExampleCommon.GetButton(17, OuyaExampleCommon.Player).ToString();
nguiHandler.button19.text = OuyaExampleCommon.GetButton(18, OuyaExampleCommon.Player).ToString();
nguiHandler.button20.text = OuyaExampleCommon.GetButton(19, OuyaExampleCommon.Player).ToString();
//nguiHandler.rawOut.text = OuyaGameObject.InputData;
nguiHandler.device.text = SystemInfo.deviceModel;
}
}
catch (System.Exception)
{
}
}
void Update()
{
OuyaNGUIHandler nguiHandler = GameObject.Find("_NGUIHandler").GetComponent<OuyaNGUIHandler>();
if (nguiHandler != null)
{
// Input.GetAxis("Joy1 Axis1");
nguiHandler.axis1.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 1", (int) OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis2.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 2", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis3.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 3", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis4.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 4", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis5.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 5", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis6.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 6", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis7.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 7", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis8.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 8", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis9.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 9", (int)OuyaExampleCommon.Player)).ToString("F5");
nguiHandler.axis10.text = Input.GetAxisRaw(string.Format("Joy{0} Axis 10", (int)OuyaExampleCommon.Player)).ToString("F5");
}
}
void FixedUpdate()
{
UpdateController();
UpdateLabels();
}
void OnGUI()
{
GUILayout.FlexibleSpace();
GUILayout.FlexibleSpace();
GUILayout.FlexibleSpace();
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal();
GUILayout.Space(600);
for (int index = 1; index <= 4; ++index)
{
if (GUILayout.Button(string.Format("JOY{0}", index), GUILayout.MaxHeight(40)))
{
OuyaExampleCommon.Player = (OuyaSDK.OuyaPlayer)index;
UpdatePlayerButtons();
}
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space(600);
for (int index = 5; index <= 8; ++index)
{
if (GUILayout.Button(string.Format("JOY{0}", index), GUILayout.MaxHeight(40)))
{
OuyaExampleCommon.Player = (OuyaSDK.OuyaPlayer)index;
UpdatePlayerButtons();
}
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space(600);
m_useSDKForInput = GUILayout.Toggle(m_useSDKForInput, "Use OuyaSDK Mappings and Unity Input", GUILayout.MinHeight(45));
GUILayout.EndHorizontal();
}
void UpdatePlayerButtons()
{
if (ThumbstickPlotCamera)
{
foreach (OuyaPlotMeshThumbstick plot in ThumbstickPlotCamera.GetComponents<OuyaPlotMeshThumbstick>())
{
plot.Player = OuyaExampleCommon.Player;
}
}
OuyaNGUIHandler nguiHandler = GameObject.Find("_NGUIHandler").GetComponent<OuyaNGUIHandler>();
if (nguiHandler != null)
{
nguiHandler.player1.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player1);
nguiHandler.player2.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player2);
nguiHandler.player3.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player3);
nguiHandler.player4.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player4);
nguiHandler.player5.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player5);
nguiHandler.player6.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player6);
nguiHandler.player7.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player7);
nguiHandler.player8.SendMessage("OnHover", OuyaExampleCommon.Player == OuyaSDK.OuyaPlayer.player8);
}
}
#endregion
#region Extra
private void UpdateHighlight(MeshRenderer mr, bool highlight, bool instant = false)
{
float time = Time.deltaTime * 10;
if (instant) { time = 1000; }
if (highlight)
{
Color c = new Color(0, 10, 0, 1);
mr.material.color = Color.Lerp(mr.material.color, c, time);
}
else
{
mr.material.color = Color.Lerp(mr.material.color, Color.white, time);
}
}
private float GetAxis(OuyaSDK.KeyEnum keyCode, OuyaSDK.OuyaPlayer player)
{
// Check if we want the *new* SDK input or the example common
if (m_useSDKForInput)
{
// Get the Unity Axis Name for the Unity API
string axisName = OuyaSDK.GetUnityAxisName(keyCode, player);
// Check if the axis name is valid
if (!string.IsNullOrEmpty(axisName))
{
//use the Unity API to get the axis value, raw or otherwise
float axisValue = Input.GetAxisRaw(axisName);
//check if the axis should be inverted
if (OuyaSDK.GetAxisInverted(keyCode, player))
{
return -axisValue;
}
else
{
return axisValue;
}
}
}
// moving the common code into the sdk via above
else
{
return OuyaExampleCommon.GetAxis(keyCode, player);
}
return 0f;
}
private bool GetButton(OuyaSDK.KeyEnum keyCode, OuyaSDK.OuyaPlayer player)
{
// Check if we want the *new* SDK input or the example common
if (m_useSDKForInput)
{
// Get the Unity KeyCode for the Unity API
KeyCode unityKeyCode = OuyaSDK.GetUnityKeyCode(keyCode, player);
// Check if the KeyCode is valid
if (unityKeyCode != (KeyCode)(-1))
{
//use the Unity API to get the button value
bool buttonState = Input.GetKey(unityKeyCode);
return buttonState;
}
}
// moving the common code into the sdk via aboveUs
else
{
return OuyaExampleCommon.GetButton(keyCode, player);
}
return false;
}
private void UpdateController()
{
#region Axis Code
UpdateHighlight(RendererAxisLeft, Mathf.Abs(GetAxis(OuyaSDK.KeyEnum.AXIS_LSTICK_X, OuyaExampleCommon.Player)) > 0.25f ||
Mathf.Abs(GetAxis(OuyaSDK.KeyEnum.AXIS_LSTICK_Y, OuyaExampleCommon.Player)) > 0.25f);
RendererAxisLeft.transform.localRotation = Quaternion.Euler(GetAxis(OuyaSDK.KeyEnum.AXIS_LSTICK_Y, OuyaExampleCommon.Player) * 15, 0, GetAxis(OuyaSDK.KeyEnum.AXIS_LSTICK_X, OuyaExampleCommon.Player) * 15);
UpdateHighlight(RendererAxisRight, Mathf.Abs(GetAxis(OuyaSDK.KeyEnum.AXIS_RSTICK_X, OuyaExampleCommon.Player)) > 0.25f ||
Mathf.Abs(GetAxis(OuyaSDK.KeyEnum.AXIS_RSTICK_Y, OuyaExampleCommon.Player)) > 0.25f);
RendererAxisRight.transform.localRotation = Quaternion.Euler(GetAxis(OuyaSDK.KeyEnum.AXIS_RSTICK_Y, OuyaExampleCommon.Player) * 15, 0, GetAxis(OuyaSDK.KeyEnum.AXIS_RSTICK_X, OuyaExampleCommon.Player) * 15);
RendererLT.transform.localRotation = Quaternion.Euler(GetAxis(OuyaSDK.KeyEnum.BUTTON_LT, OuyaExampleCommon.Player) * -15, 0, 0);
RendererRT.transform.localRotation = Quaternion.Euler(GetAxis(OuyaSDK.KeyEnum.BUTTON_RT, OuyaExampleCommon.Player) * -15, 0, 0);
if (GetButton(OuyaSDK.KeyEnum.BUTTON_L3, OuyaExampleCommon.Player))
{
RendererAxisLeft.transform.localPosition = Vector3.Lerp(RendererAxisLeft.transform.localPosition,
new Vector3(5.503977f, 0.75f, -3.344945f), Time.fixedDeltaTime);
}
else
{
RendererAxisLeft.transform.localPosition = Vector3.Lerp(RendererAxisLeft.transform.localPosition,
new Vector3(5.503977f, 1.127527f, -3.344945f), Time.fixedDeltaTime);
}
if (GetButton(OuyaSDK.KeyEnum.BUTTON_R3, OuyaExampleCommon.Player))
{
RendererAxisRight.transform.localPosition = Vector3.Lerp(RendererAxisRight.transform.localPosition,
new Vector3(-2.707688f, 0.75f, -1.354063f), Time.fixedDeltaTime);
}
else
{
RendererAxisRight.transform.localPosition = Vector3.Lerp(RendererAxisRight.transform.localPosition,
new Vector3(-2.707688f, 1.11295f, -1.354063f), Time.fixedDeltaTime);
}
#endregion
#region Button Code
#region BUTTONS O - A
//Check O button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_O, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererButtonO, true, true);
}
else
{
UpdateHighlight(RendererButtonO, false, true);
}
//Check U button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_U, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererButtonU, true, true);
}
else
{
UpdateHighlight(RendererButtonU, false, true);
}
//Check Y button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_Y, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererButtonY, true, true);
}
else
{
UpdateHighlight(RendererButtonY, false, true);
}
//Check A button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_A, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererButtonA, true, true);
}
else
{
UpdateHighlight(RendererButtonA, false, true);
}
//Check L3 button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_L3, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererAxisLeft, true, true);
}
else
{
UpdateHighlight(RendererAxisLeft, false, true);
}
//Check R3 button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_R3, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererAxisRight, true, true);
}
else
{
UpdateHighlight(RendererAxisRight, false, true);
}
#endregion
#region Bumpers
//Check LB button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_LB, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererLB, true, true);
}
else
{
UpdateHighlight(RendererLB, false, true);
}
//Check RB button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_RB, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererRB, true, true);
}
else
{
UpdateHighlight(RendererRB, false, true);
}
#endregion
#region triggers
//Check LT button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_LT, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererLT, true, true);
}
else
{
UpdateHighlight(RendererLT, false, true);
}
//Check RT button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_RT, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererRT, true, true);
}
else
{
UpdateHighlight(RendererRT, false, true);
}
#endregion
#region DPAD
//Check DPAD UP button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_DPAD_UP, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererDpadUp, true, true);
}
else
{
UpdateHighlight(RendererDpadUp, false, true);
}
//Check DPAD DOWN button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_DPAD_DOWN, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererDpadDown, true, true);
}
else
{
UpdateHighlight(RendererDpadDown, false, true);
}
//Check DPAD LEFT button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_DPAD_LEFT, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererDpadLeft, true, true);
}
else
{
UpdateHighlight(RendererDpadLeft, false, true);
}
//Check DPAD RIGHT button for down state
if (GetButton(OuyaSDK.KeyEnum.BUTTON_DPAD_RIGHT, OuyaExampleCommon.Player))
{
UpdateHighlight(RendererDpadRight, true, true);
}
else
{
UpdateHighlight(RendererDpadRight, false, true);
}
#endregion
#endregion
}
#endregion
}
| |
/*
*
* LICENSE
*
* Copyright (c) 2000 - 2011 The Legion of the Bouncy Castle Inc.
* (http://www.bouncycastle.org)
*
* 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
* 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 Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Digests
{
/**
* Draft FIPS 180-2 implementation of SHA-256. <b>Note:</b> As this is
* based on a draft this implementation is subject to change.
*
* <pre>
* block word digest
* SHA-1 512 32 160
* SHA-256 512 32 256
* SHA-384 1024 64 384
* SHA-512 1024 64 512
* </pre>
*/
public class Sha256Digest
: GeneralDigest
{
private const int DigestLength = 32;
private uint H1, H2, H3, H4, H5, H6, H7, H8;
private uint[] X = new uint[64];
private int xOff;
public Sha256Digest()
{
initHs();
}
/**
* Copy constructor. This will copy the state of the provided
* message digest.
*/
public Sha256Digest(Sha256Digest t) : base(t)
{
CopyIn(t);
}
private void CopyIn(Sha256Digest t)
{
base.CopyIn(t);
H1 = t.H1;
H2 = t.H2;
H3 = t.H3;
H4 = t.H4;
H5 = t.H5;
H6 = t.H6;
H7 = t.H7;
H8 = t.H8;
Array.Copy(t.X, 0, X, 0, t.X.Length);
xOff = t.xOff;
}
public override string AlgorithmName
{
get { return "SHA-256"; }
}
public override int GetDigestSize()
{
return DigestLength;
}
internal override void ProcessWord(
byte[] input,
int inOff)
{
X[xOff] = Pack.BE_To_UInt32(input, inOff);
if (++xOff == 16)
{
ProcessBlock();
}
}
internal override void ProcessLength(
long bitLength)
{
if (xOff > 14)
{
ProcessBlock();
}
X[14] = (uint)((ulong)bitLength >> 32);
X[15] = (uint)((ulong)bitLength);
}
public override int DoFinal(
byte[] output,
int outOff)
{
Finish();
Pack.UInt32_To_BE((uint)H1, output, outOff);
Pack.UInt32_To_BE((uint)H2, output, outOff + 4);
Pack.UInt32_To_BE((uint)H3, output, outOff + 8);
Pack.UInt32_To_BE((uint)H4, output, outOff + 12);
Pack.UInt32_To_BE((uint)H5, output, outOff + 16);
Pack.UInt32_To_BE((uint)H6, output, outOff + 20);
Pack.UInt32_To_BE((uint)H7, output, outOff + 24);
Pack.UInt32_To_BE((uint)H8, output, outOff + 28);
Reset();
return DigestLength;
}
/**
* reset the chaining variables
*/
public override void Reset()
{
base.Reset();
initHs();
xOff = 0;
Array.Clear(X, 0, X.Length);
}
private void initHs()
{
/* SHA-256 initial hash value
* The first 32 bits of the fractional parts of the square roots
* of the first eight prime numbers
*/
H1 = 0x6a09e667;
H2 = 0xbb67ae85;
H3 = 0x3c6ef372;
H4 = 0xa54ff53a;
H5 = 0x510e527f;
H6 = 0x9b05688c;
H7 = 0x1f83d9ab;
H8 = 0x5be0cd19;
}
internal override void ProcessBlock()
{
//
// expand 16 word block into 64 word blocks.
//
for (int ti = 16; ti <= 63; ti++)
{
X[ti] = Theta1(X[ti - 2]) + X[ti - 7] + Theta0(X[ti - 15]) + X[ti - 16];
}
//
// set up working variables.
//
uint a = H1;
uint b = H2;
uint c = H3;
uint d = H4;
uint e = H5;
uint f = H6;
uint g = H7;
uint h = H8;
int t = 0;
for(int i = 0; i < 8; ++i)
{
// t = 8 * i
h += Sum1Ch(e, f, g) + K[t] + X[t];
d += h;
h += Sum0Maj(a, b, c);
++t;
// t = 8 * i + 1
g += Sum1Ch(d, e, f) + K[t] + X[t];
c += g;
g += Sum0Maj(h, a, b);
++t;
// t = 8 * i + 2
f += Sum1Ch(c, d, e) + K[t] + X[t];
b += f;
f += Sum0Maj(g, h, a);
++t;
// t = 8 * i + 3
e += Sum1Ch(b, c, d) + K[t] + X[t];
a += e;
e += Sum0Maj(f, g, h);
++t;
// t = 8 * i + 4
d += Sum1Ch(a, b, c) + K[t] + X[t];
h += d;
d += Sum0Maj(e, f, g);
++t;
// t = 8 * i + 5
c += Sum1Ch(h, a, b) + K[t] + X[t];
g += c;
c += Sum0Maj(d, e, f);
++t;
// t = 8 * i + 6
b += Sum1Ch(g, h, a) + K[t] + X[t];
f += b;
b += Sum0Maj(c, d, e);
++t;
// t = 8 * i + 7
a += Sum1Ch(f, g, h) + K[t] + X[t];
e += a;
a += Sum0Maj(b, c, d);
++t;
}
H1 += a;
H2 += b;
H3 += c;
H4 += d;
H5 += e;
H6 += f;
H7 += g;
H8 += h;
//
// reset the offset and clean out the word buffer.
//
xOff = 0;
Array.Clear(X, 0, 16);
}
private static uint Sum1Ch(
uint x,
uint y,
uint z)
{
// return Sum1(x) + Ch(x, y, z);
return (((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)))
+ ((x & y) ^ ((~x) & z));
}
private static uint Sum0Maj(
uint x,
uint y,
uint z)
{
// return Sum0(x) + Maj(x, y, z);
return (((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)))
+ ((x & y) ^ (x & z) ^ (y & z));
}
// /* SHA-256 functions */
// private static uint Ch(
// uint x,
// uint y,
// uint z)
// {
// return ((x & y) ^ ((~x) & z));
// }
//
// private static uint Maj(
// uint x,
// uint y,
// uint z)
// {
// return ((x & y) ^ (x & z) ^ (y & z));
// }
//
// private static uint Sum0(
// uint x)
// {
// return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10));
// }
//
// private static uint Sum1(
// uint x)
// {
// return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7));
// }
private static uint Theta0(
uint x)
{
return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3);
}
private static uint Theta1(
uint x)
{
return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10);
}
/* SHA-256 Constants
* (represent the first 32 bits of the fractional parts of the
* cube roots of the first sixty-four prime numbers)
*/
private static readonly uint[] K = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
public override IMemoable Copy()
{
return new Sha256Digest(this);
}
public override void Reset(IMemoable other)
{
Sha256Digest d = (Sha256Digest)other;
CopyIn(d);
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Hydra.Framework.Collections
{
/// <summary>
/// Stores a pair of objects within a single struct. This struct is useful to use as the
/// T of a collection, or as the TKey or TValue of a dictionary.
/// </summary>
[Serializable]
public struct Pair<TFirst, TSecond>
: IComparable,
IComparable<Pair<TFirst, TSecond>>
{
#region Member Variables
/// <summary>
/// Comparers for the first and second type that are used to compare
/// values.
/// </summary>
private static readonly IComparer<TFirst> firstComparer = Comparer<TFirst>.Default;
private static readonly IComparer<TSecond> secondComparer = Comparer<TSecond>.Default;
/// <summary>
/// Equality Comparers for the first and second types that are used to compare values
/// </summary>
private static readonly IEqualityComparer<TFirst> firstEqualityComparer = EqualityComparer<TFirst>.Default;
private static readonly IEqualityComparer<TSecond> secondEqualityComparer = EqualityComparer<TSecond>.Default;
/// <summary>
/// The first element of the pair.
/// </summary>
private TFirst first;
/// <summary>
/// The second element of the pair.
/// </summary>
private TSecond second;
#endregion
#region Constructors
/// <summary>
/// Creates a new pair with given first and second elements.
/// </summary>
/// <param name="first">The first element of the pair.</param>
/// <param name="second">The second element of the pair.</param>
public Pair(TFirst first, TSecond second)
{
this.first = first;
this.second = second;
}
/// <summary>
/// Creates a new pair using elements from a KeyValuePair structure. The
/// First element gets the Key, and the Second elements gets the Value.
/// </summary>
/// <param name="keyAndValue">The KeyValuePair to initialize the Pair with .</param>
public Pair(KeyValuePair<TFirst, TSecond> keyAndValue)
{
this.first = keyAndValue.Key;
this.second = keyAndValue.Value;
}
#endregion
#region Properties
/// <summary>
/// The first element of the pair.
/// </summary>
/// <value>The first.</value>
public TFirst First
{
get
{
return first;
}
set
{
first = value;
}
}
/// <summary>
/// The second element of the pair.
/// </summary>
/// <value>The second.</value>
public TSecond Second
{
get
{
return second;
}
set
{
second = value;
}
}
#endregion
#region IComparable Implementation
/// <summary>
/// <para> Compares this pair to another pair of the some type. The pairs are compared by using
/// the IComparable<T> or IComparable interface on TFirst and TSecond. The pairs
/// are compared by their first elements first, if their first elements are equal, then they
/// are compared by their second elements.</para>
/// <para>If either TFirst or TSecond does not implement IComparable<T> or IComparable, then
/// an NotSupportedException is thrown, because the pairs cannot be compared.</para>
/// </summary>
/// <param name="obj">The pair to compare to.</param>
/// <returns>
/// An integer indicating how this pair compares to <paramref name="obj"/>. Less
/// than zero indicates this pair is less than <paramref name="obj"/>. Zero indicate this pair is
/// equals to <paramref name="obj"/>. Greater than zero indicates this pair is greater than
/// <paramref name="obj"/>.
/// </returns>
/// <exception cref="ArgumentException"><paramref name="obj"/> is not of the correct type.</exception>
/// <exception cref="NotSupportedException">Either FirstSecond or TSecond is not comparable
/// via the IComparable<T> or IComparable interfaces.</exception>
int IComparable.CompareTo(object obj)
{
if (obj is Pair<TFirst, TSecond>)
return CompareTo((Pair<TFirst, TSecond>)obj);
throw new ArgumentException(Hydra.Framework.Properties.Resources.BadComparandType, "obj");
}
/// <summary>
/// <para> Compares this pair to another pair of the some type. The pairs are compared by using
/// the IComparable<T> or IComparable interface on TFirst and TSecond. The pairs
/// are compared by their first elements first, if their first elements are equal, then they
/// are compared by their second elements.</para>
/// <para>If either TFirst or TSecond does not implement IComparable<T> or IComparable, then
/// an NotSupportedException is thrown, because the pairs cannot be compared.</para>
/// </summary>
/// <param name="other">The pair to compare to.</param>
/// <returns>
/// An integer indicating how this pair compares to <paramref name="other"/>. Less
/// than zero indicates this pair is less than <paramref name="other"/>. Zero indicate this pair is
/// equals to <paramref name="other"/>. Greater than zero indicates this pair is greater than
/// <paramref name="other"/>.
/// </returns>
/// <exception cref="NotSupportedException">Either FirstSecond or TSecond is not comparable
/// via the IComparable<T> or IComparable interfaces.</exception>
public int CompareTo(Pair<TFirst, TSecond> other)
{
try
{
int firstCompare = firstComparer.Compare(First, other.First);
return (firstCompare != 0) ? firstCompare : secondComparer.Compare(Second, other.Second);
}
catch (ArgumentException)
{
// Determine which type caused the problem for a better error message.
if (!typeof(IComparable<TFirst>).IsAssignableFrom(typeof(TFirst)) &&
!typeof(IComparable).IsAssignableFrom(typeof(TFirst)))
{
throw new NotSupportedException(string.Format(Hydra.Framework.Properties.Resources.UncomparableType, typeof(TFirst).FullName));
}
else if (!typeof(IComparable<TSecond>).IsAssignableFrom(typeof(TSecond)) &&
!typeof(IComparable).IsAssignableFrom(typeof(TSecond)))
{
throw new NotSupportedException(string.Format(Hydra.Framework.Properties.Resources.UncomparableType, typeof(TSecond).FullName));
}
else
throw; // Hmmm. Unclear why we got the ArgumentException.
}
}
#endregion
#region Public Methods
/// <summary>
/// Determines if this pair is equal to another pair. The pair is equal if the first and second elements
/// both compare equal using IComparable<T>.Equals or object.Equals.
/// </summary>
/// <param name="other">Pair to compare with for equality.</param>
/// <returns>
/// True if the pairs are equal. False if the pairs are not equal.
/// </returns>
public bool Equals(Pair<TFirst, TSecond> other)
{
return firstEqualityComparer.Equals(First, other.First) && secondEqualityComparer.Equals(Second, other.Second);
}
/// <summary>
/// Converts this Pair to a KeyValuePair. The Key part of the KeyValuePair gets
/// the First element, and the Value part of the KeyValuePair gets the Second
/// elements.
/// </summary>
/// <returns>The KeyValuePair created from this Pair.</returns>
public KeyValuePair<TFirst, TSecond> ToKeyValuePair()
{
return new KeyValuePair<TFirst, TSecond>(this.First, this.Second);
}
#endregion
#region Operators
/// <summary>
/// Determines if two pairs are equal. Two pairs are equal if the first and second elements
/// both compare equal using IComparable<T>.Equals or object.Equals.
/// </summary>
/// <param name="pair1">First pair to compare.</param>
/// <param name="pair2">Second pair to compare.</param>
/// <returns>
/// True if the pairs are equal. False if the pairs are not equal.
/// </returns>
public static bool operator ==(Pair<TFirst, TSecond> pair1, Pair<TFirst, TSecond> pair2)
{
return firstEqualityComparer.Equals(pair1.First, pair2.First) &&
secondEqualityComparer.Equals(pair1.Second, pair2.Second);
}
/// <summary>
/// Determines if two pairs are not equal. Two pairs are equal if the first and second elements
/// both compare equal using IComparable<T>.Equals or object.Equals.
/// </summary>
/// <param name="pair1">First pair to compare.</param>
/// <param name="pair2">Second pair to compare.</param>
/// <returns>
/// True if the pairs are not equal. False if the pairs are equal.
/// </returns>
public static bool operator !=(Pair<TFirst, TSecond> pair1, Pair<TFirst, TSecond> pair2)
{
return !(pair1 == pair2);
}
/// <summary>
/// Converts a Pair to a KeyValuePair. The Key part of the KeyValuePair gets
/// the First element, and the Value part of the KeyValuePair gets the Second
/// elements.
/// </summary>
/// <param name="pair">Pair to convert.</param>
/// <returns>
/// The KeyValuePair created from <paramref name="pair"/>.
/// </returns>
public static explicit operator KeyValuePair<TFirst, TSecond>(Pair<TFirst, TSecond> pair)
{
return new KeyValuePair<TFirst, TSecond>(pair.First, pair.Second);
}
/// <summary>
/// Converts a KeyValuePair structure into a Pair. The
/// First element gets the Key, and the Second element gets the Value.
/// </summary>
/// <param name="keyAndValue">The KeyValuePair to convert.</param>
/// <returns>
/// The Pair created by converted the KeyValuePair into a Pair.
/// </returns>
public static explicit operator Pair<TFirst, TSecond>(KeyValuePair<TFirst, TSecond> keyAndValue)
{
return new Pair<TFirst, TSecond>(keyAndValue);
}
#endregion
#region Overrides
/// <summary>
/// Determines if this pair is equal to another object. The pair is equal to another object
/// if that object is a Pair, both element types are the same, and the first and second elements
/// both compare equal using object.Equals.
/// </summary>
/// <param name="obj">Object to compare for equality.</param>
/// <returns>
/// True if the objects are equal. False if the objects are not equal.
/// </returns>
public override bool Equals(object obj)
{
if (obj != null &&
obj is Pair<TFirst, TSecond>)
{
Pair<TFirst, TSecond> other = (Pair<TFirst, TSecond>)obj;
return Equals(other);
}
else
{
return false;
}
}
/// <summary>
/// Returns a hash code for the pair, suitable for use in a hash-provider or other hashed collection.
/// Two pairs that compare equal (using Equals) will have the same hash code. The hash code for
/// the pair is derived by combining the hash codes for each of the two elements of the pair.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
// Build the hash code from the hash codes of First and Second.
int hashFirst = (First == null) ? 0x61E04917 : First.GetHashCode();
int hashSecond = (Second == null) ? 0x198ED6A3 : Second.GetHashCode();
return hashFirst ^ hashSecond;
}
/// <summary>
/// Returns a string representation of the pair. The string representation of the pair is
/// of the form:
/// <c>First: {0}, Second: {1}</c>
/// where {0} is the result of First.ToString(), and {1} is the result of Second.ToString() (or
/// "null" if they are null.)
/// </summary>
/// <returns>The string representation of the pair.</returns>
public override string ToString()
{
return string.Format("First: {0}, Second: {1}", (First == null) ? "null" : First.ToString(), (Second == null) ? "null" : Second.ToString());
}
#endregion
}
}
| |
using LibGD;
public static class GlobalMembersGdimagestringftex_returnfontpathname
{
#if __cplusplus
#endif
#define GD_H
#define GD_MAJOR_VERSION
#define GD_MINOR_VERSION
#define GD_RELEASE_VERSION
#define GD_EXTRA_VERSION
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_VERSION_STR(mjr, mnr, rev, ext) mjr "." mnr "." rev ext
#define GDXXX_VERSION_STR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_STR(s) gd.gdXXX_SSTR(s)
#define GDXXX_STR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_SSTR(s) #s
#define GDXXX_SSTR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define GD_VERSION_STRING "GD_MAJOR_VERSION" "." "GD_MINOR_VERSION" "." "GD_RELEASE_VERSION" GD_EXTRA_VERSION
#define GD_VERSION_STRING
#if _WIN32 || CYGWIN || _WIN32_WCE
#if BGDWIN32
#if NONDLL
#define BGD_EXPORT_DATA_PROT
#else
#if __GNUC__
#define BGD_EXPORT_DATA_PROT
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllexport)
#define BGD_EXPORT_DATA_PROT
#endif
#endif
#else
#if __GNUC__
#define BGD_EXPORT_DATA_PROT
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllimport)
#define BGD_EXPORT_DATA_PROT
#endif
#endif
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_STDCALL __stdcall
#define BGD_STDCALL
#define BGD_EXPORT_DATA_IMPL
#else
#if HAVE_VISIBILITY
#define BGD_EXPORT_DATA_PROT
#define BGD_EXPORT_DATA_IMPL
#else
#define BGD_EXPORT_DATA_PROT
#define BGD_EXPORT_DATA_IMPL
#endif
#define BGD_STDCALL
#endif
#if BGD_EXPORT_DATA_PROT_ConditionalDefinition1
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition2
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition3
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition4
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#else
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define Bgd.gd_DECLARE(rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#endif
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GD_IO_H
#if VMS
#endif
#if __cplusplus
#endif
#define gdMaxColors
#define gdAlphaMax
#define gdAlphaOpaque
#define gdAlphaTransparent
#define gdRedMax
#define gdGreenMax
#define gdBlueMax
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetAlpha(c) (((c) & 0x7F000000) >> 24)
#define gdTrueColorGetAlpha
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetRed(c) (((c) & 0xFF0000) >> 16)
#define gdTrueColorGetRed
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetGreen(c) (((c) & 0x00FF00) >> 8)
#define gdTrueColorGetGreen
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetBlue(c) ((c) & 0x0000FF)
#define gdTrueColorGetBlue
#define gdEffectReplace
#define gdEffectAlphaBlend
#define gdEffectNormal
#define gdEffectOverlay
#define GD_TRUE
#define GD_FALSE
#define GD_EPSILON
#define M_PI
#define gdDashSize
#define gdStyled
#define gdBrushed
#define gdStyledBrushed
#define gdTiled
#define gdTransparent
#define gdAntiAliased
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gdImageCreatePalette gdImageCreate
#define gdImageCreatePalette
#define gdFTEX_LINESPACE
#define gdFTEX_CHARMAP
#define gdFTEX_RESOLUTION
#define gdFTEX_DISABLE_KERNING
#define gdFTEX_XSHOW
#define gdFTEX_FONTPATHNAME
#define gdFTEX_FONTCONFIG
#define gdFTEX_RETURNFONTPATHNAME
#define gdFTEX_Unicode
#define gdFTEX_Shift_JIS
#define gdFTEX_Big5
#define gdFTEX_Adobe_Custom
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColor(r, g, b) (((r) << 16) + ((g) << 8) + (b))
#define gdTrueColor
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorAlpha(r, g, b, a) (((a) << 24) + ((r) << 16) + ((g) << 8) + (b))
#define gdTrueColorAlpha
#define gdArc
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gdPie gdArc
#define gdPie
#define gdChord
#define gdNoFill
#define gdEdged
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageTrueColor(im) ((im)->trueColor)
#define gdImageTrueColor
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageSX(im) ((im)->sx)
#define gdImageSX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageSY(im) ((im)->sy)
#define gdImageSY
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageColorsTotal(im) ((im)->colorsTotal)
#define gdImageColorsTotal
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageRed(im, c) ((im)->trueColor ? (((c) & 0xFF0000) >> 16) : (im)->red[(c)])
#define gdImageRed
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGreen(im, c) ((im)->trueColor ? (((c) & 0x00FF00) >> 8) : (im)->green[(c)])
#define gdImageGreen
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageBlue(im, c) ((im)->trueColor ? ((c) & 0x0000FF) : (im)->blue[(c)])
#define gdImageBlue
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageAlpha(im, c) ((im)->trueColor ? (((c) & 0x7F000000) >> 24) : (im)->alpha[(c)])
#define gdImageAlpha
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGetTransparent(im) ((im)->transparent)
#define gdImageGetTransparent
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGetInterlaced(im) ((im)->interlace)
#define gdImageGetInterlaced
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImagePalettePixel(im, x, y) (im)->pixels[(y)][(x)]
#define gdImagePalettePixel
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageTrueColorPixel(im, x, y) (im)->tpixels[(y)][(x)]
#define gdImageTrueColorPixel
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageResolutionX(im) (im)->res_x
#define gdImageResolutionX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageResolutionY(im) (im)->res_y
#define gdImageResolutionY
#define GD2_CHUNKSIZE
#define GD2_CHUNKSIZE_MIN
#define GD2_CHUNKSIZE_MAX
#define GD2_VERS
#define GD2_ID
#define GD2_FMT_RAW
#define GD2_FMT_COMPRESSED
#define GD_FLIP_HORINZONTAL
#define GD_FLIP_VERTICAL
#define GD_FLIP_BOTH
#define GD_CMP_IMAGE
#define GD_CMP_NUM_COLORS
#define GD_CMP_COLOR
#define GD_CMP_SIZE_X
#define GD_CMP_SIZE_Y
#define GD_CMP_TRANSPARENT
#define GD_CMP_BACKGROUND
#define GD_CMP_INTERLACE
#define GD_CMP_TRUECOLOR
#define GD_RESOLUTION
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GDFX_H
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GDTEST_TOP_DIR
#define GDTEST_STRING_MAX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEqualsToFile(ex,ac) gd.gdTestImageCompareToFile(__FILE__,__LINE__,NULL,(ex),(ac))
#define gdAssertImageEqualsToFile
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageFileEqualsMsg(ex,ac) gd.gdTestImageCompareFiles(__FILE__,__LINE__,(ms),(ex),(ac))
#define gdAssertImageFileEqualsMsg
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEquals(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac))
#define gdAssertImageEquals
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEqualsMsg(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac))
#define gdAssertImageEqualsMsg
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTestAssert(cond) _gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (cond))
#define gdTestAssert
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTestErrorMsg(...) _gd.gdTestErrorMsg(__FILE__, __LINE__, __VA_ARGS__)
#define gdTestErrorMsg
static int Main()
{
gdFTStringExtra strex = new gdFTStringExtra();
string path = new string(new char[2048]);
path = string.Format("{0}/freetype/DejaVuSans.ttf", GlobalMembersGdtest.DefineConstants.GDTEST_TOP_DIR);
strex.flags = GlobalMembersGdtest.DefineConstants.gdFTEX_RETURNFONTPATHNAME;
strex.fontpath = null;
gd.gdImageStringFTEx(null, null, 0, path, 72, 0, 0, 0, "hello, gd", strex);
if (strex.fontpath == 0)
{
return 1;
}
if (string.Compare(path, strex.fontpath) != 0)
{
return 2;
}
gd.gdFree(strex.fontpath);
return 0;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Insights
{
using Azure;
using Rest;
using 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>
/// EventCategoriesOperations operations.
/// </summary>
internal partial class EventCategoriesOperations : IServiceOperations<MonitorClient>, IEventCategoriesOperations
{
/// <summary>
/// Initializes a new instance of the EventCategoriesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal EventCategoriesOperations(MonitorClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the MonitorClient
/// </summary>
public MonitorClient Client { get; private set; }
/// <summary>
/// get the list of available event categories supported in the Activity Log
/// Service. The current list includes the following: Aministrative, Security,
/// ServiceHealth, Alert, Recommendation, Policy.
/// </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>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<LocalizableString>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
string apiVersion = "2015-04-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("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("/") ? "" : "/")), "providers/microsoft.insights/eventcategories").ToString();
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 System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<LocalizableString>>();
_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<LocalizableString>>(_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;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.