context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyrightD
* 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.Collections.Generic;
using System.Text;
using OMV = OpenMetaverse;
namespace OpenSim.Region.Physics.BulletSPlugin
{
// Classes to allow some type checking for the API
// These hold pointers to allocated objects in the unmanaged space.
// These classes are subclassed by the various physical implementations of
// objects. In particular, there is a version for physical instances in
// unmanaged memory ("unman") and one for in managed memory ("XNA").
// Currently, the instances of these classes are a reference to a
// physical representation and this has no releationship to other
// instances. Someday, refarb the usage of these classes so each instance
// refers to a particular physical instance and this class controls reference
// counts and such. This should be done along with adding BSShapes.
public class BulletWorld
{
public BulletWorld(uint worldId, BSScene bss)
{
worldID = worldId;
physicsScene = bss;
}
public uint worldID;
// The scene is only in here so very low level routines have a handle to print debug/error messages
public BSScene physicsScene;
}
// An allocated Bullet btRigidBody
public class BulletBody
{
public BulletBody(uint id)
{
ID = id;
collisionType = CollisionType.Static;
}
public uint ID;
public CollisionType collisionType;
public virtual void Clear() { }
public virtual bool HasPhysicalBody { get { return false; } }
// Apply the specificed collision mask into the physical world
public virtual bool ApplyCollisionMask(BSScene physicsScene)
{
// Should assert the body has been added to the physical world.
// (The collision masks are stored in the collision proxy cache which only exists for
// a collision body that is in the world.)
return physicsScene.PE.SetCollisionGroupMask(this,
BulletSimData.CollisionTypeMasks[collisionType].group,
BulletSimData.CollisionTypeMasks[collisionType].mask);
}
// Used for log messages for a unique display of the memory/object allocated to this instance
public virtual string AddrString
{
get { return "unknown"; }
}
public override string ToString()
{
StringBuilder buff = new StringBuilder();
buff.Append("<id=");
buff.Append(ID.ToString());
buff.Append(",p=");
buff.Append(AddrString);
buff.Append(",c=");
buff.Append(collisionType);
buff.Append(">");
return buff.ToString();
}
}
public class BulletShape
{
public BulletShape()
{
shapeType = BSPhysicsShapeType.SHAPE_UNKNOWN;
shapeKey = (System.UInt64)FixedShapeKey.KEY_NONE;
isNativeShape = false;
}
public BSPhysicsShapeType shapeType;
public System.UInt64 shapeKey;
public bool isNativeShape;
public virtual void Clear() { }
public virtual bool HasPhysicalShape { get { return false; } }
// Make another reference to this physical object.
public virtual BulletShape Clone() { return new BulletShape(); }
// Return 'true' if this and other refer to the same physical object
public virtual bool ReferenceSame(BulletShape xx) { return false; }
// Used for log messages for a unique display of the memory/object allocated to this instance
public virtual string AddrString
{
get { return "unknown"; }
}
public override string ToString()
{
StringBuilder buff = new StringBuilder();
buff.Append("<p=");
buff.Append(AddrString);
buff.Append(",s=");
buff.Append(shapeType.ToString());
buff.Append(",k=");
buff.Append(shapeKey.ToString("X"));
buff.Append(",n=");
buff.Append(isNativeShape.ToString());
buff.Append(">");
return buff.ToString();
}
}
// An allocated Bullet btConstraint
public class BulletConstraint
{
public BulletConstraint()
{
}
public virtual void Clear() { }
public virtual bool HasPhysicalConstraint { get { return false; } }
// Used for log messages for a unique display of the memory/object allocated to this instance
public virtual string AddrString
{
get { return "unknown"; }
}
}
// An allocated HeightMapThing which holds various heightmap info.
// Made a class rather than a struct so there would be only one
// instance of this and C# will pass around pointers rather
// than making copies.
public class BulletHMapInfo
{
public BulletHMapInfo(uint id, float[] hm, float pSizeX, float pSizeY) {
ID = id;
heightMap = hm;
terrainRegionBase = OMV.Vector3.Zero;
minCoords = new OMV.Vector3(100f, 100f, 25f);
maxCoords = new OMV.Vector3(101f, 101f, 26f);
minZ = maxZ = 0f;
sizeX = pSizeX;
sizeY = pSizeY;
}
public uint ID;
public float[] heightMap;
public OMV.Vector3 terrainRegionBase;
public OMV.Vector3 minCoords;
public OMV.Vector3 maxCoords;
public float sizeX, sizeY;
public float minZ, maxZ;
public BulletShape terrainShape;
public BulletBody terrainBody;
}
// The general class of collsion object.
public enum CollisionType
{
Avatar,
Groundplane,
Terrain,
Static,
Dynamic,
VolumeDetect,
// Linkset, // A linkset should be either Static or Dynamic
LinksetChild,
Unknown
};
// Hold specification of group and mask collision flags for a CollisionType
public struct CollisionTypeFilterGroup
{
public CollisionTypeFilterGroup(CollisionType t, uint g, uint m)
{
type = t;
group = g;
mask = m;
}
public CollisionType type;
public uint group;
public uint mask;
};
public static class BulletSimData
{
// Map of collisionTypes to flags for collision groups and masks.
// An object's 'group' is the collison groups this object belongs to
// An object's 'filter' is the groups another object has to belong to in order to collide with me
// A collision happens if ((obj1.group & obj2.filter) != 0) || ((obj2.group & obj1.filter) != 0)
//
// As mentioned above, don't use the CollisionFilterGroups definitions directly in the code
// but, instead, use references to this dictionary. Finding and debugging
// collision flag problems will be made easier.
public static Dictionary<CollisionType, CollisionTypeFilterGroup> CollisionTypeMasks
= new Dictionary<CollisionType, CollisionTypeFilterGroup>()
{
{ CollisionType.Avatar,
new CollisionTypeFilterGroup(CollisionType.Avatar,
(uint)CollisionFilterGroups.BCharacterGroup,
(uint)CollisionFilterGroups.BAllGroup)
},
{ CollisionType.Groundplane,
new CollisionTypeFilterGroup(CollisionType.Groundplane,
(uint)CollisionFilterGroups.BGroundPlaneGroup,
// (uint)CollisionFilterGroups.BAllGroup)
(uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup))
},
{ CollisionType.Terrain,
new CollisionTypeFilterGroup(CollisionType.Terrain,
(uint)CollisionFilterGroups.BTerrainGroup,
(uint)(CollisionFilterGroups.BAllGroup & ~CollisionFilterGroups.BStaticGroup))
},
{ CollisionType.Static,
new CollisionTypeFilterGroup(CollisionType.Static,
(uint)CollisionFilterGroups.BStaticGroup,
(uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup))
},
{ CollisionType.Dynamic,
new CollisionTypeFilterGroup(CollisionType.Dynamic,
(uint)CollisionFilterGroups.BSolidGroup,
(uint)(CollisionFilterGroups.BAllGroup))
},
{ CollisionType.VolumeDetect,
new CollisionTypeFilterGroup(CollisionType.VolumeDetect,
(uint)CollisionFilterGroups.BSensorTrigger,
(uint)(~CollisionFilterGroups.BSensorTrigger))
},
{ CollisionType.LinksetChild,
new CollisionTypeFilterGroup(CollisionType.LinksetChild,
(uint)CollisionFilterGroups.BLinksetChildGroup,
(uint)(CollisionFilterGroups.BNoneGroup))
// (uint)(CollisionFilterGroups.BCharacterGroup | CollisionFilterGroups.BSolidGroup))
},
};
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
namespace MLifterRecorder.DragNDrop
{
/// <summary>
/// The DragAndDropListView control inherits from ListView, and provides native support for dragging and dropping ListItems to reorder them or move them to other DragAndDropListView controls.
/// http://www.codeproject.com/cs/miscctrl/DragAndDropListView.asp
/// </summary>
/// <remarks>Documented by Dev03, 2007-07-19</remarks>
public class DragAndDropListView : ListView
{
#region Private Members
private ListViewItem m_previousItem;
private bool m_allowReorder;
private Color m_lineColor;
private string m_lock;
#endregion
#region Public Properties
[Category("Behavior")]
public bool AllowReorder
{
get { return m_allowReorder; }
set { m_allowReorder = value; }
}
[Category("Appearance")]
public Color LineColor
{
get { return m_lineColor; }
set { m_lineColor = value; }
}
#endregion
#region Protected and Public Methods
public DragAndDropListView()
: base()
{
m_allowReorder = true;
m_lineColor = Color.Red;
m_lock = "";
}
public void SetLockCode(string lock_code)
{
m_lock = lock_code;
}
public string GetLockCode()
{
return m_lock;
}
protected override void OnDragDrop(DragEventArgs drgevent)
{
if (!m_allowReorder)
{
base.OnDragDrop(drgevent);
return;
}
// get the currently hovered row that the items will be dragged to
Point clientPoint = base.PointToClient(new Point(drgevent.X, drgevent.Y));
ListViewItem hoverItem = base.GetItemAt(clientPoint.X, clientPoint.Y);
if (!drgevent.Data.GetDataPresent(typeof(DragItemData).ToString()) || ((DragItemData)drgevent.Data.GetData(typeof(DragItemData).ToString())).ListView == null || ((DragItemData)drgevent.Data.GetData(typeof(DragItemData).ToString())).DragItems.Count == 0)
return;
// retrieve the drag item data
DragItemData data = (DragItemData)drgevent.Data.GetData(typeof(DragItemData).ToString());
// check if lock condition is ok
if (m_lock != data.ListView.GetLockCode())
return;
if (hoverItem == null)
{
// remove all the selected items from the previous list view
// if the list view was found
if (data.ListView != null)
{
foreach (ListViewItem itemToRemove in data.ListView.SelectedItems)
{
data.ListView.Items.Remove(itemToRemove);
}
}
// the user does not wish to re-order the items, just append to the end
for (int i = 0; i < data.DragItems.Count; i++)
{
ListViewItem newItem = (ListViewItem)data.DragItems[i];
// rename the ListViewItems to their original name
newItem.Name = newItem.Name.Replace("copy_of_", "");
base.Items.Add(newItem);
base.SelectedIndices.Add(base.Items.Count - 1);
}
}
else
{
// the user wishes to re-order the items
// get the index of the hover item
int hoverIndex = hoverItem.Index;
// determine if the items to be dropped are from
// this list view. If they are, perform a hack
// to increment the hover index so that the items
// get moved properly.
if (this == data.ListView)
{
if (hoverIndex > base.SelectedItems[0].Index)
hoverIndex--;
}
// remove all the selected items from the previous list view
// if the list view was found
if (data.ListView != null)
{
foreach (ListViewItem itemToRemove in data.ListView.SelectedItems)
{
data.ListView.Items.Remove(itemToRemove);
}
}
// insert the new items into the list view
// by inserting the items reversely from the array list
for (int i = data.DragItems.Count - 1; i >= 0; i--)
{
ListViewItem newItem = (ListViewItem)data.DragItems[i];
// rename the ListViewItems to their original name
newItem.Name = newItem.Name.Replace("copy_of_", "");
base.Items.Insert(hoverIndex, newItem);
base.SelectedIndices.Add(hoverIndex);
}
}
// set the back color of the previous item, then nullify it
if (m_previousItem != null)
{
m_previousItem = null;
}
this.Invalidate();
// call the base on drag drop to raise the event
base.OnDragDrop(drgevent);
}
protected override void OnDragOver(DragEventArgs drgevent)
{
if (!m_allowReorder)
{
base.OnDragOver(drgevent);
return;
}
if (!drgevent.Data.GetDataPresent(typeof(DragItemData).ToString()))
{
// the item(s) being dragged do not have any data associated
drgevent.Effect = DragDropEffects.None;
return;
}
if (((DragItemData)drgevent.Data.GetData(typeof(DragItemData).ToString())).ListView == null)
return;
// retrieve the drag item data
DragItemData data = (DragItemData)drgevent.Data.GetData(typeof(DragItemData).ToString());
// check if lock condition is ok
if (m_lock != data.ListView.GetLockCode())
{
// the item(s) being dragged do not have any data associated
drgevent.Effect = DragDropEffects.None;
return;
}
if (base.Items.Count > 0)
{
// get the currently hovered row that the items will be dragged to
Point clientPoint = base.PointToClient(new Point(drgevent.X, drgevent.Y));
ListViewItem hoverItem = base.GetItemAt(clientPoint.X, clientPoint.Y);
Graphics g = this.CreateGraphics();
if (hoverItem == null)
{
//MessageBox.Show(base.GetChildAtPoint(new Point(clientPoint.X, clientPoint.Y)).GetType().ToString());
// no item was found, so no drop should take place
drgevent.Effect = DragDropEffects.Move;
if (m_previousItem != null)
{
m_previousItem = null;
Invalidate();
}
hoverItem = base.Items[base.Items.Count - 1];
if (this.View == View.Details || this.View == View.List)
{
using (Pen pen = new Pen(m_lineColor, 2))
{
g.DrawLine(pen, new Point(hoverItem.Bounds.X, hoverItem.Bounds.Y + hoverItem.Bounds.Height), new Point(hoverItem.Bounds.X + this.Bounds.Width, hoverItem.Bounds.Y + hoverItem.Bounds.Height));
}
using (SolidBrush solidBrush = new SolidBrush(m_lineColor))
{
g.FillPolygon(solidBrush, new Point[] { new Point(hoverItem.Bounds.X, hoverItem.Bounds.Y + hoverItem.Bounds.Height - 5), new Point(hoverItem.Bounds.X + 5, hoverItem.Bounds.Y + hoverItem.Bounds.Height), new Point(hoverItem.Bounds.X, hoverItem.Bounds.Y + hoverItem.Bounds.Height + 5) });
}
using (SolidBrush solidBrush = new SolidBrush(m_lineColor))
{
g.FillPolygon(solidBrush, new Point[] { new Point(this.Bounds.Width - 4, hoverItem.Bounds.Y + hoverItem.Bounds.Height - 5), new Point(this.Bounds.Width - 9, hoverItem.Bounds.Y + hoverItem.Bounds.Height), new Point(this.Bounds.Width - 4, hoverItem.Bounds.Y + hoverItem.Bounds.Height + 5) });
}
}
else
{
using (Pen pen = new Pen(m_lineColor, 2))
{
g.DrawLine(pen, new Point(hoverItem.Bounds.X + hoverItem.Bounds.Width, hoverItem.Bounds.Y), new Point(hoverItem.Bounds.X + hoverItem.Bounds.Width, hoverItem.Bounds.Y + hoverItem.Bounds.Height));
}
using (SolidBrush solidBrush = new SolidBrush(m_lineColor))
{
g.FillPolygon(solidBrush, new Point[] { new Point(hoverItem.Bounds.X + hoverItem.Bounds.Width - 5, hoverItem.Bounds.Y), new Point(hoverItem.Bounds.X + hoverItem.Bounds.Width + 5, hoverItem.Bounds.Y), new Point(hoverItem.Bounds.X + hoverItem.Bounds.Width, hoverItem.Bounds.Y + 5) });
}
using (SolidBrush solidBrush = new SolidBrush(m_lineColor))
{
g.FillPolygon(solidBrush, new Point[] { new Point(hoverItem.Bounds.X + hoverItem.Bounds.Width - 5, hoverItem.Bounds.Y + hoverItem.Bounds.Height), new Point(hoverItem.Bounds.X + hoverItem.Bounds.Width + 5, hoverItem.Bounds.Y + hoverItem.Bounds.Height), new Point(hoverItem.Bounds.X + hoverItem.Bounds.Width, hoverItem.Bounds.Y + hoverItem.Bounds.Height - 5) });
}
}
// call the base OnDragOver event
base.OnDragOver(drgevent);
return;
}
// determine if the user is currently hovering over a new
// item. If so, set the previous item's back color back
// to the default color.
if ((m_previousItem != null && m_previousItem != hoverItem) || m_previousItem == null)
{
this.Invalidate();
}
// set the background color of the item being hovered
// and assign the previous item to the item being hovered
//hoverItem.BackColor = Color.Beige;
m_previousItem = hoverItem;
if (this.View == View.Details || this.View == View.List)
{
using (Pen pen = new Pen(m_lineColor, 2))
{
g.DrawLine(pen, new Point(hoverItem.Bounds.X, hoverItem.Bounds.Y), new Point(hoverItem.Bounds.X + this.Bounds.Width, hoverItem.Bounds.Y));
}
using (SolidBrush solidBrush = new SolidBrush(m_lineColor))
{
g.FillPolygon(solidBrush, new Point[] { new Point(hoverItem.Bounds.X, hoverItem.Bounds.Y - 5), new Point(hoverItem.Bounds.X + 5, hoverItem.Bounds.Y), new Point(hoverItem.Bounds.X, hoverItem.Bounds.Y + 5) });
}
using (SolidBrush solidBrush = new SolidBrush(m_lineColor))
{
g.FillPolygon(solidBrush, new Point[] { new Point(this.Bounds.Width - 4, hoverItem.Bounds.Y - 5), new Point(this.Bounds.Width - 9, hoverItem.Bounds.Y), new Point(this.Bounds.Width - 4, hoverItem.Bounds.Y + 5) });
}
}
else
{
using (Pen pen = new Pen(m_lineColor, 2))
{
g.DrawLine(pen, new Point(hoverItem.Bounds.X, hoverItem.Bounds.Y), new Point(hoverItem.Bounds.X, hoverItem.Bounds.Y + hoverItem.Bounds.Height));
}
using (SolidBrush solidBrush = new SolidBrush(m_lineColor))
{
g.FillPolygon(solidBrush, new Point[] { new Point(hoverItem.Bounds.X - 5, hoverItem.Bounds.Y), new Point(hoverItem.Bounds.X + 5, hoverItem.Bounds.Y), new Point(hoverItem.Bounds.X, hoverItem.Bounds.Y + 5) });
}
using (SolidBrush solidBrush = new SolidBrush(m_lineColor))
{
g.FillPolygon(solidBrush, new Point[] { new Point(hoverItem.Bounds.X - 5, hoverItem.Bounds.Y + hoverItem.Bounds.Height), new Point(hoverItem.Bounds.X + 5, hoverItem.Bounds.Y + hoverItem.Bounds.Height), new Point(hoverItem.Bounds.X, hoverItem.Bounds.Y + hoverItem.Bounds.Height - 5) });
}
}
// go through each of the selected items, and if any of the
// selected items have the same index as the item being
// hovered, disable dropping.
foreach (ListViewItem itemToMove in base.SelectedItems)
{
if (itemToMove.Index == hoverItem.Index)
{
drgevent.Effect = DragDropEffects.None;
hoverItem.EnsureVisible();
return;
}
}
// ensure that the hover item is visible
hoverItem.EnsureVisible();
}
// everything is fine, allow the user to move the items
drgevent.Effect = DragDropEffects.Move;
// call the base OnDragOver event
base.OnDragOver(drgevent);
}
protected override void OnDragEnter(DragEventArgs drgevent)
{
if (!m_allowReorder)
{
base.OnDragEnter(drgevent);
return;
}
if (!drgevent.Data.GetDataPresent(typeof(DragItemData).ToString()))
{
// the item(s) being dragged do not have any data associated
drgevent.Effect = DragDropEffects.None;
return;
}
// everything is fine, allow the user to move the items
drgevent.Effect = DragDropEffects.Move;
// call the base OnDragEnter event
base.OnDragEnter(drgevent);
}
protected override void OnItemDrag(ItemDragEventArgs e)
{
if (!m_allowReorder)
{
base.OnItemDrag(e);
return;
}
// call the DoDragDrop method
base.DoDragDrop(GetDataForDragDrop(), DragDropEffects.Move);
// call the base OnItemDrag event
base.OnItemDrag(e);
}
protected override void OnLostFocus(EventArgs e)
{
// reset the selected items background and remove the previous item
ResetOutOfRange();
Invalidate();
// call the OnLostFocus event
base.OnLostFocus(e);
}
protected override void OnDragLeave(EventArgs e)
{
// reset the selected items background and remove the previous item
ResetOutOfRange();
Invalidate();
// call the base OnDragLeave event
base.OnDragLeave(e);
}
#endregion
#region Private Methods
private DragItemData GetDataForDragDrop()
{
// create a drag item data object that will be used to pass along with the drag and drop
DragItemData data = new DragItemData(this);
// go through each of the selected items and
// add them to the drag items collection
// by creating a clone of the list item
foreach (ListViewItem item in this.SelectedItems)
{
object copied_item = item.Clone();
(copied_item as ListViewItem).Name = "copy_of_" + item.Name;
//System.Diagnostics.Debug.Print("\n*********************************************\nName-"+(copied_item as ListViewItem).Name+"-End Name\n*********************************************\n");
data.DragItems.Add(copied_item);
}
return data;
}
private void ResetOutOfRange()
{
// determine if the previous item exists,
// if it does, reset the background and release
// the previous item
if (m_previousItem != null)
{
m_previousItem = null;
}
}
#endregion
#region DragItemData Class
private class DragItemData
{
#region Private Members
private DragAndDropListView m_listView;
private ArrayList m_dragItems;
#endregion
#region Public Properties
public DragAndDropListView ListView
{
get { return m_listView; }
}
public ArrayList DragItems
{
get { return m_dragItems; }
}
#endregion
#region Public Methods and Implementation
public DragItemData(DragAndDropListView listView)
{
m_listView = listView;
m_dragItems = new ArrayList();
}
#endregion
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
namespace Lewis.SST.Help
{
/// <summary>
/// Class to display About/error message form.
/// </summary>
public class About : System.Windows.Forms.Form
{
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.TextBox txtCRT;
private System.Windows.Forms.TextBox txtCompany;
private System.Windows.Forms.TextBox txtComments;
private System.Windows.Forms.TextBox txtDescription;
private System.Windows.Forms.TextBox txtVer;
private System.Windows.Forms.TextBox txtProductName;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Panel panelAbout;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.RichTextBox rtxtHelp;
private System.Windows.Forms.Button btnOk;
private System.Windows.Forms.PictureBox Logo;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private string _message;
/// <summary>
/// Initializes a new instance of the <see cref="About"/> class.
/// </summary>
public About()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
initHelpMsg();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="a"></param>
/// <param name="message"></param>
public About(Assembly a, string message)
{
InitializeComponent();
_message = message;
if (a != null)
{
this.txtCompany.Text = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).CompanyName;
this.txtCRT.Text = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).LegalCopyright;
this.txtProductName.Text = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).ProductName;
this.txtDescription.Text = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).FileDescription;
this.txtComments.Text = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).Comments;
this.txtVer.Text = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).FileVersion;
}
initHelpMsg();
}
/// <summary>
/// The about class constructor
/// </summary>
/// <param name="a">assembly</param>
public About(Assembly a)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
if (a != null)
{
this.txtCompany.Text = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).CompanyName;
this.txtCRT.Text = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).LegalCopyright;
this.txtProductName.Text = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).ProductName;
this.txtDescription.Text = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).FileDescription;
this.txtComments.Text = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).Comments;
this.txtVer.Text = System.Diagnostics.FileVersionInfo.GetVersionInfo(a.Location).FileVersion;
}
initHelpMsg();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(About));
this.panel1 = new System.Windows.Forms.Panel();
this.Logo = new System.Windows.Forms.PictureBox();
this.panelAbout = new System.Windows.Forms.Panel();
this.txtCRT = new System.Windows.Forms.TextBox();
this.txtCompany = new System.Windows.Forms.TextBox();
this.txtComments = new System.Windows.Forms.TextBox();
this.txtDescription = new System.Windows.Forms.TextBox();
this.txtVer = new System.Windows.Forms.TextBox();
this.txtProductName = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.rtxtHelp = new System.Windows.Forms.RichTextBox();
this.btnOk = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.Logo)).BeginInit();
this.panelAbout.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.BackColor = System.Drawing.Color.LightSteelBlue;
this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(434, 16);
this.panel1.TabIndex = 0;
//
// Logo
//
this.Logo.BackColor = System.Drawing.Color.White;
this.Logo.Dock = System.Windows.Forms.DockStyle.Top;
this.Logo.Image = ((System.Drawing.Image)(resources.GetObject("Logo.Image")));
this.Logo.Location = new System.Drawing.Point(0, 16);
this.Logo.Name = "Logo";
this.Logo.Size = new System.Drawing.Size(434, 55);
this.Logo.TabIndex = 16;
this.Logo.TabStop = false;
//
// panelAbout
//
this.panelAbout.Controls.Add(this.txtCRT);
this.panelAbout.Controls.Add(this.txtCompany);
this.panelAbout.Controls.Add(this.txtComments);
this.panelAbout.Controls.Add(this.txtDescription);
this.panelAbout.Controls.Add(this.txtVer);
this.panelAbout.Controls.Add(this.txtProductName);
this.panelAbout.Controls.Add(this.label6);
this.panelAbout.Controls.Add(this.label5);
this.panelAbout.Controls.Add(this.label4);
this.panelAbout.Controls.Add(this.label3);
this.panelAbout.Controls.Add(this.label2);
this.panelAbout.Controls.Add(this.label1);
this.panelAbout.Dock = System.Windows.Forms.DockStyle.Top;
this.panelAbout.Location = new System.Drawing.Point(0, 71);
this.panelAbout.Name = "panelAbout";
this.panelAbout.Size = new System.Drawing.Size(434, 146);
this.panelAbout.TabIndex = 1;
//
// txtCRT
//
this.txtCRT.Location = new System.Drawing.Point(81, 24);
this.txtCRT.Name = "txtCRT";
this.txtCRT.ReadOnly = true;
this.txtCRT.Size = new System.Drawing.Size(346, 20);
this.txtCRT.TabIndex = 3;
this.txtCRT.WordWrap = false;
//
// txtCompany
//
this.txtCompany.Location = new System.Drawing.Point(81, 3);
this.txtCompany.Name = "txtCompany";
this.txtCompany.ReadOnly = true;
this.txtCompany.Size = new System.Drawing.Size(346, 20);
this.txtCompany.TabIndex = 1;
this.txtCompany.WordWrap = false;
//
// txtComments
//
this.txtComments.Location = new System.Drawing.Point(81, 121);
this.txtComments.Name = "txtComments";
this.txtComments.ReadOnly = true;
this.txtComments.Size = new System.Drawing.Size(346, 20);
this.txtComments.TabIndex = 11;
this.txtComments.WordWrap = false;
//
// txtDescription
//
this.txtDescription.Location = new System.Drawing.Point(81, 101);
this.txtDescription.Name = "txtDescription";
this.txtDescription.ReadOnly = true;
this.txtDescription.Size = new System.Drawing.Size(346, 20);
this.txtDescription.TabIndex = 9;
this.txtDescription.WordWrap = false;
//
// txtVer
//
this.txtVer.Location = new System.Drawing.Point(81, 73);
this.txtVer.Name = "txtVer";
this.txtVer.ReadOnly = true;
this.txtVer.Size = new System.Drawing.Size(346, 20);
this.txtVer.TabIndex = 7;
this.txtVer.WordWrap = false;
//
// txtProductName
//
this.txtProductName.Location = new System.Drawing.Point(81, 52);
this.txtProductName.Name = "txtProductName";
this.txtProductName.ReadOnly = true;
this.txtProductName.Size = new System.Drawing.Size(346, 20);
this.txtProductName.TabIndex = 5;
this.txtProductName.WordWrap = false;
//
// label6
//
this.label6.Location = new System.Drawing.Point(7, 24);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(67, 21);
this.label6.TabIndex = 2;
this.label6.Text = "Copyright:";
this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label5
//
this.label5.Location = new System.Drawing.Point(7, 3);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(67, 21);
this.label5.TabIndex = 0;
this.label5.Text = "Company:";
this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label4
//
this.label4.Location = new System.Drawing.Point(7, 121);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(67, 21);
this.label4.TabIndex = 10;
this.label4.Text = "Description:";
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label3
//
this.label3.Location = new System.Drawing.Point(7, 101);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(67, 20);
this.label3.TabIndex = 8;
this.label3.Text = "Title:";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label2
//
this.label2.Location = new System.Drawing.Point(21, 73);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 21);
this.label2.TabIndex = 6;
this.label2.Text = "Version:";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label1
//
this.label1.Location = new System.Drawing.Point(21, 52);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(53, 21);
this.label1.TabIndex = 4;
this.label1.Text = "Product:";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// panel2
//
this.panel2.Controls.Add(this.rtxtHelp);
this.panel2.Controls.Add(this.btnOk);
this.panel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel2.Location = new System.Drawing.Point(0, 217);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(434, 210);
this.panel2.TabIndex = 2;
//
// rtxtHelp
//
this.rtxtHelp.AcceptsTab = true;
this.rtxtHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.rtxtHelp.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.rtxtHelp.Location = new System.Drawing.Point(7, 4);
this.rtxtHelp.Name = "rtxtHelp";
this.rtxtHelp.ReadOnly = true;
this.rtxtHelp.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.ForcedVertical;
this.rtxtHelp.Size = new System.Drawing.Size(420, 162);
this.rtxtHelp.TabIndex = 0;
this.rtxtHelp.Text = "Command Line Options:";
this.rtxtHelp.WordWrap = false;
//
// btnOk
//
this.btnOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOk.Location = new System.Drawing.Point(344, 172);
this.btnOk.Name = "btnOk";
this.btnOk.Size = new System.Drawing.Size(60, 24);
this.btnOk.TabIndex = 1;
this.btnOk.Text = "Okay";
this.btnOk.Click += new System.EventHandler(this.btnOk_Click);
//
// About
//
this.AcceptButton = this.btnOk;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(434, 427);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panelAbout);
this.Controls.Add(this.Logo);
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "About";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "About the DTS Command Line Tool";
((System.ComponentModel.ISupportInitialize)(this.Logo)).EndInit();
this.panelAbout.ResumeLayout(false);
this.panelAbout.PerformLayout();
this.panel2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void btnOk_Click(object sender, System.EventArgs e)
{
this.Close();
}
/// <summary>
/// Shows the text method shows the current about information.
/// </summary>
/// <param name="text">The text.</param>
public void ShowText(string text)
{
this.panelAbout.Visible = false;
initHelpMsg(text);
this.Text = "DTS Package Information:";
this.Height = this.panel1.Height + this.panel2.Height + this.Logo.Height + this.btnOk.Height + 20;
this.ShowDialog();
}
/// <summary>
/// public property to set the message property to value
/// </summary>
public string Message
{
set { _message = value; }
}
private void initHelpMsg(string text)
{
UTF8Encoding e = new UTF8Encoding();
rtxtHelp.LoadFile(new MemoryStream(e.GetBytes(text.ToCharArray())), RichTextBoxStreamType.PlainText);
}
private void initHelpMsg()
{
String strHlpMsg = null;
this.panelAbout.Visible = true;
if (_message != null)
{
initHelpMsg(_message);
}
else
{
strHlpMsg = strHlpMsg + @"{\rtf1\ansi\b ";
strHlpMsg = strHlpMsg + @"Command Line Parameters:\b0 \par[/?] or [help]\tab\tab - display this window.\par ";
strHlpMsg = strHlpMsg + @"[/d]\tab\tab\tab - display debug messages, [/h] overrides this.\par ";
strHlpMsg = strHlpMsg + @"[/f logfile name]\tab\tab - set the package logging file name.\par ";
strHlpMsg = strHlpMsg + @"[/e password]\tab\tab - set the package password.\par ";
strHlpMsg = strHlpMsg + @"[/h]\tab\tab\tab - hide all debug and error message windows.\par ";
strHlpMsg = strHlpMsg + @"[/i \{packageID\}]\tab\tab - sets the package ID to use.\par ";
strHlpMsg = strHlpMsg + @"\tab\tab\tab ...use with [/n] option.\par ";
strHlpMsg = strHlpMsg + @"[/l DTS/XML file name]\tab - load package from DTS/XML file.\par ";
strHlpMsg = strHlpMsg + @"\tab\tab\tab ...use with [/n] option.\par ";
strHlpMsg = strHlpMsg + @"\tab\tab\tab ...automatically adds the .XML extension.\par ";
strHlpMsg = strHlpMsg + @"[/n DTSPackageName]\tab - sets the DTS Package Name.\par ";
strHlpMsg = strHlpMsg + @"\tab\tab\tab ...this is a \b REQUIRED\b0 parameter.\par ";
strHlpMsg = strHlpMsg + @"[/p password]\tab\tab - change the default admin password.\par ";
strHlpMsg = strHlpMsg + @"[/r]\tab\tab\tab - remove the existing DTS package by name.\par ";
strHlpMsg = strHlpMsg + @"\tab\tab\tab ...use with [/n] option.\par ";
strHlpMsg = strHlpMsg + @"[/pi]\tab\tab\tab - return package ID and version information.\par ";
strHlpMsg = strHlpMsg + @"\tab\tab\tab ...use with [/n] option.\par ";
strHlpMsg = strHlpMsg + @"[/s sqlservername]\tab\tab - change the default server.\par ";
strHlpMsg = strHlpMsg + @"\tab\tab\tab ...this defaults to the local machine name.\par ";
strHlpMsg = strHlpMsg + @"[/t]\tab\tab\tab - tests the SQL server connection, then exits.\par ";
strHlpMsg = strHlpMsg + @"[/u username]\tab\tab - change the default admin user.\par ";
strHlpMsg = strHlpMsg + @"[/v \{versionID\}]\tab\tab - sets the version ID to use.\par ";
strHlpMsg = strHlpMsg + @"\tab\tab\tab ...use with [/n] option.\par ";
strHlpMsg = strHlpMsg + @"[/w]\tab\tab\tab - use Windows authentication for SQL server.\par ";
strHlpMsg = strHlpMsg + @"\tab\tab\tab ...overrides SQL mixed mode settings.\par ";
strHlpMsg = strHlpMsg + @"\tab\tab\tab ...use with load, remove and save operations.\par ";
strHlpMsg = strHlpMsg + @"[/x XML file name]\tab\tab - output package to XML file.\par ";
strHlpMsg = strHlpMsg + @"\tab\tab\tab ...automatically adds the .XML extension.\par ";
strHlpMsg = strHlpMsg + @"\tab\tab\tab ...use with [/n] option.\par ";
strHlpMsg = strHlpMsg + "}";
initHelpMsg(strHlpMsg);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using CoreFoundation;
using CoreGraphics;
using Foundation;
using Mapsui.UI.iOS.Extensions;
using Mapsui.Utilities;
using SkiaSharp.Views.iOS;
using UIKit;
#nullable enable
namespace Mapsui.UI.iOS
{
[Register("MapControl"), DesignTimeVisible(true)]
public partial class MapControl : UIView, IMapControl
{
private readonly SKGLView _canvas = new SKGLView();
private double _innerRotation;
public MapControl(CGRect frame)
: base(frame)
{
CommonInitialize();
Initialize();
}
[Preserve]
public MapControl(IntPtr handle) : base(handle) // used when initialized from storyboard
{
CommonInitialize();
Initialize();
}
private void Initialize()
{
_invalidate = () => {
RunOnUIThread(() => {
SetNeedsDisplay();
_canvas?.SetNeedsDisplay();
});
};
BackgroundColor = UIColor.White;
_canvas.TranslatesAutoresizingMaskIntoConstraints = false;
_canvas.MultipleTouchEnabled = true;
_canvas.PaintSurface += OnPaintSurface;
AddSubview(_canvas);
AddConstraints(new[]
{
NSLayoutConstraint.Create(this, NSLayoutAttribute.Leading, NSLayoutRelation.Equal, _canvas,
NSLayoutAttribute.Leading, 1.0f, 0.0f),
NSLayoutConstraint.Create(this, NSLayoutAttribute.Trailing, NSLayoutRelation.Equal, _canvas,
NSLayoutAttribute.Trailing, 1.0f, 0.0f),
NSLayoutConstraint.Create(this, NSLayoutAttribute.Top, NSLayoutRelation.Equal, _canvas,
NSLayoutAttribute.Top, 1.0f, 0.0f),
NSLayoutConstraint.Create(this, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, _canvas,
NSLayoutAttribute.Bottom, 1.0f, 0.0f)
});
ClipsToBounds = true;
MultipleTouchEnabled = true;
UserInteractionEnabled = true;
var doubleTapGestureRecognizer = new UITapGestureRecognizer(OnDoubleTapped)
{
NumberOfTapsRequired = 2,
CancelsTouchesInView = false,
};
AddGestureRecognizer(doubleTapGestureRecognizer);
var tapGestureRecognizer = new UITapGestureRecognizer(OnSingleTapped)
{
NumberOfTapsRequired = 1,
CancelsTouchesInView = false,
};
tapGestureRecognizer.RequireGestureRecognizerToFail(doubleTapGestureRecognizer);
AddGestureRecognizer(tapGestureRecognizer);
_viewport.SetSize(ViewportWidth, ViewportHeight);
}
private void OnDoubleTapped(UITapGestureRecognizer gesture)
{
var position = GetScreenPosition(gesture.LocationInView(this));
OnInfo(InvokeInfo(position, position, 2));
}
private void OnSingleTapped(UITapGestureRecognizer gesture)
{
var position = GetScreenPosition(gesture.LocationInView(this));
OnInfo(InvokeInfo(position, position, 1));
}
private void OnPaintSurface(object sender, SKPaintGLSurfaceEventArgs args)
{
if (PixelDensity <= 0)
return;
var canvas = args.Surface.Canvas;
canvas.Scale(PixelDensity, PixelDensity);
CommonDrawControl(canvas);
}
public override void TouchesBegan(NSSet touches, UIEvent? evt)
{
base.TouchesBegan(touches, evt);
_innerRotation = Viewport.Rotation;
}
public override void TouchesMoved(NSSet touches, UIEvent? evt)
{
base.TouchesMoved(touches, evt);
if (evt?.AllTouches.Count == 1)
{
if (touches.AnyObject is UITouch touch)
{
var position = touch.LocationInView(this).ToMapsui();
var previousPosition = touch.PreviousLocationInView(this).ToMapsui();
_viewport.Transform(position, previousPosition);
RefreshGraphics();
_innerRotation = Viewport.Rotation;
}
}
else if (evt?.AllTouches.Count >= 2)
{
var previousLocation = evt.AllTouches.Select(t => ((UITouch)t).PreviousLocationInView(this))
.Select(p => new MPoint(p.X, p.Y)).ToList();
var locations = evt.AllTouches.Select(t => ((UITouch)t).LocationInView(this))
.Select(p => new MPoint(p.X, p.Y)).ToList();
var (previousCenter, previousRadius, previousAngle) = GetPinchValues(previousLocation);
var (center, radius, angle) = GetPinchValues(locations);
double rotationDelta = 0;
if (!(Map?.RotationLock ?? false))
{
_innerRotation += angle - previousAngle;
_innerRotation %= 360;
if (_innerRotation > 180)
_innerRotation -= 360;
else if (_innerRotation < -180)
_innerRotation += 360;
if (Viewport.Rotation == 0 && Math.Abs(_innerRotation) >= Math.Abs(UnSnapRotationDegrees))
rotationDelta = _innerRotation;
else if (Viewport.Rotation != 0)
{
if (Math.Abs(_innerRotation) <= Math.Abs(ReSnapRotationDegrees))
rotationDelta = -Viewport.Rotation;
else
rotationDelta = _innerRotation - Viewport.Rotation;
}
}
_viewport.Transform(center, previousCenter, radius / previousRadius, rotationDelta);
RefreshGraphics();
}
}
public override void TouchesEnded(NSSet touches, UIEvent? e)
{
Refresh();
}
/// <summary>
/// Gets screen position in device independent units (or DIP or DP).
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
private MPoint GetScreenPosition(CGPoint point)
{
return new MPoint(point.X, point.Y);
}
private void RunOnUIThread(Action action)
{
DispatchQueue.MainQueue.DispatchAsync(action);
}
public override CGRect Frame
{
get => base.Frame;
set
{
_canvas.Frame = value;
base.Frame = value;
SetViewportSize();
OnPropertyChanged();
}
}
public override void LayoutMarginsDidChange()
{
if (_canvas == null) return;
base.LayoutMarginsDidChange();
SetViewportSize();
}
public void OpenBrowser(string url)
{
UIApplication.SharedApplication.OpenUrl(new NSUrl(url));
}
public new void Dispose()
{
IosCommonDispose(true);
base.Dispose();
}
protected override void Dispose(bool disposing)
{
IosCommonDispose(disposing);
base.Dispose(disposing);
}
private void IosCommonDispose(bool disposing)
{
if (disposing)
{
_map?.Dispose();
Unsubscribe();
_canvas?.Dispose();
}
CommonDispose(disposing);
}
private static (MPoint centre, double radius, double angle) GetPinchValues(List<MPoint> locations)
{
if (locations.Count < 2)
throw new ArgumentException();
double centerX = 0;
double centerY = 0;
foreach (var location in locations)
{
centerX += location.X;
centerY += location.Y;
}
centerX = centerX / locations.Count;
centerY = centerY / locations.Count;
var radius = Algorithms.Distance(centerX, centerY, locations[0].X, locations[0].Y);
var angle = Math.Atan2(locations[1].Y - locations[0].Y, locations[1].X - locations[0].X) * 180.0 / Math.PI;
return (new MPoint(centerX, centerY), radius, angle);
}
private float ViewportWidth => (float)_canvas.Frame.Width; // todo: check if we need _canvas
private float ViewportHeight => (float)_canvas.Frame.Height; // todo: check if we need _canvas
private float GetPixelDensity()
{
return (float)_canvas.ContentScaleFactor; // todo: Check if I need canvas
}
}
}
| |
/*
* @author Valentin Simonov / http://va.lent.in/
* @author Valentin Frolov
* @author Andrew David Griffiths
*/
#if UNITY_STANDALONE_WIN
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using TouchScript.Pointers;
using TouchScript.Utils;
using TouchScript.Utils.Platform;
using UnityEngine;
namespace TouchScript.InputSources.InputHandlers
{
/// <summary>
/// Windows 8 pointer handling implementation which can be embedded to other (input) classes. Uses WindowsTouch.dll to query native touches with WM_TOUCH or WM_POINTER APIs.
/// </summary>
public class Windows8PointerHandler : WindowsPointerHandler
{
#region Public properties
/// <summary>
/// Should the primary pointer also dispatch a mouse pointer.
/// </summary>
public bool MouseInPointer
{
get { return mouseInPointer; }
set
{
WindowsUtils.EnableMouseInPointer(value);
mouseInPointer = value;
if (mouseInPointer)
{
if (mousePointer == null) mousePointer = internalAddMousePointer(Vector3.zero);
}
else
{
if (mousePointer != null)
{
if ((mousePointer.Buttons & Pointer.PointerButtonState.AnyButtonPressed) != 0)
{
mousePointer.Buttons = PointerUtils.UpPressedButtons(mousePointer.Buttons);
releasePointer(mousePointer);
}
removePointer(mousePointer);
}
}
}
}
#endregion
#region Private variables
private bool mouseInPointer = true;
#endregion
#region Constructor
/// <inheritdoc />
public Windows8PointerHandler(PointerDelegate addPointer, PointerDelegate updatePointer, PointerDelegate pressPointer, PointerDelegate releasePointer, PointerDelegate removePointer, PointerDelegate cancelPointer) : base(addPointer, updatePointer, pressPointer, releasePointer, removePointer, cancelPointer)
{
mousePool = new ObjectPool<MousePointer>(4, () => new MousePointer(this), null, resetPointer);
penPool = new ObjectPool<PenPointer>(2, () => new PenPointer(this), null, resetPointer);
mousePointer = internalAddMousePointer(Vector3.zero);
init(TOUCH_API.WIN8);
}
#endregion
#region Public methods
/// <inheritdoc />
public override bool UpdateInput()
{
base.UpdateInput();
return true;
}
/// <inheritdoc />
public override bool CancelPointer(Pointer pointer, bool shouldReturn)
{
if (pointer.Equals(mousePointer))
{
cancelPointer(mousePointer);
if (shouldReturn) mousePointer = internalReturnMousePointer(mousePointer);
else mousePointer = internalAddMousePointer(pointer.Position); // can't totally cancel mouse pointer
return true;
}
if (pointer.Equals(penPointer))
{
cancelPointer(penPointer);
if (shouldReturn) penPointer = internalReturnPenPointer(penPointer);
return true;
}
return base.CancelPointer(pointer, shouldReturn);
}
/// <inheritdoc />
public override void Dispose()
{
if (mousePointer != null)
{
cancelPointer(mousePointer);
mousePointer = null;
}
if (penPointer != null)
{
cancelPointer(penPointer);
penPointer = null;
}
WindowsUtils.EnableMouseInPointer(false);
base.Dispose();
}
#endregion
#region Internal methods
/// <inheritdoc />
public override void INTERNAL_DiscardPointer(Pointer pointer)
{
if (pointer is MousePointer) mousePool.Release(pointer as MousePointer);
else if (pointer is PenPointer) penPool.Release(pointer as PenPointer);
else base.INTERNAL_DiscardPointer(pointer);
}
#endregion
}
public class Windows7PointerHandler : WindowsPointerHandler
{
/// <inheritdoc />
public Windows7PointerHandler(PointerDelegate addPointer, PointerDelegate updatePointer, PointerDelegate pressPointer, PointerDelegate releasePointer, PointerDelegate removePointer, PointerDelegate cancelPointer) : base(addPointer, updatePointer, pressPointer, releasePointer, removePointer, cancelPointer)
{
init(TOUCH_API.WIN7);
}
#region Public methods
/// <inheritdoc />
public override bool UpdateInput()
{
base.UpdateInput();
return winTouchToInternalId.Count > 0;
}
#endregion
}
/// <summary>
/// Base class for Windows 8 and Windows 7 input handlers.
/// </summary>
public abstract class WindowsPointerHandler : IInputSource, IDisposable
{
#region Consts
/// <summary>
/// Windows constant to turn off press and hold visual effect.
/// </summary>
public const string PRESS_AND_HOLD_ATOM = "MicrosoftTabletPenServiceProperty";
/// <summary>
/// The method delegate used to pass data from the native DLL.
/// </summary>
/// <param name="id">Pointer id.</param>
/// <param name="evt">Current event.</param>
/// <param name="type">Pointer type.</param>
/// <param name="position">Pointer position.</param>
/// <param name="data">Pointer data.</param>
protected delegate void NativePointerDelegate(int id, PointerEvent evt, PointerType type, Vector2 position, PointerData data);
/// <summary>
/// The method delegate used to pass log messages from the native DLL.
/// </summary>
/// <param name="log">The log message.</param>
protected delegate void NativeLog([MarshalAs(UnmanagedType.BStr)] string log);
#endregion
#region Public properties
/// <inheritdoc />
public ICoordinatesRemapper CoordinatesRemapper { get; set; }
#endregion
#region Private variables
private NativePointerDelegate nativePointerDelegate;
private NativeLog nativeLogDelegate;
protected PointerDelegate addPointer;
protected PointerDelegate updatePointer;
protected PointerDelegate pressPointer;
protected PointerDelegate releasePointer;
protected PointerDelegate removePointer;
protected PointerDelegate cancelPointer;
protected IntPtr hMainWindow;
protected ushort pressAndHoldAtomID;
protected Dictionary<int, TouchPointer> winTouchToInternalId = new Dictionary<int, TouchPointer>(10);
protected ObjectPool<TouchPointer> touchPool;
protected ObjectPool<MousePointer> mousePool;
protected ObjectPool<PenPointer> penPool;
protected MousePointer mousePointer;
protected PenPointer penPointer;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="WindowsPointerHandler"/> class.
/// </summary>
/// <param name="addPointer">A function called when a new pointer is detected.</param>
/// <param name="updatePointer">A function called when a pointer is moved or its parameter is updated.</param>
/// <param name="pressPointer">A function called when a pointer touches the surface.</param>
/// <param name="releasePointer">A function called when a pointer is lifted off.</param>
/// <param name="removePointer">A function called when a pointer is removed.</param>
/// <param name="cancelPointer">A function called when a pointer is cancelled.</param>
public WindowsPointerHandler(PointerDelegate addPointer, PointerDelegate updatePointer, PointerDelegate pressPointer, PointerDelegate releasePointer, PointerDelegate removePointer, PointerDelegate cancelPointer)
{
this.addPointer = addPointer;
this.updatePointer = updatePointer;
this.pressPointer = pressPointer;
this.releasePointer = releasePointer;
this.removePointer = removePointer;
this.cancelPointer = cancelPointer;
nativeLogDelegate = nativeLog;
nativePointerDelegate = nativePointer;
touchPool = new ObjectPool<TouchPointer>(10, () => new TouchPointer(this), null, resetPointer);
hMainWindow = WindowsUtils.GetActiveWindow();
disablePressAndHold();
setScaling();
}
#endregion
#region Public methods
/// <inheritdoc />
public virtual bool UpdateInput()
{
return false;
}
/// <inheritdoc />
public virtual void UpdateResolution()
{
setScaling();
if (mousePointer != null) TouchManager.Instance.CancelPointer(mousePointer.Id);
}
/// <inheritdoc />
public virtual bool CancelPointer(Pointer pointer, bool shouldReturn)
{
var touch = pointer as TouchPointer;
if (touch == null) return false;
int internalTouchId = -1;
foreach (var t in winTouchToInternalId)
{
if (t.Value == touch)
{
internalTouchId = t.Key;
break;
}
}
if (internalTouchId > -1)
{
cancelPointer(touch);
winTouchToInternalId.Remove(internalTouchId);
if (shouldReturn) winTouchToInternalId[internalTouchId] = internalReturnTouchPointer(touch);
return true;
}
return false;
}
/// <summary>
/// Releases resources.
/// </summary>
public virtual void Dispose()
{
foreach (var i in winTouchToInternalId) cancelPointer(i.Value);
winTouchToInternalId.Clear();
enablePressAndHold();
DisposePlugin();
}
#endregion
#region Internal methods
/// <inheritdoc />
public virtual void INTERNAL_DiscardPointer(Pointer pointer)
{
var p = pointer as TouchPointer;
if (p == null) return;
touchPool.Release(p);
}
#endregion
#region Protected methods
protected TouchPointer internalAddTouchPointer(Vector2 position)
{
var pointer = touchPool.Get();
pointer.Position = remapCoordinates(position);
pointer.Buttons |= Pointer.PointerButtonState.FirstButtonDown | Pointer.PointerButtonState.FirstButtonPressed;
addPointer(pointer);
pressPointer(pointer);
return pointer;
}
protected TouchPointer internalReturnTouchPointer(TouchPointer pointer)
{
var newPointer = touchPool.Get();
newPointer.CopyFrom(pointer);
pointer.Buttons |= Pointer.PointerButtonState.FirstButtonDown | Pointer.PointerButtonState.FirstButtonPressed;
newPointer.Flags |= Pointer.FLAG_RETURNED;
addPointer(newPointer);
pressPointer(newPointer);
return newPointer;
}
protected void internalRemoveTouchPointer(TouchPointer pointer)
{
pointer.Buttons &= ~Pointer.PointerButtonState.FirstButtonPressed;
pointer.Buttons |= Pointer.PointerButtonState.FirstButtonUp;
releasePointer(pointer);
removePointer(pointer);
}
protected MousePointer internalAddMousePointer(Vector2 position)
{
var pointer = mousePool.Get();
pointer.Position = remapCoordinates(position);
addPointer(pointer);
return pointer;
}
protected MousePointer internalReturnMousePointer(MousePointer pointer)
{
var newPointer = mousePool.Get();
newPointer.CopyFrom(pointer);
newPointer.Flags |= Pointer.FLAG_RETURNED;
addPointer(newPointer);
if ((newPointer.Buttons & Pointer.PointerButtonState.AnyButtonPressed) != 0)
{
// Adding down state this frame
newPointer.Buttons = PointerUtils.DownPressedButtons(newPointer.Buttons);
pressPointer(newPointer);
}
return newPointer;
}
protected PenPointer internalAddPenPointer(Vector2 position)
{
if (penPointer != null) throw new InvalidOperationException("One pen pointer is already registered! Trying to add another one.");
var pointer = penPool.Get();
pointer.Position = remapCoordinates(position);
addPointer(pointer);
return pointer;
}
protected void internalRemovePenPointer(PenPointer pointer)
{
removePointer(pointer);
penPointer = null;
}
protected PenPointer internalReturnPenPointer(PenPointer pointer)
{
var newPointer = penPool.Get();
newPointer.CopyFrom(pointer);
newPointer.Flags |= Pointer.FLAG_RETURNED;
addPointer(newPointer);
if ((newPointer.Buttons & Pointer.PointerButtonState.AnyButtonPressed) != 0)
{
// Adding down state this frame
newPointer.Buttons = PointerUtils.DownPressedButtons(newPointer.Buttons);
pressPointer(newPointer);
}
return newPointer;
}
protected void init(TOUCH_API api)
{
Init(api, nativeLogDelegate, nativePointerDelegate);
}
protected Vector2 remapCoordinates(Vector2 position)
{
if (CoordinatesRemapper != null) return CoordinatesRemapper.Remap(position);
return position;
}
protected void resetPointer(Pointer p)
{
p.INTERNAL_Reset();
}
#endregion
#region Private functions
private void disablePressAndHold()
{
// https://msdn.microsoft.com/en-us/library/bb969148(v=vs.85).aspx
pressAndHoldAtomID = WindowsUtils.GlobalAddAtom(PRESS_AND_HOLD_ATOM);
WindowsUtils.SetProp(hMainWindow, PRESS_AND_HOLD_ATOM,
WindowsUtils.TABLET_DISABLE_PRESSANDHOLD | // disables press and hold (right-click) gesture
WindowsUtils.TABLET_DISABLE_PENTAPFEEDBACK | // disables UI feedback on pen up (waves)
WindowsUtils.TABLET_DISABLE_PENBARRELFEEDBACK | // disables UI feedback on pen button down (circle)
WindowsUtils.TABLET_DISABLE_FLICKS // disables pen flicks (back, forward, drag down, drag up);
);
}
private void enablePressAndHold()
{
if (pressAndHoldAtomID != 0)
{
WindowsUtils.RemoveProp(hMainWindow, PRESS_AND_HOLD_ATOM);
WindowsUtils.GlobalDeleteAtom(pressAndHoldAtomID);
}
}
private void setScaling()
{
var screenWidth = Screen.width;
var screenHeight = Screen.height;
if (!Screen.fullScreen)
{
SetScreenParams(screenWidth, screenHeight, 0, 0, 1, 1);
return;
}
int width, height;
WindowsUtils.GetNativeMonitorResolution(out width, out height);
float scale = Mathf.Max(screenWidth / ((float) width), screenHeight / ((float) height));
SetScreenParams(screenWidth, screenHeight, (width - screenWidth / scale) * .5f, (height - screenHeight / scale) * .5f, scale, scale);
}
#endregion
#region Pointer callbacks
private void nativeLog(string log)
{
Debug.Log("[WindowsTouch.dll]: " + log);
}
private void nativePointer(int id, PointerEvent evt, PointerType type, Vector2 position, PointerData data)
{
switch (type)
{
case PointerType.Mouse:
switch (evt)
{
// Enter and Exit are not used - mouse is always present
// TODO: how does it work with 2+ mice?
case PointerEvent.Enter:
throw new NotImplementedException("This is not supposed to be called o.O");
case PointerEvent.Leave:
break;
case PointerEvent.Down:
mousePointer.Buttons = updateButtons(mousePointer.Buttons, data.PointerFlags, data.ChangedButtons);
pressPointer(mousePointer);
break;
case PointerEvent.Up:
mousePointer.Buttons = updateButtons(mousePointer.Buttons, data.PointerFlags, data.ChangedButtons);
releasePointer(mousePointer);
break;
case PointerEvent.Update:
mousePointer.Position = position;
mousePointer.Buttons = updateButtons(mousePointer.Buttons, data.PointerFlags, data.ChangedButtons);
updatePointer(mousePointer);
break;
case PointerEvent.Cancelled:
cancelPointer(mousePointer);
// can't cancel the mouse pointer, it is always present
mousePointer = internalAddMousePointer(mousePointer.Position);
break;
}
break;
case PointerType.Touch:
TouchPointer touchPointer;
switch (evt)
{
case PointerEvent.Enter:
break;
case PointerEvent.Leave:
// Sometimes Windows might not send Up, so have to execute touch release logic here.
// Has been working fine on test devices so far.
if (winTouchToInternalId.TryGetValue(id, out touchPointer))
{
winTouchToInternalId.Remove(id);
internalRemoveTouchPointer(touchPointer);
}
break;
case PointerEvent.Down:
touchPointer = internalAddTouchPointer(position);
touchPointer.Rotation = getTouchRotation(ref data);
touchPointer.Pressure = getTouchPressure(ref data);
winTouchToInternalId.Add(id, touchPointer);
break;
case PointerEvent.Up:
break;
case PointerEvent.Update:
if (!winTouchToInternalId.TryGetValue(id, out touchPointer)) return;
touchPointer.Position = position;
touchPointer.Rotation = getTouchRotation(ref data);
touchPointer.Pressure = getTouchPressure(ref data);
updatePointer(touchPointer);
break;
case PointerEvent.Cancelled:
if (winTouchToInternalId.TryGetValue(id, out touchPointer))
{
winTouchToInternalId.Remove(id);
cancelPointer(touchPointer);
}
break;
}
break;
case PointerType.Pen:
switch (evt)
{
case PointerEvent.Enter:
penPointer = internalAddPenPointer(position);
penPointer.Pressure = getPenPressure(ref data);
penPointer.Rotation = getPenRotation(ref data);
break;
case PointerEvent.Leave:
if (penPointer == null) break;
internalRemovePenPointer(penPointer);
break;
case PointerEvent.Down:
if (penPointer == null) break;
penPointer.Buttons = updateButtons(penPointer.Buttons, data.PointerFlags, data.ChangedButtons);
penPointer.Pressure = getPenPressure(ref data);
penPointer.Rotation = getPenRotation(ref data);
pressPointer(penPointer);
break;
case PointerEvent.Up:
if (penPointer == null) break;
mousePointer.Buttons = updateButtons(penPointer.Buttons, data.PointerFlags, data.ChangedButtons);
releasePointer(penPointer);
break;
case PointerEvent.Update:
if (penPointer == null) break;
penPointer.Position = position;
penPointer.Pressure = getPenPressure(ref data);
penPointer.Rotation = getPenRotation(ref data);
penPointer.Buttons = updateButtons(penPointer.Buttons, data.PointerFlags, data.ChangedButtons);
updatePointer(penPointer);
break;
case PointerEvent.Cancelled:
if (penPointer == null) break;
cancelPointer(penPointer);
break;
}
break;
}
}
private Pointer.PointerButtonState updateButtons(Pointer.PointerButtonState current, PointerFlags flags, ButtonChangeType change)
{
var currentUpDown = ((uint) current) & 0xFFFFFC00;
var pressed = ((uint) flags >> 4) & 0x1F;
var newUpDown = 0U;
if (change != ButtonChangeType.None) newUpDown = 1U << (10 + (int) change);
var combined = (Pointer.PointerButtonState) (pressed | newUpDown | currentUpDown);
return combined;
}
private float getTouchPressure(ref PointerData data)
{
var reliable = (data.Mask & (uint) TouchMask.Pressure) > 0;
if (reliable) return data.Pressure / 1024f;
return TouchPointer.DEFAULT_PRESSURE;
}
private float getTouchRotation(ref PointerData data)
{
var reliable = (data.Mask & (uint) TouchMask.Orientation) > 0;
if (reliable) return data.Rotation / 180f * Mathf.PI;
return TouchPointer.DEFAULT_ROTATION;
}
private float getPenPressure(ref PointerData data)
{
var reliable = (data.Mask & (uint) PenMask.Pressure) > 0;
if (reliable) return data.Pressure / 1024f;
return PenPointer.DEFAULT_PRESSURE;
}
private float getPenRotation(ref PointerData data)
{
var reliable = (data.Mask & (uint) PenMask.Rotation) > 0;
if (reliable) return data.Rotation / 180f * Mathf.PI;
return PenPointer.DEFAULT_ROTATION;
}
#endregion
#region p/invoke
protected enum TOUCH_API
{
WIN7,
WIN8
}
protected enum PointerEvent : uint
{
Enter = 0x0249,
Leave = 0x024A,
Update = 0x0245,
Down = 0x0246,
Up = 0x0247,
Cancelled = 0x1000
}
protected enum PointerType
{
Pointer = 0x00000001,
Touch = 0x00000002,
Pen = 0x00000003,
Mouse = 0x00000004,
TouchPad = 0x00000005
}
[Flags]
protected enum PointerFlags
{
None = 0x00000000,
New = 0x00000001,
InRange = 0x00000002,
InContact = 0x00000004,
FirstButton = 0x00000010,
SecondButton = 0x00000020,
ThirdButton = 0x00000040,
FourthButton = 0x00000080,
FifthButton = 0x00000100,
Primary = 0x00002000,
Confidence = 0x00004000,
Canceled = 0x00008000,
Down = 0x00010000,
Update = 0x00020000,
Up = 0x00040000,
Wheel = 0x00080000,
HWheel = 0x00100000,
CaptureChanged = 0x00200000,
HasTransform = 0x00400000
}
protected enum ButtonChangeType
{
None,
FirstDown,
FirstUp,
SecondDown,
SecondUp,
ThirdDown,
ThirdUp,
FourthDown,
FourthUp,
FifthDown,
FifthUp
}
[Flags]
protected enum TouchFlags
{
None = 0x00000000
}
[Flags]
protected enum TouchMask
{
None = 0x00000000,
ContactArea = 0x00000001,
Orientation = 0x00000002,
Pressure = 0x00000004
}
[Flags]
protected enum PenFlags
{
None = 0x00000000,
Barrel = 0x00000001,
Inverted = 0x00000002,
Eraser = 0x00000004
}
[Flags]
protected enum PenMask
{
None = 0x00000000,
Pressure = 0x00000001,
Rotation = 0x00000002,
TiltX = 0x00000004,
TiltY = 0x00000008
}
[StructLayout(LayoutKind.Sequential)]
protected struct PointerData
{
public PointerFlags PointerFlags;
public uint Flags;
public uint Mask;
public ButtonChangeType ChangedButtons;
public uint Rotation;
public uint Pressure;
public int TiltX;
public int TiltY;
}
[DllImport("WindowsTouch", CallingConvention = CallingConvention.StdCall)]
private static extern void Init(TOUCH_API api, NativeLog log, NativePointerDelegate pointerDelegate);
[DllImport("WindowsTouch", EntryPoint = "Dispose", CallingConvention = CallingConvention.StdCall)]
private static extern void DisposePlugin();
[DllImport("WindowsTouch", CallingConvention = CallingConvention.StdCall)]
private static extern void SetScreenParams(int width, int height, float offsetX, float offsetY, float scaleX, float scaleY);
#endregion
}
}
#endif
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
// Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com)
// David Stephensen (mailto:David.Stephensen@pdfsharp.com)
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// Andrew Tsekhansky (mailto:pakeha07@gmail.com): Table rendering optimization in 2010
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using MigraDoc.DocumentObjectModel.IO;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.DocumentObjectModel.Visitors;
using MigraDoc.DocumentObjectModel.Internals;
namespace MigraDoc.DocumentObjectModel.Visitors
{
/// <summary>
/// Represents a merged list of cells of a table.
/// </summary>
public class MergedCellList
{
/// <summary>
/// Enumeration of neighbor positions of cells in a table.
/// </summary>
private enum NeighborPosition
{
Top,
Left,
Right,
Bottom
}
/// <summary>
/// Initializes a new instance of the MergedCellList class.
/// </summary>
public MergedCellList(Table table)
{
Init(table);
}
private int RowCount;
private int ColCount;
private Table Table;
private CellInfo[,] CellInfos;
private Hashtable CellIndex;
/// <summary>
/// Initializes this instance from a table.
/// </summary>
private void Init(Table table)
{
Table = table;
RowCount = Table.Rows.Count;
ColCount = Table.Columns.Count;
CellIndex = new Hashtable();
CellInfos = new CellInfo[RowCount, ColCount];
for (int rwIdx = 0; rwIdx < RowCount; rwIdx++)
{
for (int clmIdx = 0; clmIdx < ColCount; clmIdx++)
{
Cell cell = table[rwIdx, clmIdx];
if (CellInfos[rwIdx, clmIdx] == null)
{
for (int mx = 0; mx <= cell.MergeRight; mx++)
for (int my = 0; my <= cell.MergeDown; my++)
{
bool isMergedCell = mx > 0 || my > 0;
CellInfo cellInfo = new CellInfo();
cellInfo.TableCell = table[rwIdx + my, clmIdx + mx];
cellInfo.Cell = cell;
cellInfo.IsMergedCell = isMergedCell;
cellInfo.MergedWith = isMergedCell ? CellInfos[rwIdx, clmIdx] : null;
cellInfo.Row = rwIdx;
cellInfo.Col = clmIdx;
CellInfos[rwIdx + my, clmIdx + mx] = cellInfo;
CellIndex[cellInfo.TableCell] = CellInfos[rwIdx, clmIdx];
}
}
}
}
}
public IEnumerable<Cell> GetCells()
{
return GetCells(0, this.RowCount - 1);
}
public IEnumerable<Cell> GetRowCells(int row)
{
return GetCells(row, row);
}
public IEnumerable<Cell> GetCells(int startRow, int endRow)
{
for (int rowIndex = startRow; rowIndex <= endRow; rowIndex++)
for (int colIndex = 0; colIndex < ColCount; colIndex++)
{
CellInfo cellInfo = CellInfos[rowIndex, colIndex];
if (!cellInfo.IsMergedCell)
yield return cellInfo.Cell;
colIndex += cellInfo.Cell.MergeRight;
}
}
private static Borders GetCellBorders(Cell cell)
{
return cell.HasBorders ? cell.Borders : null; //AndrewT: optimization return cell.GetValue("Borders", GV.ReadOnly) as Borders;
}
/// <summary>
/// Gets a borders object that should be used for rendering.
/// </summary>
/// <exception cref="System.ArgumentException">
/// Thrown when the cell is not in this list.
/// This situation occurs if the given cell is merged "away" by a previous one.
/// </exception>
public Borders GetEffectiveBorders(Cell cell)
{
CellInfo cellInfo = this.CellIndex[cell] as CellInfo;
if (cellInfo == null)
throw new ArgumentException("cell is not a relevant cell", "cell");
if (cellInfo.Borders == null)
{
Borders borders = GetCellBorders(cell);
if (borders != null)
{
Document doc = borders.Document;
borders = borders.Clone();
borders.parent = cell;
doc = borders.Document;
}
else
borders = new Borders(cell.parent);
if (cell.mergeRight > 0)
{
Cell rightBorderCell = cell.Table[cell.Row.Index, cell.Column.Index + cell.mergeRight];
if (rightBorderCell.borders != null && rightBorderCell.borders.right != null)
borders.Right = rightBorderCell.borders.right.Clone();
else
borders.right = null;
}
if (cell.mergeDown > 0)
{
Cell bottomBorderCell = cell.Table[cell.Row.Index + cell.mergeDown, cell.Column.Index];
if (bottomBorderCell.borders != null && bottomBorderCell.borders.bottom != null)
borders.Bottom = bottomBorderCell.borders.bottom.Clone();
else
borders.bottom = null;
}
Cell leftNeighbor = GetNeighbor(cellInfo, NeighborPosition.Left);
Cell rightNeighbor = GetNeighbor(cellInfo, NeighborPosition.Right);
Cell topNeighbor = GetNeighbor(cellInfo, NeighborPosition.Top);
Cell bottomNeighbor = GetNeighbor(cellInfo, NeighborPosition.Bottom);
if (leftNeighbor != null)
{
Borders nbrBrdrs = GetCellBorders(leftNeighbor);
if (nbrBrdrs != null && GetEffectiveBorderWidth(nbrBrdrs, BorderType.Right) >= GetEffectiveBorderWidth(borders, BorderType.Left))
borders.SetValue("Left", GetBorderFromBorders(nbrBrdrs, BorderType.Right));
}
if (rightNeighbor != null)
{
Borders nbrBrdrs = GetCellBorders(rightNeighbor);
if (nbrBrdrs != null && GetEffectiveBorderWidth(nbrBrdrs, BorderType.Left) > GetEffectiveBorderWidth(borders, BorderType.Right))
borders.SetValue("Right", GetBorderFromBorders(nbrBrdrs, BorderType.Left));
}
if (topNeighbor != null)
{
Borders nbrBrdrs = GetCellBorders(topNeighbor);
if (nbrBrdrs != null && GetEffectiveBorderWidth(nbrBrdrs, BorderType.Bottom) >= GetEffectiveBorderWidth(borders, BorderType.Top))
borders.SetValue("Top", GetBorderFromBorders(nbrBrdrs, BorderType.Bottom));
}
if (bottomNeighbor != null)
{
Borders nbrBrdrs = GetCellBorders(bottomNeighbor);
if (nbrBrdrs != null && GetEffectiveBorderWidth(nbrBrdrs, BorderType.Top) > GetEffectiveBorderWidth(borders, BorderType.Bottom))
borders.SetValue("Bottom", GetBorderFromBorders(nbrBrdrs, BorderType.Top));
}
cellInfo.Borders = borders;
}
else
{
cellInfo.Borders = cell.borders;
if (cell.mergeRight > 0)
{
Cell rightBorderCell = cell.Table[cell.Row.Index, cell.Column.Index + cell.mergeRight];
if (rightBorderCell.borders != null && rightBorderCell.borders.right != null)
cellInfo.Borders.Right = rightBorderCell.borders.right.Clone();
else
cellInfo.Borders.right = null;
}
}
return cellInfo.Borders;
}
/// <summary>
/// Gets the cell that covers the given cell by merging. Usually the cell itself if not merged.
/// </summary>
public Cell GetCoveringCell(Cell cell)
{
return ((CellInfo)CellIndex[cell]).Cell;
}
/// <summary>
/// Returns the border of the given borders-object of the specified type (top, bottom, ...).
/// If that border doesn't exist, it returns a new border object that inherits all properties from the given borders object
/// </summary>
private Border GetBorderFromBorders(Borders borders, BorderType type)
{
Border returnBorder = borders.GetValue(type.ToString(), GV.ReadOnly) as Border;
if (returnBorder == null)
{
returnBorder = new Border();
returnBorder.style = borders.style;
returnBorder.width = borders.width;
returnBorder.color = borders.color;
returnBorder.visible = borders.visible;
}
return returnBorder;
}
/// <summary>
/// Returns the width of the border at the specified position.
/// </summary>
private Unit GetEffectiveBorderWidth(Borders borders, BorderType type)
{
if (borders == null)
return 0;
return borders.GetEffectiveWidth(type);
}
/// <summary>
/// Gets the specified cell's uppermost neighbor at the specified position.
/// </summary>
private Cell GetNeighbor(CellInfo cellInfo, NeighborPosition position)
{
Cell cell = cellInfo.Cell;
switch (position)
{
case NeighborPosition.Left:
if (cellInfo.BlockCol > 0)
return CellInfos[cellInfo.BlockRow, cellInfo.BlockCol - 1].Cell;
break;
case NeighborPosition.Right:
if (cellInfo.BlockCol + cell.MergeRight < ColCount - 1)
return CellInfos[cellInfo.BlockRow, cellInfo.BlockCol + cell.MergeRight + 1].Cell;
break;
case NeighborPosition.Top:
if (cellInfo.BlockRow > 0)
return CellInfos[cellInfo.BlockRow - 1, cellInfo.BlockCol].Cell;
break;
case NeighborPosition.Bottom:
if (cellInfo.BlockRow + cell.MergeDown < RowCount - 1)
return CellInfos[cellInfo.BlockRow + cell.MergeDown + 1, cellInfo.BlockCol].Cell;
break;
}
//Cell cell = cellInfo.CoverCell;
//if (cell.Column.Index == 0 && position == NeighborPosition.Left ||
// cell.Row.Index == 0 && position == NeighborPosition.Top ||
// cell.Row.Index + cell.MergeDown == cell.Table.Rows.Count - 1 && position == NeighborPosition.Bottom ||
// cell.Column.Index + cell.MergeRight == cell.Table.Columns.Count - 1 && position == NeighborPosition.Right)
// return null;
//switch (position)
//{
// case NeighborPosition.Top:
// case NeighborPosition.Left:
// for (int index = cellIdx - 1; index >= 0; --index)
// {
// Cell currCell = this[index];
// if (IsNeighbor(cell, currCell, position))
// return currCell;
// }
// break;
// case NeighborPosition.Right:
// if (cellIdx + 1 < this.Count)
// {
// Cell cell2 = this[cellIdx + 1];
// if (cell2.Row.Index == cell.Row.Index)
// return cell2;
// }
// for (int index = cellIdx - 1; index >= 0; --index)
// {
// Cell currCell = this[index];
// if (IsNeighbor(cell, currCell, position))
// return currCell;
// }
// break;
// case NeighborPosition.Bottom:
// for (int index = cellIdx + 1; index < this.Count; ++index)
// {
// Cell currCell = this[index];
// if (IsNeighbor(cell, currCell, position))
// return currCell;
// }
// break;
//}
return null;
}
public int CalcLastConnectedRow(int row)
{
int lastConnectedRow = row;
for (int rowIndex = row; rowIndex <= lastConnectedRow && rowIndex < this.RowCount; rowIndex++)
{
int downConnection = rowIndex;
for (int colIndex = 0; colIndex < this.ColCount; colIndex++)
{
CellInfo cellInfo = CellInfos[rowIndex, colIndex];
downConnection = Math.Max(downConnection, cellInfo.BlockRow + Math.Max(cellInfo.Cell.Row.KeepWith, cellInfo.Cell.MergeDown));
colIndex += cellInfo.Cell.MergeRight;
}
lastConnectedRow = Math.Max(lastConnectedRow, downConnection);
}
return Math.Min(this.RowCount - 1, lastConnectedRow);
}
public int CalcLastConnectedColumn(int column)
{
int lastConnectedColumn = column;
for (int colIndex = column; colIndex <= lastConnectedColumn && colIndex < this.ColCount; colIndex++)
{
int rightConnection = column;
for (int rowIndex = 0; rowIndex < this.RowCount; rowIndex++)
{
CellInfo cellInfo = CellInfos[rowIndex, colIndex];
cellInfo = cellInfo.MergedWith ?? cellInfo;
rightConnection = Math.Max(rightConnection, cellInfo.BlockCol + Math.Max(cellInfo.Cell.Column.KeepWith, cellInfo.Cell.MergeRight));
rowIndex += cellInfo.Cell.MergeDown;
}
lastConnectedColumn = Math.Max(lastConnectedColumn, rightConnection);
}
return Math.Min(lastConnectedColumn, this.ColCount);
}
}
internal class CellInfo
{
// Cell from table at given Row, Col
public Cell TableCell;
// Cell which fills given Row, Col
public Cell Cell;
// Whether cell is merged with another cell
public bool IsMergedCell;
// CellInfo this cell is merged with
public CellInfo MergedWith;
// Cell's Row
public int Row;
// Cells' Col
public int Col;
// Row where merged area starts
public int BlockRow
{
get
{
return MergedWith == null ? Row : MergedWith.Row;
}
}
// Col where merged area starts
public int BlockCol
{
get
{
return MergedWith == null ? Col : MergedWith.Col;
}
}
public Borders Borders;
}
}
| |
#pragma warning disable CS1591
using Discord.API.Gateway;
using Discord.Net.Queue;
using Discord.Net.Rest;
using Discord.Net.WebSockets;
using Discord.WebSocket;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GameModel = Discord.API.Game;
namespace Discord.API
{
internal class DiscordSocketApiClient : DiscordRestApiClient
{
public event Func<GatewayOpCode, Task> SentGatewayMessage { add { _sentGatewayMessageEvent.Add(value); } remove { _sentGatewayMessageEvent.Remove(value); } }
private readonly AsyncEvent<Func<GatewayOpCode, Task>> _sentGatewayMessageEvent = new AsyncEvent<Func<GatewayOpCode, Task>>();
public event Func<GatewayOpCode, int?, string, object, Task> ReceivedGatewayEvent { add { _receivedGatewayEvent.Add(value); } remove { _receivedGatewayEvent.Remove(value); } }
private readonly AsyncEvent<Func<GatewayOpCode, int?, string, object, Task>> _receivedGatewayEvent = new AsyncEvent<Func<GatewayOpCode, int?, string, object, Task>>();
public event Func<Exception, Task> Disconnected { add { _disconnectedEvent.Add(value); } remove { _disconnectedEvent.Remove(value); } }
private readonly AsyncEvent<Func<Exception, Task>> _disconnectedEvent = new AsyncEvent<Func<Exception, Task>>();
private readonly bool _isExplicitUrl;
private CancellationTokenSource _connectCancelToken;
private string _gatewayUrl;
//Store our decompression streams for zlib shared state
private MemoryStream _compressed;
private DeflateStream _decompressor;
internal IWebSocketClient WebSocketClient { get; }
public ConnectionState ConnectionState { get; private set; }
public DiscordSocketApiClient(RestClientProvider restClientProvider, WebSocketProvider webSocketProvider, string userAgent,
string url = null, RetryMode defaultRetryMode = RetryMode.AlwaysRetry, JsonSerializer serializer = null,
RateLimitPrecision rateLimitPrecision = RateLimitPrecision.Second,
bool useSystemClock = true)
: base(restClientProvider, userAgent, defaultRetryMode, serializer, rateLimitPrecision, useSystemClock)
{
_gatewayUrl = url;
if (url != null)
_isExplicitUrl = true;
WebSocketClient = webSocketProvider();
//WebSocketClient.SetHeader("user-agent", DiscordConfig.UserAgent); (Causes issues in .NET Framework 4.6+)
WebSocketClient.BinaryMessage += async (data, index, count) =>
{
using (var decompressed = new MemoryStream())
{
if (data[0] == 0x78)
{
//Strip the zlib header
_compressed.Write(data, index + 2, count - 2);
_compressed.SetLength(count - 2);
}
else
{
_compressed.Write(data, index, count);
_compressed.SetLength(count);
}
//Reset positions so we don't run out of memory
_compressed.Position = 0;
_decompressor.CopyTo(decompressed);
_compressed.Position = 0;
decompressed.Position = 0;
using (var reader = new StreamReader(decompressed))
using (var jsonReader = new JsonTextReader(reader))
{
var msg = _serializer.Deserialize<SocketFrame>(jsonReader);
if (msg != null)
await _receivedGatewayEvent.InvokeAsync((GatewayOpCode)msg.Operation, msg.Sequence, msg.Type, msg.Payload).ConfigureAwait(false);
}
}
};
WebSocketClient.TextMessage += async text =>
{
using (var reader = new StringReader(text))
using (var jsonReader = new JsonTextReader(reader))
{
var msg = _serializer.Deserialize<SocketFrame>(jsonReader);
if (msg != null)
await _receivedGatewayEvent.InvokeAsync((GatewayOpCode)msg.Operation, msg.Sequence, msg.Type, msg.Payload).ConfigureAwait(false);
}
};
WebSocketClient.Closed += async ex =>
{
await DisconnectAsync().ConfigureAwait(false);
await _disconnectedEvent.InvokeAsync(ex).ConfigureAwait(false);
};
}
internal override void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
_connectCancelToken?.Dispose();
(WebSocketClient as IDisposable)?.Dispose();
_decompressor?.Dispose();
_compressed?.Dispose();
}
_isDisposed = true;
}
base.Dispose(disposing);
}
public async Task ConnectAsync()
{
await _stateLock.WaitAsync().ConfigureAwait(false);
try
{
await ConnectInternalAsync().ConfigureAwait(false);
}
finally { _stateLock.Release(); }
}
/// <exception cref="InvalidOperationException">The client must be logged in before connecting.</exception>
/// <exception cref="NotSupportedException">This client is not configured with WebSocket support.</exception>
internal override async Task ConnectInternalAsync()
{
if (LoginState != LoginState.LoggedIn)
throw new InvalidOperationException("The client must be logged in before connecting.");
if (WebSocketClient == null)
throw new NotSupportedException("This client is not configured with WebSocket support.");
RequestQueue.ClearGatewayBuckets();
//Re-create streams to reset the zlib state
_compressed?.Dispose();
_decompressor?.Dispose();
_compressed = new MemoryStream();
_decompressor = new DeflateStream(_compressed, CompressionMode.Decompress);
ConnectionState = ConnectionState.Connecting;
try
{
_connectCancelToken?.Dispose();
_connectCancelToken = new CancellationTokenSource();
if (WebSocketClient != null)
WebSocketClient.SetCancelToken(_connectCancelToken.Token);
if (!_isExplicitUrl)
{
var gatewayResponse = await GetGatewayAsync().ConfigureAwait(false);
_gatewayUrl = $"{gatewayResponse.Url}?v={DiscordConfig.APIVersion}&encoding={DiscordSocketConfig.GatewayEncoding}&compress=zlib-stream";
}
await WebSocketClient.ConnectAsync(_gatewayUrl).ConfigureAwait(false);
ConnectionState = ConnectionState.Connected;
}
catch
{
if (!_isExplicitUrl)
_gatewayUrl = null; //Uncache in case the gateway url changed
await DisconnectInternalAsync().ConfigureAwait(false);
throw;
}
}
public async Task DisconnectAsync(Exception ex = null)
{
await _stateLock.WaitAsync().ConfigureAwait(false);
try
{
await DisconnectInternalAsync(ex).ConfigureAwait(false);
}
finally { _stateLock.Release(); }
}
/// <exception cref="NotSupportedException">This client is not configured with WebSocket support.</exception>
internal override async Task DisconnectInternalAsync(Exception ex = null)
{
if (WebSocketClient == null)
throw new NotSupportedException("This client is not configured with WebSocket support.");
if (ConnectionState == ConnectionState.Disconnected) return;
ConnectionState = ConnectionState.Disconnecting;
try { _connectCancelToken?.Cancel(false); }
catch { }
if (ex is GatewayReconnectException)
await WebSocketClient.DisconnectAsync(4000);
else
await WebSocketClient.DisconnectAsync().ConfigureAwait(false);
ConnectionState = ConnectionState.Disconnected;
}
//Core
public Task SendGatewayAsync(GatewayOpCode opCode, object payload, RequestOptions options = null)
=> SendGatewayInternalAsync(opCode, payload, options);
private async Task SendGatewayInternalAsync(GatewayOpCode opCode, object payload, RequestOptions options)
{
CheckState();
//TODO: Add ETF
byte[] bytes = null;
payload = new SocketFrame { Operation = (int)opCode, Payload = payload };
if (payload != null)
bytes = Encoding.UTF8.GetBytes(SerializeJson(payload));
options.IsGatewayBucket = true;
if (options.BucketId == null)
options.BucketId = GatewayBucket.Get(GatewayBucketType.Unbucketed).Id;
await RequestQueue.SendAsync(new WebSocketRequest(WebSocketClient, bytes, true, opCode == GatewayOpCode.Heartbeat, options)).ConfigureAwait(false);
await _sentGatewayMessageEvent.InvokeAsync(opCode).ConfigureAwait(false);
}
public async Task SendIdentifyAsync(int largeThreshold = 100, int shardID = 0, int totalShards = 1, bool guildSubscriptions = true, GatewayIntents? gatewayIntents = null, (UserStatus, bool, long?, GameModel)? presence = null, RequestOptions options = null)
{
options = RequestOptions.CreateOrClone(options);
var props = new Dictionary<string, string>
{
["$device"] = "Discord.Net"
};
var msg = new IdentifyParams()
{
Token = AuthToken,
Properties = props,
LargeThreshold = largeThreshold
};
if (totalShards > 1)
msg.ShardingParams = new int[] { shardID, totalShards };
options.BucketId = GatewayBucket.Get(GatewayBucketType.Identify).Id;
if (gatewayIntents.HasValue)
msg.Intents = (int)gatewayIntents.Value;
else
msg.GuildSubscriptions = guildSubscriptions;
if (presence.HasValue)
{
msg.Presence = new StatusUpdateParams
{
Status = presence.Value.Item1,
IsAFK = presence.Value.Item2,
IdleSince = presence.Value.Item3,
Game = presence.Value.Item4,
};
}
await SendGatewayAsync(GatewayOpCode.Identify, msg, options: options).ConfigureAwait(false);
}
public async Task SendResumeAsync(string sessionId, int lastSeq, RequestOptions options = null)
{
options = RequestOptions.CreateOrClone(options);
var msg = new ResumeParams()
{
Token = AuthToken,
SessionId = sessionId,
Sequence = lastSeq
};
await SendGatewayAsync(GatewayOpCode.Resume, msg, options: options).ConfigureAwait(false);
}
public async Task SendHeartbeatAsync(int lastSeq, RequestOptions options = null)
{
options = RequestOptions.CreateOrClone(options);
await SendGatewayAsync(GatewayOpCode.Heartbeat, lastSeq, options: options).ConfigureAwait(false);
}
public async Task SendStatusUpdateAsync(UserStatus status, bool isAFK, long? since, GameModel game, RequestOptions options = null)
{
options = RequestOptions.CreateOrClone(options);
var args = new StatusUpdateParams
{
Status = status,
IdleSince = since,
IsAFK = isAFK,
Game = game
};
options.BucketId = GatewayBucket.Get(GatewayBucketType.PresenceUpdate).Id;
await SendGatewayAsync(GatewayOpCode.StatusUpdate, args, options: options).ConfigureAwait(false);
}
public async Task SendRequestMembersAsync(IEnumerable<ulong> guildIds, RequestOptions options = null)
{
options = RequestOptions.CreateOrClone(options);
await SendGatewayAsync(GatewayOpCode.RequestGuildMembers, new RequestMembersParams { GuildIds = guildIds, Query = "", Limit = 0 }, options: options).ConfigureAwait(false);
}
public async Task SendVoiceStateUpdateAsync(ulong guildId, ulong? channelId, bool selfDeaf, bool selfMute, RequestOptions options = null)
{
options = RequestOptions.CreateOrClone(options);
var payload = new VoiceStateUpdateParams
{
GuildId = guildId,
ChannelId = channelId,
SelfDeaf = selfDeaf,
SelfMute = selfMute
};
await SendGatewayAsync(GatewayOpCode.VoiceStateUpdate, payload, options: options).ConfigureAwait(false);
}
public async Task SendGuildSyncAsync(IEnumerable<ulong> guildIds, RequestOptions options = null)
{
options = RequestOptions.CreateOrClone(options);
await SendGatewayAsync(GatewayOpCode.GuildSync, guildIds, options: options).ConfigureAwait(false);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.ExpressRoute;
using Microsoft.WindowsAzure.Management.ExpressRoute.Models;
namespace Microsoft.WindowsAzure.Management.ExpressRoute
{
internal partial class DedicatedCircuitOperations : IServiceOperations<ExpressRouteManagementClient>, IDedicatedCircuitOperations
{
/// <summary>
/// Initializes a new instance of the DedicatedCircuitOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DedicatedCircuitOperations(ExpressRouteManagementClient client)
{
this._client = client;
}
private ExpressRouteManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.ExpressRouteManagementClient.
/// </summary>
public ExpressRouteManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The New Dedicated Circuit operation creates a new dedicated circuit.
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the New Dedicated Circuit
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<ExpressRouteOperationResponse> BeginNewAsync(DedicatedCircuitNewParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.CircuitName == null)
{
throw new ArgumentNullException("parameters.CircuitName");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
if (parameters.ServiceProviderName == null)
{
throw new ArgumentNullException("parameters.ServiceProviderName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginNewAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement createDedicatedCircuitElement = new XElement(XName.Get("CreateDedicatedCircuit", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(createDedicatedCircuitElement);
XElement bandwidthElement = new XElement(XName.Get("Bandwidth", "http://schemas.microsoft.com/windowsazure"));
bandwidthElement.Value = parameters.Bandwidth.ToString();
createDedicatedCircuitElement.Add(bandwidthElement);
XElement circuitNameElement = new XElement(XName.Get("CircuitName", "http://schemas.microsoft.com/windowsazure"));
circuitNameElement.Value = parameters.CircuitName;
createDedicatedCircuitElement.Add(circuitNameElement);
XElement locationElement = new XElement(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
locationElement.Value = parameters.Location;
createDedicatedCircuitElement.Add(locationElement);
XElement serviceProviderNameElement = new XElement(XName.Get("ServiceProviderName", "http://schemas.microsoft.com/windowsazure"));
serviceProviderNameElement.Value = parameters.ServiceProviderName;
createDedicatedCircuitElement.Add(serviceProviderNameElement);
XElement skuElement = new XElement(XName.Get("Sku", "http://schemas.microsoft.com/windowsazure"));
skuElement.Value = parameters.Sku.ToString();
createDedicatedCircuitElement.Add(skuElement);
XElement billingTypeElement = new XElement(XName.Get("BillingType", "http://schemas.microsoft.com/windowsazure"));
billingTypeElement.Value = parameters.BillingType.ToString();
createDedicatedCircuitElement.Add(billingTypeElement);
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ExpressRouteOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ExpressRouteOperationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationAsyncResponseElement != null)
{
XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Remove Dedicated Circuit operation deletes an existing
/// dedicated circuit.
/// </summary>
/// <param name='serviceKey'>
/// Required. Service key representing the dedicated circuit to be
/// deleted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<ExpressRouteOperationResponse> BeginRemoveAsync(string serviceKey, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
TracingAdapter.Enter(invocationId, this, "BeginRemoveAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
url = url + Uri.EscapeDataString(serviceKey);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ExpressRouteOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ExpressRouteOperationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationAsyncResponseElement != null)
{
XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Update Dedicated Circuit operation updates an existing
/// dedicated circuit.
/// </summary>
/// <param name='serviceKey'>
/// Required. Service Key of the circuit being updated
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Dedicated Circuit
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<ExpressRouteOperationResponse> BeginUpdateAsync(string serviceKey, DedicatedCircuitUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "BeginUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
url = url + Uri.EscapeDataString(serviceKey);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement updateDedicatedCircuitElement = new XElement(XName.Get("UpdateDedicatedCircuit", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(updateDedicatedCircuitElement);
if (parameters.Bandwidth != null)
{
XElement bandwidthElement = new XElement(XName.Get("Bandwidth", "http://schemas.microsoft.com/windowsazure"));
bandwidthElement.Value = parameters.Bandwidth;
updateDedicatedCircuitElement.Add(bandwidthElement);
}
if (parameters.Sku != null)
{
XElement skuElement = new XElement(XName.Get("Sku", "http://schemas.microsoft.com/windowsazure"));
skuElement.Value = parameters.Sku;
updateDedicatedCircuitElement.Add(skuElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ExpressRouteOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ExpressRouteOperationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationAsyncResponseElement != null)
{
XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Dedicated Circuit operation retrieves the specified
/// dedicated circuit.
/// </summary>
/// <param name='serviceKey'>
/// Required. The service key representing the circuit.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Dedicated Circuit operation response.
/// </returns>
public async Task<DedicatedCircuitGetResponse> GetAsync(string serviceKey, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
url = url + Uri.EscapeDataString(serviceKey);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DedicatedCircuitGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DedicatedCircuitGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement dedicatedCircuitElement = responseDoc.Element(XName.Get("DedicatedCircuit", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitElement != null)
{
AzureDedicatedCircuit dedicatedCircuitInstance = new AzureDedicatedCircuit();
result.DedicatedCircuit = dedicatedCircuitInstance;
XElement bandwidthElement = dedicatedCircuitElement.Element(XName.Get("Bandwidth", "http://schemas.microsoft.com/windowsazure"));
if (bandwidthElement != null)
{
uint bandwidthInstance = uint.Parse(bandwidthElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitInstance.Bandwidth = bandwidthInstance;
}
XElement circuitNameElement = dedicatedCircuitElement.Element(XName.Get("CircuitName", "http://schemas.microsoft.com/windowsazure"));
if (circuitNameElement != null)
{
string circuitNameInstance = circuitNameElement.Value;
dedicatedCircuitInstance.CircuitName = circuitNameInstance;
}
XElement locationElement = dedicatedCircuitElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
if (locationElement != null)
{
string locationInstance = locationElement.Value;
dedicatedCircuitInstance.Location = locationInstance;
}
XElement serviceKeyElement = dedicatedCircuitElement.Element(XName.Get("ServiceKey", "http://schemas.microsoft.com/windowsazure"));
if (serviceKeyElement != null)
{
string serviceKeyInstance = serviceKeyElement.Value;
dedicatedCircuitInstance.ServiceKey = serviceKeyInstance;
}
XElement serviceProviderNameElement = dedicatedCircuitElement.Element(XName.Get("ServiceProviderName", "http://schemas.microsoft.com/windowsazure"));
if (serviceProviderNameElement != null)
{
string serviceProviderNameInstance = serviceProviderNameElement.Value;
dedicatedCircuitInstance.ServiceProviderName = serviceProviderNameInstance;
}
XElement serviceProviderProvisioningStateElement = dedicatedCircuitElement.Element(XName.Get("ServiceProviderProvisioningState", "http://schemas.microsoft.com/windowsazure"));
if (serviceProviderProvisioningStateElement != null)
{
ProviderProvisioningState serviceProviderProvisioningStateInstance = ((ProviderProvisioningState)Enum.Parse(typeof(ProviderProvisioningState), serviceProviderProvisioningStateElement.Value, true));
dedicatedCircuitInstance.ServiceProviderProvisioningState = serviceProviderProvisioningStateInstance;
}
XElement skuElement = dedicatedCircuitElement.Element(XName.Get("Sku", "http://schemas.microsoft.com/windowsazure"));
if (skuElement != null)
{
CircuitSku skuInstance = ((CircuitSku)Enum.Parse(typeof(CircuitSku), skuElement.Value, true));
dedicatedCircuitInstance.Sku = skuInstance;
}
XElement statusElement = dedicatedCircuitElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
DedicatedCircuitState statusInstance = ((DedicatedCircuitState)Enum.Parse(typeof(DedicatedCircuitState), statusElement.Value, true));
dedicatedCircuitInstance.Status = statusInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Express Route operation status gets information on the
/// status of Express Route operations in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx
/// for more information)
/// </summary>
/// <param name='operationId'>
/// Required. The id of the operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<ExpressRouteOperationStatusResponse> GetOperationStatusAsync(string operationId, CancellationToken cancellationToken)
{
// Validate
if (operationId == null)
{
throw new ArgumentNullException("operationId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationId", operationId);
TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/operation/";
url = url + Uri.EscapeDataString(operationId);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ExpressRouteOperationStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ExpressRouteOperationStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationElement = responseDoc.Element(XName.Get("GatewayOperation", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationElement != null)
{
XElement idElement = gatewayOperationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.Id = idInstance;
}
XElement statusElement = gatewayOperationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
ExpressRouteOperationStatus statusInstance = ((ExpressRouteOperationStatus)Enum.Parse(typeof(ExpressRouteOperationStatus), statusElement.Value, true));
result.Status = statusInstance;
}
XElement httpStatusCodeElement = gatewayOperationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
if (httpStatusCodeElement != null)
{
HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
result.HttpStatusCode = httpStatusCodeInstance;
}
XElement dataElement = gatewayOperationElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure"));
if (dataElement != null)
{
string dataInstance = dataElement.Value;
result.Data = dataInstance;
}
XElement errorElement = gatewayOperationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
ExpressRouteOperationStatusResponse.ErrorDetails errorInstance = new ExpressRouteOperationStatusResponse.ErrorDetails();
result.Error = errorInstance;
XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
errorInstance.Code = codeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Dedicated Circuit operation retrieves a list of dedicated
/// circuits owned by the customer.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Dedicated Circuit operation response.
/// </returns>
public async Task<DedicatedCircuitListResponse> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DedicatedCircuitListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DedicatedCircuitListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement dedicatedCircuitsSequenceElement = responseDoc.Element(XName.Get("DedicatedCircuits", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitsSequenceElement != null)
{
foreach (XElement dedicatedCircuitsElement in dedicatedCircuitsSequenceElement.Elements(XName.Get("DedicatedCircuit", "http://schemas.microsoft.com/windowsazure")))
{
AzureDedicatedCircuit dedicatedCircuitInstance = new AzureDedicatedCircuit();
result.DedicatedCircuits.Add(dedicatedCircuitInstance);
XElement bandwidthElement = dedicatedCircuitsElement.Element(XName.Get("Bandwidth", "http://schemas.microsoft.com/windowsazure"));
if (bandwidthElement != null)
{
uint bandwidthInstance = uint.Parse(bandwidthElement.Value, CultureInfo.InvariantCulture);
dedicatedCircuitInstance.Bandwidth = bandwidthInstance;
}
XElement circuitNameElement = dedicatedCircuitsElement.Element(XName.Get("CircuitName", "http://schemas.microsoft.com/windowsazure"));
if (circuitNameElement != null)
{
string circuitNameInstance = circuitNameElement.Value;
dedicatedCircuitInstance.CircuitName = circuitNameInstance;
}
XElement locationElement = dedicatedCircuitsElement.Element(XName.Get("Location", "http://schemas.microsoft.com/windowsazure"));
if (locationElement != null)
{
string locationInstance = locationElement.Value;
dedicatedCircuitInstance.Location = locationInstance;
}
XElement serviceKeyElement = dedicatedCircuitsElement.Element(XName.Get("ServiceKey", "http://schemas.microsoft.com/windowsazure"));
if (serviceKeyElement != null)
{
string serviceKeyInstance = serviceKeyElement.Value;
dedicatedCircuitInstance.ServiceKey = serviceKeyInstance;
}
XElement serviceProviderNameElement = dedicatedCircuitsElement.Element(XName.Get("ServiceProviderName", "http://schemas.microsoft.com/windowsazure"));
if (serviceProviderNameElement != null)
{
string serviceProviderNameInstance = serviceProviderNameElement.Value;
dedicatedCircuitInstance.ServiceProviderName = serviceProviderNameInstance;
}
XElement serviceProviderProvisioningStateElement = dedicatedCircuitsElement.Element(XName.Get("ServiceProviderProvisioningState", "http://schemas.microsoft.com/windowsazure"));
if (serviceProviderProvisioningStateElement != null)
{
ProviderProvisioningState serviceProviderProvisioningStateInstance = ((ProviderProvisioningState)Enum.Parse(typeof(ProviderProvisioningState), serviceProviderProvisioningStateElement.Value, true));
dedicatedCircuitInstance.ServiceProviderProvisioningState = serviceProviderProvisioningStateInstance;
}
XElement skuElement = dedicatedCircuitsElement.Element(XName.Get("Sku", "http://schemas.microsoft.com/windowsazure"));
if (skuElement != null)
{
CircuitSku skuInstance = ((CircuitSku)Enum.Parse(typeof(CircuitSku), skuElement.Value, true));
dedicatedCircuitInstance.Sku = skuInstance;
}
XElement statusElement = dedicatedCircuitsElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
DedicatedCircuitState statusInstance = ((DedicatedCircuitState)Enum.Parse(typeof(DedicatedCircuitState), statusElement.Value, true));
dedicatedCircuitInstance.Status = statusInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The New Dedicated Circuit operation creates a new dedicated circuit.
/// </summary>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Virtual Network Gateway
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<ExpressRouteOperationStatusResponse> NewAsync(DedicatedCircuitNewParameters parameters, CancellationToken cancellationToken)
{
ExpressRouteManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "NewAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationResponse response = await client.DedicatedCircuits.BeginNewAsync(parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationStatusResponse result = await client.DedicatedCircuits.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == ExpressRouteOperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.DedicatedCircuits.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != ExpressRouteOperationStatus.Successful)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// The Remove Dedicated Circuit operation deletes an existing
/// dedicated circuit.
/// </summary>
/// <param name='serviceKey'>
/// Required. Service Key associated with the dedicated circuit to be
/// deleted.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<ExpressRouteOperationStatusResponse> RemoveAsync(string serviceKey, CancellationToken cancellationToken)
{
ExpressRouteManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
TracingAdapter.Enter(invocationId, this, "RemoveAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationResponse response = await client.DedicatedCircuits.BeginRemoveAsync(serviceKey, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationStatusResponse result = await client.DedicatedCircuits.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == ExpressRouteOperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.DedicatedCircuits.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != ExpressRouteOperationStatus.Successful)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// The Update Dedicated Circuit operation updates an existing
/// dedicated circuit.
/// </summary>
/// <param name='serviceKey'>
/// Required. Service Key of the circuit being updated
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the update dedicated circuit
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<ExpressRouteOperationStatusResponse> UpdateAsync(string serviceKey, DedicatedCircuitUpdateParameters parameters, CancellationToken cancellationToken)
{
ExpressRouteManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationResponse response = await client.DedicatedCircuits.BeginUpdateAsync(serviceKey, parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationStatusResponse result = await client.DedicatedCircuits.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == ExpressRouteOperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.DedicatedCircuits.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != ExpressRouteOperationStatus.Successful)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
}
}
| |
/*
* Copyright (c) 2006-2014, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org 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.Runtime.InteropServices;
namespace OpenMetaverse
{
/// <summary>
/// An 8-bit color structure including an alpha channel
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Color4 : IComparable<Color4>, IEquatable<Color4>
{
/// <summary>Red</summary>
public float R;
/// <summary>Green</summary>
public float G;
/// <summary>Blue</summary>
public float B;
/// <summary>Alpha</summary>
public float A;
#region Constructors
/// <summary>
///
/// </summary>
/// <param name="r"></param>
/// <param name="g"></param>
/// <param name="b"></param>
/// <param name="a"></param>
public Color4(byte r, byte g, byte b, byte a)
{
const float quanta = 1.0f / 255.0f;
R = (float)r * quanta;
G = (float)g * quanta;
B = (float)b * quanta;
A = (float)a * quanta;
}
public Color4(float r, float g, float b, float a)
{
// Quick check to see if someone is doing something obviously wrong
// like using float values from 0.0 - 255.0
if (r > 1f || g > 1f || b > 1f || a > 1f)
throw new ArgumentException(
String.Format("Attempting to initialize Color4 with out of range values <{0},{1},{2},{3}>",
r, g, b, a));
// Valid range is from 0.0 to 1.0
R = Utils.Clamp(r, 0f, 1f);
G = Utils.Clamp(g, 0f, 1f);
B = Utils.Clamp(b, 0f, 1f);
A = Utils.Clamp(a, 0f, 1f);
}
/// <summary>
/// Builds a color from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing a 16 byte color</param>
/// <param name="pos">Beginning position in the byte array</param>
/// <param name="inverted">True if the byte array stores inverted values,
/// otherwise false. For example the color black (fully opaque) inverted
/// would be 0xFF 0xFF 0xFF 0x00</param>
public Color4(byte[] byteArray, int pos, bool inverted)
{
R = G = B = A = 0f;
FromBytes(byteArray, pos, inverted);
}
/// <summary>
/// Returns the raw bytes for this vector
/// </summary>
/// <param name="byteArray">Byte array containing a 16 byte color</param>
/// <param name="pos">Beginning position in the byte array</param>
/// <param name="inverted">True if the byte array stores inverted values,
/// otherwise false. For example the color black (fully opaque) inverted
/// would be 0xFF 0xFF 0xFF 0x00</param>
/// <param name="alphaInverted">True if the alpha value is inverted in
/// addition to whatever the inverted parameter is. Setting inverted true
/// and alphaInverted true will flip the alpha value back to non-inverted,
/// but keep the other color bytes inverted</param>
/// <returns>A 16 byte array containing R, G, B, and A</returns>
public Color4(byte[] byteArray, int pos, bool inverted, bool alphaInverted)
{
R = G = B = A = 0f;
FromBytes(byteArray, pos, inverted, alphaInverted);
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="color">Color to copy</param>
public Color4(Color4 color)
{
R = color.R;
G = color.G;
B = color.B;
A = color.A;
}
#endregion Constructors
#region Public Methods
/// <summary>
/// IComparable.CompareTo implementation
/// </summary>
/// <remarks>Sorting ends up like this: |--Grayscale--||--Color--|.
/// Alpha is only used when the colors are otherwise equivalent</remarks>
public int CompareTo(Color4 color)
{
float thisHue = GetHue();
float thatHue = color.GetHue();
if (thisHue < 0f && thatHue < 0f)
{
// Both monochromatic
if (R == color.R)
{
// Monochromatic and equal, compare alpha
return A.CompareTo(color.A);
}
else
{
// Compare lightness
return R.CompareTo(R);
}
}
else
{
if (thisHue == thatHue)
{
// RGB is equal, compare alpha
return A.CompareTo(color.A);
}
else
{
// Compare hues
return thisHue.CompareTo(thatHue);
}
}
}
public void FromBytes(byte[] byteArray, int pos, bool inverted)
{
const float quanta = 1.0f / 255.0f;
if (inverted)
{
R = (float)(255 - byteArray[pos]) * quanta;
G = (float)(255 - byteArray[pos + 1]) * quanta;
B = (float)(255 - byteArray[pos + 2]) * quanta;
A = (float)(255 - byteArray[pos + 3]) * quanta;
}
else
{
R = (float)byteArray[pos] * quanta;
G = (float)byteArray[pos + 1] * quanta;
B = (float)byteArray[pos + 2] * quanta;
A = (float)byteArray[pos + 3] * quanta;
}
}
/// <summary>
/// Builds a color from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing a 16 byte color</param>
/// <param name="pos">Beginning position in the byte array</param>
/// <param name="inverted">True if the byte array stores inverted values,
/// otherwise false. For example the color black (fully opaque) inverted
/// would be 0xFF 0xFF 0xFF 0x00</param>
/// <param name="alphaInverted">True if the alpha value is inverted in
/// addition to whatever the inverted parameter is. Setting inverted true
/// and alphaInverted true will flip the alpha value back to non-inverted,
/// but keep the other color bytes inverted</param>
public void FromBytes(byte[] byteArray, int pos, bool inverted, bool alphaInverted)
{
FromBytes(byteArray, pos, inverted);
if (alphaInverted)
A = 1.0f - A;
}
public byte[] GetBytes()
{
return GetBytes(false);
}
public byte[] GetBytes(bool inverted)
{
byte[] byteArray = new byte[4];
ToBytes(byteArray, 0, inverted);
return byteArray;
}
public byte[] GetFloatBytes()
{
byte[] bytes = new byte[16];
ToFloatBytes(bytes, 0);
return bytes;
}
/// <summary>
/// Writes the raw bytes for this color to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 16 bytes before the end of the array</param>
public void ToBytes(byte[] dest, int pos)
{
ToBytes(dest, pos, false);
}
/// <summary>
/// Serializes this color into four bytes in a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 4 bytes before the end of the array</param>
/// <param name="inverted">True to invert the output (1.0 becomes 0
/// instead of 255)</param>
public void ToBytes(byte[] dest, int pos, bool inverted)
{
dest[pos + 0] = Utils.FloatToByte(R, 0f, 1f);
dest[pos + 1] = Utils.FloatToByte(G, 0f, 1f);
dest[pos + 2] = Utils.FloatToByte(B, 0f, 1f);
dest[pos + 3] = Utils.FloatToByte(A, 0f, 1f);
if (inverted)
{
dest[pos + 0] = (byte)(255 - dest[pos + 0]);
dest[pos + 1] = (byte)(255 - dest[pos + 1]);
dest[pos + 2] = (byte)(255 - dest[pos + 2]);
dest[pos + 3] = (byte)(255 - dest[pos + 3]);
}
}
/// <summary>
/// Writes the raw bytes for this color to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 16 bytes before the end of the array</param>
public void ToFloatBytes(byte[] dest, int pos)
{
Buffer.BlockCopy(BitConverter.GetBytes(R), 0, dest, pos + 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(G), 0, dest, pos + 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes(B), 0, dest, pos + 8, 4);
Buffer.BlockCopy(BitConverter.GetBytes(A), 0, dest, pos + 12, 4);
}
public float GetHue()
{
const float HUE_MAX = 360f;
float max = Math.Max(Math.Max(R, G), B);
float min = Math.Min(Math.Min(R, B), B);
if (max == min)
{
// Achromatic, hue is undefined
return -1f;
}
else if (R == max)
{
float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min);
float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min);
return bDelta - gDelta;
}
else if (G == max)
{
float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min);
float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min);
return (HUE_MAX / 3f) + rDelta - bDelta;
}
else // B == max
{
float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min);
float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min);
return ((2f * HUE_MAX) / 3f) + gDelta - rDelta;
}
}
/// <summary>
/// Ensures that values are in range 0-1
/// </summary>
public void ClampValues()
{
if (R < 0f)
R = 0f;
if (G < 0f)
G = 0f;
if (B < 0f)
B = 0f;
if (A < 0f)
A = 0f;
if (R > 1f)
R = 1f;
if (G > 1f)
G = 1f;
if (B > 1f)
B = 1f;
if (A > 1f)
A = 1f;
}
#endregion Public Methods
#region Static Methods
/// <summary>
/// Create an RGB color from a hue, saturation, value combination
/// </summary>
/// <param name="hue">Hue</param>
/// <param name="saturation">Saturation</param>
/// <param name="value">Value</param>
/// <returns>An fully opaque RGB color (alpha is 1.0)</returns>
public static Color4 FromHSV(double hue, double saturation, double value)
{
double r = 0d;
double g = 0d;
double b = 0d;
if (saturation == 0d)
{
// If s is 0, all colors are the same.
// This is some flavor of gray.
r = value;
g = value;
b = value;
}
else
{
double p;
double q;
double t;
double fractionalSector;
int sectorNumber;
double sectorPos;
// The color wheel consists of 6 sectors.
// Figure out which sector you//re in.
sectorPos = hue / 60d;
sectorNumber = (int)(Math.Floor(sectorPos));
// get the fractional part of the sector.
// That is, how many degrees into the sector
// are you?
fractionalSector = sectorPos - sectorNumber;
// Calculate values for the three axes
// of the color.
p = value * (1d - saturation);
q = value * (1d - (saturation * fractionalSector));
t = value * (1d - (saturation * (1d - fractionalSector)));
// Assign the fractional colors to r, g, and b
// based on the sector the angle is in.
switch (sectorNumber)
{
case 0:
r = value;
g = t;
b = p;
break;
case 1:
r = q;
g = value;
b = p;
break;
case 2:
r = p;
g = value;
b = t;
break;
case 3:
r = p;
g = q;
b = value;
break;
case 4:
r = t;
g = p;
b = value;
break;
case 5:
r = value;
g = p;
b = q;
break;
}
}
return new Color4((float)r, (float)g, (float)b, 1f);
}
/// <summary>
/// Performs linear interpolation between two colors
/// </summary>
/// <param name="value1">Color to start at</param>
/// <param name="value2">Color to end at</param>
/// <param name="amount">Amount to interpolate</param>
/// <returns>The interpolated color</returns>
public static Color4 Lerp(Color4 value1, Color4 value2, float amount)
{
return new Color4(
Utils.Lerp(value1.R, value2.R, amount),
Utils.Lerp(value1.G, value2.G, amount),
Utils.Lerp(value1.B, value2.B, amount),
Utils.Lerp(value1.A, value2.A, amount));
}
#endregion Static Methods
#region Overrides
public override string ToString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", R, G, B, A);
}
public string ToRGBString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", R, G, B);
}
public override bool Equals(object obj)
{
return (obj is Color4) ? this == (Color4)obj : false;
}
public bool Equals(Color4 other)
{
return this == other;
}
public override int GetHashCode()
{
return R.GetHashCode() ^ G.GetHashCode() ^ B.GetHashCode() ^ A.GetHashCode();
}
#endregion Overrides
#region Operators
public static bool operator ==(Color4 lhs, Color4 rhs)
{
return (lhs.R == rhs.R) && (lhs.G == rhs.G) && (lhs.B == rhs.B) && (lhs.A == rhs.A);
}
public static bool operator !=(Color4 lhs, Color4 rhs)
{
return !(lhs == rhs);
}
public static Color4 operator +(Color4 lhs, Color4 rhs)
{
lhs.R += rhs.R;
lhs.G += rhs.G;
lhs.B += rhs.B;
lhs.A += rhs.A;
lhs.ClampValues();
return lhs;
}
public static Color4 operator -(Color4 lhs, Color4 rhs)
{
lhs.R -= rhs.R;
lhs.G -= rhs.G;
lhs.B -= rhs.B;
lhs.A -= rhs.A;
lhs.ClampValues();
return lhs;
}
public static Color4 operator *(Color4 lhs, Color4 rhs)
{
lhs.R *= rhs.R;
lhs.G *= rhs.G;
lhs.B *= rhs.B;
lhs.A *= rhs.A;
lhs.ClampValues();
return lhs;
}
#endregion Operators
/// <summary>A Color4 with zero RGB values and fully opaque (alpha 1.0)</summary>
public readonly static Color4 Black = new Color4(0f, 0f, 0f, 1f);
/// <summary>A Color4 with full RGB values (1.0) and fully opaque (alpha 1.0)</summary>
public readonly static Color4 White = new Color4(1f, 1f, 1f, 1f);
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using Consul;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Runtime.Host;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
namespace Orleans.Runtime.Membership
{
/// <summary>
/// A Membership Table implementation using Consul 0.6.0 https://consul.io/
/// </summary>
public class ConsulBasedMembershipTable : IMembershipTable
{
private static readonly TableVersion NotFoundTableVersion = new TableVersion(0, "0");
private ILogger _logger;
private readonly ConsulClient _consulClient;
private readonly ConsulClusteringSiloOptions clusteringSiloTableOptions;
private readonly string clusterId;
private readonly string kvRootFolder;
private readonly string versionKey;
public ConsulBasedMembershipTable(
ILogger<ConsulBasedMembershipTable> logger,
IOptions<ConsulClusteringSiloOptions> membershipTableOptions,
IOptions<ClusterOptions> clusterOptions)
{
this.clusterId = clusterOptions.Value.ClusterId;
this.kvRootFolder = membershipTableOptions.Value.KvRootFolder;
this._logger = logger;
this.clusteringSiloTableOptions = membershipTableOptions.Value;
_consulClient =
new ConsulClient(config =>
{
config.Address = this.clusteringSiloTableOptions.Address;
config.Token = this.clusteringSiloTableOptions.AclClientToken;
});
versionKey = ConsulSiloRegistrationAssembler.FormatVersionKey(clusterId, kvRootFolder);
}
/// <summary>
/// Initializes the Consul based membership table.
/// </summary>
/// <param name="tryInitTableVersion">Will be ignored: Consul does not support the extended Membership Protocol TableVersion</param>
/// <returns></returns>
/// <remarks>
/// Consul Membership Provider does not support the extended Membership Protocol,
/// therefore there is no MembershipTable to Initialize
/// </remarks>
public Task InitializeMembershipTable(bool tryInitTableVersion)
{
return Task.CompletedTask;
}
public async Task<MembershipTableData> ReadRow(SiloAddress siloAddress)
{
var (siloRegistration, tableVersion) = await GetConsulSiloRegistration(siloAddress);
return AssembleMembershipTableData(tableVersion, siloRegistration);
}
public Task<MembershipTableData> ReadAll()
{
return ReadAll(this._consulClient, this.clusterId, this.kvRootFolder, this._logger, this.versionKey);
}
public static async Task<MembershipTableData> ReadAll(ConsulClient consulClient, string clusterId, string kvRootFolder, ILogger logger, string versionKey)
{
var deploymentKVAddresses = await consulClient.KV.List(ConsulSiloRegistrationAssembler.FormatDeploymentKVPrefix(clusterId, kvRootFolder));
if (deploymentKVAddresses.Response == null)
{
logger.Debug("Could not find any silo registrations for deployment {0}.", clusterId);
return new MembershipTableData(NotFoundTableVersion);
}
var allSiloRegistrations =
deploymentKVAddresses.Response
.Where(siloKV => !siloKV.Key.EndsWith(ConsulSiloRegistrationAssembler.SiloIAmAliveSuffix, StringComparison.OrdinalIgnoreCase)
&& !siloKV.Key.EndsWith(ConsulSiloRegistrationAssembler.VersionSuffix, StringComparison.OrdinalIgnoreCase))
.Select(siloKV =>
{
var iAmAliveKV = deploymentKVAddresses.Response.Where(kv => kv.Key.Equals(ConsulSiloRegistrationAssembler.FormatSiloIAmAliveKey(siloKV.Key), StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
return ConsulSiloRegistrationAssembler.FromKVPairs(clusterId, siloKV, iAmAliveKV);
}).ToArray();
var tableVersion = GetTableVersion(versionKey, deploymentKVAddresses);
return AssembleMembershipTableData(tableVersion, allSiloRegistrations);
}
public async Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion)
{
try
{
//Use "0" as the eTag then Consul KV CAS will treat the operation as an insert and return false if the KV already exiats.
var siloRegistration = ConsulSiloRegistrationAssembler.FromMembershipEntry(this.clusterId, entry, "0");
var insertKV = ConsulSiloRegistrationAssembler.ToKVPair(siloRegistration, this.kvRootFolder);
var rowInsert = new KVTxnOp(insertKV.Key, KVTxnVerb.CAS) { Index = siloRegistration.LastIndex, Value = insertKV.Value };
var versionUpdate = this.GetVersionRowUpdate(tableVersion);
var responses = await _consulClient.KV.Txn(new List<KVTxnOp> { rowInsert, versionUpdate });
if (!responses.Response.Success)
{
_logger.Debug("ConsulMembershipProvider failed to insert the row {0}.", entry.SiloAddress);
return false;
}
return true;
}
catch (Exception ex)
{
_logger.Info("ConsulMembershipProvider failed to insert registration for silo {0}; {1}.", entry.SiloAddress, ex);
throw;
}
}
public async Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion)
{
//Update Silo Liveness
try
{
var siloRegistration = ConsulSiloRegistrationAssembler.FromMembershipEntry(this.clusterId, entry, etag);
var updateKV = ConsulSiloRegistrationAssembler.ToKVPair(siloRegistration, this.kvRootFolder);
var rowUpdate = new KVTxnOp(updateKV.Key, KVTxnVerb.CAS) { Index = siloRegistration.LastIndex, Value = updateKV.Value };
var versionUpdate = this.GetVersionRowUpdate(tableVersion);
var responses = await _consulClient.KV.Txn(new List<KVTxnOp> { rowUpdate, versionUpdate });
if (!responses.Response.Success)
{
_logger.Debug("ConsulMembershipProvider failed the CAS check when updating the registration for silo {0}.", entry.SiloAddress);
return false;
}
return true;
}
catch (Exception ex)
{
_logger.Info("ConsulMembershipProvider failed to update the registration for silo {0}: {1}.", entry.SiloAddress, ex);
throw;
}
}
public async Task UpdateIAmAlive(MembershipEntry entry)
{
var iAmAliveKV = ConsulSiloRegistrationAssembler.ToIAmAliveKVPair(this.clusterId, this.kvRootFolder, entry.SiloAddress, entry.IAmAliveTime);
await _consulClient.KV.Put(iAmAliveKV);
}
public async Task DeleteMembershipTableEntries(string clusterId)
{
await _consulClient.KV.DeleteTree(ConsulSiloRegistrationAssembler.FormatDeploymentKVPrefix(this.clusterId, this.kvRootFolder));
}
private static TableVersion GetTableVersion(string versionKey, QueryResult<KVPair[]> entries)
{
TableVersion tableVersion;
var tableVersionEntry = entries?.Response?.FirstOrDefault(kv => kv.Key.Equals(versionKey ?? string.Empty, StringComparison.OrdinalIgnoreCase));
if (tableVersionEntry != null)
{
var versionNumber = 0;
if (tableVersionEntry.Value is byte[] versionData && versionData.Length > 0)
{
int.TryParse(Encoding.UTF8.GetString(tableVersionEntry.Value), out versionNumber);
}
tableVersion = new TableVersion(versionNumber, tableVersionEntry.ModifyIndex.ToString(CultureInfo.InvariantCulture));
}
else
{
tableVersion = NotFoundTableVersion;
}
return tableVersion;
}
private KVTxnOp GetVersionRowUpdate(TableVersion version)
{
ulong.TryParse(version.VersionEtag, out var index);
var versionBytes = Encoding.UTF8.GetBytes(version.Version.ToString(CultureInfo.InvariantCulture));
return new KVTxnOp(this.versionKey, KVTxnVerb.CAS) { Index = index, Value = versionBytes };
}
private async Task<(ConsulSiloRegistration, TableVersion)> GetConsulSiloRegistration(SiloAddress siloAddress)
{
var deploymentKey = ConsulSiloRegistrationAssembler.FormatDeploymentKVPrefix(this.clusterId, this.kvRootFolder);
var siloKey = ConsulSiloRegistrationAssembler.FormatDeploymentSiloKey(this.clusterId, this.kvRootFolder, siloAddress);
var entries = await _consulClient.KV.List(deploymentKey);
if (entries.Response == null) return (null, NotFoundTableVersion);
var siloKV = entries.Response.Single(KV => KV.Key.Equals(siloKey, StringComparison.OrdinalIgnoreCase));
var iAmAliveKV = entries.Response.SingleOrDefault(KV => KV.Key.Equals(ConsulSiloRegistrationAssembler.FormatSiloIAmAliveKey(siloKey), StringComparison.OrdinalIgnoreCase));
var tableVersion = GetTableVersion(versionKey: versionKey, entries: entries);
var siloRegistration = ConsulSiloRegistrationAssembler.FromKVPairs(this.clusterId, siloKV, iAmAliveKV);
return (siloRegistration, tableVersion);
}
private static MembershipTableData AssembleMembershipTableData(TableVersion tableVersion, params ConsulSiloRegistration[] silos)
{
var membershipEntries = silos
.Where(silo => silo != null)
.Select(silo => ConsulSiloRegistrationAssembler.ToMembershipEntry(silo))
.ToList();
return new MembershipTableData(membershipEntries, tableVersion);
}
public async Task CleanupDefunctSiloEntries(DateTimeOffset beforeDate)
{
var allKVs = await _consulClient.KV.List(ConsulSiloRegistrationAssembler.FormatDeploymentKVPrefix(this.clusterId, this.kvRootFolder));
if (allKVs.Response == null)
{
_logger.Debug("Could not find any silo registrations for deployment {0}.", this.clusterId);
return;
}
var allRegistrations =
allKVs.Response
.Where(siloKV => !siloKV.Key.EndsWith(ConsulSiloRegistrationAssembler.SiloIAmAliveSuffix, StringComparison.OrdinalIgnoreCase)
&& !siloKV.Key.EndsWith(ConsulSiloRegistrationAssembler.VersionSuffix, StringComparison.OrdinalIgnoreCase))
.Select(siloKV =>
{
var iAmAliveKV = allKVs.Response.Where(kv => kv.Key.Equals(ConsulSiloRegistrationAssembler.FormatSiloIAmAliveKey(siloKV.Key), StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
return new
{
RegistrationKey = siloKV.Key,
Registration = ConsulSiloRegistrationAssembler.FromKVPairs(clusterId, siloKV, iAmAliveKV)
};
}).ToArray();
foreach (var entry in allRegistrations)
{
if (entry.Registration.IAmAliveTime < beforeDate)
{
await _consulClient.KV.DeleteTree(entry.RegistrationKey);
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
// DEBUG ON
// DEBUG OFF
using System.Reflection;
namespace OpenSim.Services.Connectors.SimianGrid
{
/// <summary>
/// Connects avatar appearance data to the SimianGrid backend
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimianAvatarServiceConnector")]
public class SimianAvatarServiceConnector : IAvatarService, ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
// private static string ZeroID = UUID.Zero.ToString();
private bool m_Enabled = false;
private string m_serverUrl = String.Empty;
#region ISharedRegionModule
public SimianAvatarServiceConnector()
{
}
public string Name { get { return "SimianAvatarServiceConnector"; } }
public Type ReplaceableInterface { get { return null; } }
public void AddRegion(Scene scene)
{
if (m_Enabled) { scene.RegisterModuleInterface<IAvatarService>(this); }
}
public void Close()
{
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (m_Enabled) { scene.UnregisterModuleInterface<IAvatarService>(this); }
}
#endregion ISharedRegionModule
public SimianAvatarServiceConnector(IConfigSource source)
{
CommonInit(source);
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("AvatarServices", "");
if (name == Name)
CommonInit(source);
}
}
private void CommonInit(IConfigSource source)
{
IConfig gridConfig = source.Configs["AvatarService"];
if (gridConfig != null)
{
string serviceUrl = gridConfig.GetString("AvatarServerURI");
if (!String.IsNullOrEmpty(serviceUrl))
{
if (!serviceUrl.EndsWith("/") && !serviceUrl.EndsWith("="))
serviceUrl = serviceUrl + '/';
m_serverUrl = serviceUrl;
m_Enabled = true;
}
}
if (String.IsNullOrEmpty(m_serverUrl))
m_log.Info("[SIMIAN AVATAR CONNECTOR]: No AvatarServerURI specified, disabling connector");
}
#region IAvatarService
// <summary>
// Retrieves the LLPackedAppearance field from user data and unpacks
// it into an AvatarAppearance structure
// </summary>
// <param name="userID"></param>
public AvatarAppearance GetAppearance(UUID userID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "UserID", userID.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
OSDMap map = null;
try { map = OSDParser.DeserializeJson(response["LLPackedAppearance"].AsString()) as OSDMap; }
catch { }
if (map != null)
{
AvatarAppearance appearance = new AvatarAppearance(map);
// DEBUG ON
m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR] retrieved appearance for {0}:\n{1}", userID, appearance.ToString());
// DEBUG OFF
return appearance;
}
m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR]: Failed to decode appearance for {0}", userID);
return null;
}
m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR]: Failed to get appearance for {0}: {1}",
userID, response["Message"].AsString());
return null;
}
// <summary>
// </summary>
// <param name=""></param>
public AvatarData GetAvatar(UUID userID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetUser" },
{ "UserID", userID.ToString() }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
OSDMap map = null;
try { map = OSDParser.DeserializeJson(response["LLAppearance"].AsString()) as OSDMap; }
catch { }
if (map != null)
{
AvatarWearable[] wearables = new AvatarWearable[13];
wearables[0] = new AvatarWearable(map["ShapeItem"].AsUUID(), map["ShapeAsset"].AsUUID());
wearables[1] = new AvatarWearable(map["SkinItem"].AsUUID(), map["SkinAsset"].AsUUID());
wearables[2] = new AvatarWearable(map["HairItem"].AsUUID(), map["HairAsset"].AsUUID());
wearables[3] = new AvatarWearable(map["EyesItem"].AsUUID(), map["EyesAsset"].AsUUID());
wearables[4] = new AvatarWearable(map["ShirtItem"].AsUUID(), map["ShirtAsset"].AsUUID());
wearables[5] = new AvatarWearable(map["PantsItem"].AsUUID(), map["PantsAsset"].AsUUID());
wearables[6] = new AvatarWearable(map["ShoesItem"].AsUUID(), map["ShoesAsset"].AsUUID());
wearables[7] = new AvatarWearable(map["SocksItem"].AsUUID(), map["SocksAsset"].AsUUID());
wearables[8] = new AvatarWearable(map["JacketItem"].AsUUID(), map["JacketAsset"].AsUUID());
wearables[9] = new AvatarWearable(map["GlovesItem"].AsUUID(), map["GlovesAsset"].AsUUID());
wearables[10] = new AvatarWearable(map["UndershirtItem"].AsUUID(), map["UndershirtAsset"].AsUUID());
wearables[11] = new AvatarWearable(map["UnderpantsItem"].AsUUID(), map["UnderpantsAsset"].AsUUID());
wearables[12] = new AvatarWearable(map["SkirtItem"].AsUUID(), map["SkirtAsset"].AsUUID());
AvatarAppearance appearance = new AvatarAppearance();
appearance.Wearables = wearables;
appearance.AvatarHeight = (float)map["Height"].AsReal();
AvatarData avatar = new AvatarData(appearance);
// Get attachments
map = null;
try { map = OSDParser.DeserializeJson(response["LLAttachments"].AsString()) as OSDMap; }
catch { }
if (map != null)
{
foreach (KeyValuePair<string, OSD> kvp in map)
avatar.Data[kvp.Key] = kvp.Value.AsString();
}
return avatar;
}
else
{
m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed to get user appearance for " + userID +
", LLAppearance is missing or invalid");
return null;
}
}
else
{
m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed to get user appearance for " + userID + ": " +
response["Message"].AsString());
}
return null;
}
public bool RemoveItems(UUID userID, string[] names)
{
m_log.Error("[SIMIAN AVATAR CONNECTOR]: RemoveItems called for " + userID + " with " + names.Length + " names, implement this");
return false;
}
public bool ResetAvatar(UUID userID)
{
m_log.Error("[SIMIAN AVATAR CONNECTOR]: ResetAvatar called for " + userID + ", implement this");
return false;
}
// <summary>
// </summary>
// <param name=""></param>
public bool SetAppearance(UUID userID, AvatarAppearance appearance)
{
OSDMap map = appearance.Pack();
if (map == null)
{
m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR]: Failed to encode appearance for {0}", userID);
return false;
}
// m_log.DebugFormat("[SIMIAN AVATAR CONNECTOR] save appearance for {0}",userID);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddUserData" },
{ "UserID", userID.ToString() },
{ "LLPackedAppearance", OSDParser.SerializeJsonString(map) }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.WarnFormat("[SIMIAN AVATAR CONNECTOR]: Failed to save appearance for {0}: {1}",
userID, response["Message"].AsString());
return success;
}
// <summary>
// </summary>
// <param name=""></param>
public bool SetAvatar(UUID userID, AvatarData avatar)
{
m_log.Debug("[SIMIAN AVATAR CONNECTOR]: SetAvatar called for " + userID);
if (avatar.AvatarType == 1) // LLAvatar
{
AvatarAppearance appearance = avatar.ToAvatarAppearance();
OSDMap map = new OSDMap();
map["Height"] = OSD.FromReal(appearance.AvatarHeight);
map["BodyItem"] = appearance.Wearables[AvatarWearable.BODY][0].ItemID.ToString();
map["EyesItem"] = appearance.Wearables[AvatarWearable.EYES][0].ItemID.ToString();
map["GlovesItem"] = appearance.Wearables[AvatarWearable.GLOVES][0].ItemID.ToString();
map["HairItem"] = appearance.Wearables[AvatarWearable.HAIR][0].ItemID.ToString();
map["JacketItem"] = appearance.Wearables[AvatarWearable.JACKET][0].ItemID.ToString();
map["PantsItem"] = appearance.Wearables[AvatarWearable.PANTS][0].ItemID.ToString();
map["ShirtItem"] = appearance.Wearables[AvatarWearable.SHIRT][0].ItemID.ToString();
map["ShoesItem"] = appearance.Wearables[AvatarWearable.SHOES][0].ItemID.ToString();
map["SkinItem"] = appearance.Wearables[AvatarWearable.SKIN][0].ItemID.ToString();
map["SkirtItem"] = appearance.Wearables[AvatarWearable.SKIRT][0].ItemID.ToString();
map["SocksItem"] = appearance.Wearables[AvatarWearable.SOCKS][0].ItemID.ToString();
map["UnderPantsItem"] = appearance.Wearables[AvatarWearable.UNDERPANTS][0].ItemID.ToString();
map["UnderShirtItem"] = appearance.Wearables[AvatarWearable.UNDERSHIRT][0].ItemID.ToString();
map["BodyAsset"] = appearance.Wearables[AvatarWearable.BODY][0].AssetID.ToString();
map["EyesAsset"] = appearance.Wearables[AvatarWearable.EYES][0].AssetID.ToString();
map["GlovesAsset"] = appearance.Wearables[AvatarWearable.GLOVES][0].AssetID.ToString();
map["HairAsset"] = appearance.Wearables[AvatarWearable.HAIR][0].AssetID.ToString();
map["JacketAsset"] = appearance.Wearables[AvatarWearable.JACKET][0].AssetID.ToString();
map["PantsAsset"] = appearance.Wearables[AvatarWearable.PANTS][0].AssetID.ToString();
map["ShirtAsset"] = appearance.Wearables[AvatarWearable.SHIRT][0].AssetID.ToString();
map["ShoesAsset"] = appearance.Wearables[AvatarWearable.SHOES][0].AssetID.ToString();
map["SkinAsset"] = appearance.Wearables[AvatarWearable.SKIN][0].AssetID.ToString();
map["SkirtAsset"] = appearance.Wearables[AvatarWearable.SKIRT][0].AssetID.ToString();
map["SocksAsset"] = appearance.Wearables[AvatarWearable.SOCKS][0].AssetID.ToString();
map["UnderPantsAsset"] = appearance.Wearables[AvatarWearable.UNDERPANTS][0].AssetID.ToString();
map["UnderShirtAsset"] = appearance.Wearables[AvatarWearable.UNDERSHIRT][0].AssetID.ToString();
OSDMap items = new OSDMap();
foreach (KeyValuePair<string, string> kvp in avatar.Data)
{
if (kvp.Key.StartsWith("_ap_"))
items.Add(kvp.Key, OSD.FromString(kvp.Value));
}
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddUserData" },
{ "UserID", userID.ToString() },
{ "LLAppearance", OSDParser.SerializeJsonString(map) },
{ "LLAttachments", OSDParser.SerializeJsonString(items) }
};
OSDMap response = SimianGrid.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN AVATAR CONNECTOR]: Failed saving appearance for " + userID + ": " + response["Message"].AsString());
return success;
}
else
{
m_log.Error("[SIMIAN AVATAR CONNECTOR]: Can't save appearance for " + userID + ". Unhandled avatar type " + avatar.AvatarType);
return false;
}
}
public bool SetItems(UUID userID, string[] names, string[] values)
{
m_log.Error("[SIMIAN AVATAR CONNECTOR]: SetItems called for " + userID + " with " + names.Length + " names and " + values.Length + " values, implement this");
return false;
}
#endregion IAvatarService
}
}
| |
using System;
using Newtonsoft.Json.Linq;
namespace XBMCRPC.Methods
{
public partial class Addons
{
private readonly Client _client;
public Addons(Client client)
{
_client = client;
}
/// <summary>
/// Executes the given addon with the given parameters (if possible)
/// </summary>
public string ExecuteAddon(XBMCRPC.Addons.ExecuteAddon_params1 params_arg, string addonid=null, bool wait=false)
{
var jArgs = new JObject();
if (addonid != null)
{
var jpropaddonid = JToken.FromObject(addonid, _client.Serializer);
jArgs.Add(new JProperty("addonid", jpropaddonid));
}
if (params_arg != null)
{
var jpropparams_arg = JToken.FromObject(params_arg, _client.Serializer);
jArgs.Add(new JProperty("params_arg", jpropparams_arg));
}
if (wait != null)
{
var jpropwait = JToken.FromObject(wait, _client.Serializer);
jArgs.Add(new JProperty("wait", jpropwait));
}
return _client.GetData<string>("Addons.ExecuteAddon", jArgs);
}
/// <summary>
/// Executes the given addon with the given parameters (if possible)
/// </summary>
public string ExecuteAddon(global::System.Collections.Generic.List<string> params_arg, string addonid=null, bool wait=false)
{
var jArgs = new JObject();
if (addonid != null)
{
var jpropaddonid = JToken.FromObject(addonid, _client.Serializer);
jArgs.Add(new JProperty("addonid", jpropaddonid));
}
if (params_arg != null)
{
var jpropparams_arg = JToken.FromObject(params_arg, _client.Serializer);
jArgs.Add(new JProperty("params_arg", jpropparams_arg));
}
if (wait != null)
{
var jpropwait = JToken.FromObject(wait, _client.Serializer);
jArgs.Add(new JProperty("wait", jpropwait));
}
return _client.GetData<string>("Addons.ExecuteAddon", jArgs);
}
/// <summary>
/// Executes the given addon with the given parameters (if possible)
/// </summary>
public string ExecuteAddon(string params_arg, string addonid=null, bool wait=false)
{
var jArgs = new JObject();
if (addonid != null)
{
var jpropaddonid = JToken.FromObject(addonid, _client.Serializer);
jArgs.Add(new JProperty("addonid", jpropaddonid));
}
if (params_arg != null)
{
var jpropparams_arg = JToken.FromObject(params_arg, _client.Serializer);
jArgs.Add(new JProperty("params_arg", jpropparams_arg));
}
if (wait != null)
{
var jpropwait = JToken.FromObject(wait, _client.Serializer);
jArgs.Add(new JProperty("wait", jpropwait));
}
return _client.GetData<string>("Addons.ExecuteAddon", jArgs);
}
/// <summary>
/// Executes the given addon with the given parameters (if possible)
/// </summary>
public string ExecuteAddon(string addonid=null, bool wait=false)
{
var jArgs = new JObject();
if (addonid != null)
{
var jpropaddonid = JToken.FromObject(addonid, _client.Serializer);
jArgs.Add(new JProperty("addonid", jpropaddonid));
}
if (wait != null)
{
var jpropwait = JToken.FromObject(wait, _client.Serializer);
jArgs.Add(new JProperty("wait", jpropwait));
}
return _client.GetData<string>("Addons.ExecuteAddon", jArgs);
}
/// <summary>
/// Gets the details of a specific addon
/// </summary>
public XBMCRPC.Addons.GetAddonDetailsResponse GetAddonDetails(string addonid=null, XBMCRPC.Addon.Fields properties=null)
{
var jArgs = new JObject();
if (addonid != null)
{
var jpropaddonid = JToken.FromObject(addonid, _client.Serializer);
jArgs.Add(new JProperty("addonid", jpropaddonid));
}
if (properties != null)
{
var jpropproperties = JToken.FromObject(properties, _client.Serializer);
jArgs.Add(new JProperty("properties", jpropproperties));
}
return _client.GetData<XBMCRPC.Addons.GetAddonDetailsResponse>("Addons.GetAddonDetails", jArgs);
}
/// <summary>
/// Gets all available addons
/// </summary>
public XBMCRPC.Addons.GetAddonsResponse GetAddons(bool enabled, XBMCRPC.Addon.Types type=0, XBMCRPC.Addon.Content content=0, XBMCRPC.Addon.Fields properties=null, XBMCRPC.List.Limits limits=null)
{
var jArgs = new JObject();
if (type != null)
{
var jproptype = JToken.FromObject(type, _client.Serializer);
jArgs.Add(new JProperty("type", jproptype));
}
if (content != null)
{
var jpropcontent = JToken.FromObject(content, _client.Serializer);
jArgs.Add(new JProperty("content", jpropcontent));
}
if (enabled != null)
{
var jpropenabled = JToken.FromObject(enabled, _client.Serializer);
jArgs.Add(new JProperty("enabled", jpropenabled));
}
if (properties != null)
{
var jpropproperties = JToken.FromObject(properties, _client.Serializer);
jArgs.Add(new JProperty("properties", jpropproperties));
}
if (limits != null)
{
var jproplimits = JToken.FromObject(limits, _client.Serializer);
jArgs.Add(new JProperty("limits", jproplimits));
}
return _client.GetData<XBMCRPC.Addons.GetAddonsResponse>("Addons.GetAddons", jArgs);
}
/// <summary>
/// Gets all available addons
/// </summary>
public XBMCRPC.Addons.GetAddonsResponse GetAddons(XBMCRPC.Addons.GetAddons_enabled2 enabled, XBMCRPC.Addon.Types type=0, XBMCRPC.Addon.Content content=0, XBMCRPC.Addon.Fields properties=null, XBMCRPC.List.Limits limits=null)
{
var jArgs = new JObject();
if (type != null)
{
var jproptype = JToken.FromObject(type, _client.Serializer);
jArgs.Add(new JProperty("type", jproptype));
}
if (content != null)
{
var jpropcontent = JToken.FromObject(content, _client.Serializer);
jArgs.Add(new JProperty("content", jpropcontent));
}
if (enabled != null)
{
var jpropenabled = JToken.FromObject(enabled, _client.Serializer);
jArgs.Add(new JProperty("enabled", jpropenabled));
}
if (properties != null)
{
var jpropproperties = JToken.FromObject(properties, _client.Serializer);
jArgs.Add(new JProperty("properties", jpropproperties));
}
if (limits != null)
{
var jproplimits = JToken.FromObject(limits, _client.Serializer);
jArgs.Add(new JProperty("limits", jproplimits));
}
return _client.GetData<XBMCRPC.Addons.GetAddonsResponse>("Addons.GetAddons", jArgs);
}
/// <summary>
/// Gets all available addons
/// </summary>
public XBMCRPC.Addons.GetAddonsResponse GetAddons(XBMCRPC.Addon.Types type=0, XBMCRPC.Addon.Content content=0, XBMCRPC.Addon.Fields properties=null, XBMCRPC.List.Limits limits=null)
{
var jArgs = new JObject();
if (type != null)
{
var jproptype = JToken.FromObject(type, _client.Serializer);
jArgs.Add(new JProperty("type", jproptype));
}
if (content != null)
{
var jpropcontent = JToken.FromObject(content, _client.Serializer);
jArgs.Add(new JProperty("content", jpropcontent));
}
if (properties != null)
{
var jpropproperties = JToken.FromObject(properties, _client.Serializer);
jArgs.Add(new JProperty("properties", jpropproperties));
}
if (limits != null)
{
var jproplimits = JToken.FromObject(limits, _client.Serializer);
jArgs.Add(new JProperty("limits", jproplimits));
}
return _client.GetData<XBMCRPC.Addons.GetAddonsResponse>("Addons.GetAddons", jArgs);
}
/// <summary>
/// Enables/Disables a specific addon
/// </summary>
public string SetAddonEnabled(bool enabled, string addonid=null)
{
var jArgs = new JObject();
if (addonid != null)
{
var jpropaddonid = JToken.FromObject(addonid, _client.Serializer);
jArgs.Add(new JProperty("addonid", jpropaddonid));
}
if (enabled != null)
{
var jpropenabled = JToken.FromObject(enabled, _client.Serializer);
jArgs.Add(new JProperty("enabled", jpropenabled));
}
return _client.GetData<string>("Addons.SetAddonEnabled", jArgs);
}
/// <summary>
/// Enables/Disables a specific addon
/// </summary>
public string SetAddonEnabled(XBMCRPC.Global.Toggle2 enabled, string addonid=null)
{
var jArgs = new JObject();
if (addonid != null)
{
var jpropaddonid = JToken.FromObject(addonid, _client.Serializer);
jArgs.Add(new JProperty("addonid", jpropaddonid));
}
if (enabled != null)
{
var jpropenabled = JToken.FromObject(enabled, _client.Serializer);
jArgs.Add(new JProperty("enabled", jpropenabled));
}
return _client.GetData<string>("Addons.SetAddonEnabled", jArgs);
}
/// <summary>
/// Enables/Disables a specific addon
/// </summary>
public string SetAddonEnabled(string addonid=null)
{
var jArgs = new JObject();
if (addonid != null)
{
var jpropaddonid = JToken.FromObject(addonid, _client.Serializer);
jArgs.Add(new JProperty("addonid", jpropaddonid));
}
return _client.GetData<string>("Addons.SetAddonEnabled", jArgs);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Versioning;
using Moq;
using NuGet.Test.Mocks;
using Xunit;
namespace NuGet.Test
{
public class PackageRepositoryTest
{
[Fact]
public void FindByIdReturnsPackage()
{
// Arrange
var repo = GetLocalRepository();
// Act
var package = repo.FindPackage(packageId: "A");
// Assert
Assert.NotNull(package);
Assert.Equal("A", package.Id);
}
[Fact]
public void FindByIdReturnsNullWhenPackageNotFound()
{
// Arrange
var repo = GetLocalRepository();
// Act
var package = repo.FindPackage(packageId: "X");
// Assert
Assert.Null(package);
}
[Fact]
public void FindByIdAndVersionReturnsPackage()
{
// Arrange
var repo = GetRemoteRepository();
// Act
var package = repo.FindPackage(packageId: "A", version: SemanticVersion.Parse("1.0"));
// Assert
Assert.NotNull(package);
Assert.Equal("A", package.Id);
Assert.Equal(SemanticVersion.Parse("1.0"), package.Version);
}
[Fact]
public void FindByIdAndVersionReturnsNullWhenPackageNotFound()
{
// Arrange
var repo = GetLocalRepository();
// Act
var package1 = repo.FindPackage(packageId: "X", version: SemanticVersion.Parse("1.0"));
var package2 = repo.FindPackage(packageId: "A", version: SemanticVersion.Parse("1.1"));
// Assert
Assert.Null(package1 ?? package2);
}
[Fact]
public void FindByIdAndVersionRangeReturnsPackage()
{
// Arrange
var repo = GetRemoteRepository();
var versionSpec = VersionUtility.ParseVersionSpec("[0.9, 1.1]");
// Act
var package = repo.FindPackage("A", versionSpec, allowPrereleaseVersions: false, allowUnlisted: true);
// Assert
Assert.NotNull(package);
Assert.Equal("A", package.Id);
Assert.Equal(SemanticVersion.Parse("1.0"), package.Version);
}
[Fact]
public void FindByIdAndVersionRangeReturnsNullWhenPackageNotFound()
{
// Arrange
var repo = GetLocalRepository();
// Act
var package1 = repo.FindPackage("X", VersionUtility.ParseVersionSpec("[0.9, 1.1]"), allowPrereleaseVersions: false, allowUnlisted: true);
var package2 = repo.FindPackage("A", VersionUtility.ParseVersionSpec("[1.4, 1.5]"), allowPrereleaseVersions: false, allowUnlisted: true);
// Assert
Assert.Null(package1 ?? package2);
}
[Fact]
public void FindPackageByIdVersionAndVersionRangesUsesRangeIfExactVersionIsNull()
{
// Arrange
var repo = GetRemoteRepository();
// Act
var package = repo.FindPackage("A", VersionUtility.ParseVersionSpec("[0.6, 1.1.5]"), allowPrereleaseVersions: false, allowUnlisted: true);
// Assert
Assert.NotNull(package);
Assert.Equal("A", package.Id);
Assert.Equal(SemanticVersion.Parse("1.0"), package.Version);
}
[Fact]
public void FindPackagesReturnsPackagesWithTermInPackageTagOrDescriptionOrId()
{
// Arrange
var term = "TAG";
var repo = new MockPackageRepository();
repo.Add(CreateMockPackage("A", "1.0", "Description", " TAG "));
repo.Add(CreateMockPackage("B", "2.0", "Description", "Tags"));
repo.Add(CreateMockPackage("C", "1.0", "This description has tags in it"));
repo.Add(CreateMockPackage("D", "1.0", "Description"));
repo.Add(CreateMockPackage("TagCloud", "1.0", "Description"));
// Act
var packages = repo.GetPackages().Find(term).ToList();
// Assert
Assert.Equal(3, packages.Count);
Assert.Equal("A", packages[0].Id);
Assert.Equal("C", packages[1].Id);
Assert.Equal("TagCloud", packages[2].Id);
}
[Fact]
public void FindPackagesReturnsPrereleasePackagesIfTheFlagIsSetToTrue()
{
// Arrange
var term = "B";
var repo = GetRemoteRepository(includePrerelease: true);
// Act
var packages = repo.GetPackages().Find(term);
// Assert
Assert.Equal(packages.Count(), 2);
packages = packages.OrderBy(p => p.Id);
Assert.Equal(packages.ElementAt(0).Id, "B");
Assert.Equal(packages.ElementAt(0).Version, new SemanticVersion("1.0"));
Assert.Equal(packages.ElementAt(1).Id, "B");
Assert.Equal(packages.ElementAt(1).Version, new SemanticVersion("1.0-beta"));
}
[Fact]
public void FindPackagesReturnsPackagesWithTerm()
{
// Arrange
var term = "B xaml";
var repo = GetRemoteRepository();
// Act
var packages = repo.GetPackages().Find(term);
// Assert
Assert.Equal(packages.Count(), 2);
packages = packages.OrderBy(p => p.Id);
Assert.Equal(packages.ElementAt(0).Id, "B");
Assert.Equal(packages.ElementAt(1).Id, "C");
}
[Fact]
public void FindPackagesReturnsEmptyCollectionWhenNoPackageContainsTerm()
{
// Arrange
var term = "does-not-exist";
var repo = GetRemoteRepository();
// Act
var packages = repo.GetPackages().Find(term);
// Assert
Assert.False(packages.Any());
}
[Fact]
public void FindPackagesReturnsAllPackagesWhenSearchTermIsNullOrEmpty()
{
// Arrange
var repo = GetLocalRepository();
// Act
var packages1 = repo.GetPackages().Find(String.Empty);
var packages2 = repo.GetPackages().Find(null);
var packages3 = repo.GetPackages();
// Assert
Assert.Equal(packages1.ToList(), packages2.ToList());
Assert.Equal(packages2.ToList(), packages3.ToList());
}
[Fact]
public void SearchUsesInterfaceIfImplementedByRepository()
{
// Arrange
var repo = new Mock<MockPackageRepository>(MockBehavior.Strict);
repo.Setup(m => m.GetPackages()).Returns(Enumerable.Empty<IPackage>().AsQueryable());
repo.As<IServiceBasedRepository>().Setup(m => m.Search(It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), false))
.Returns(new[] { PackageUtility.CreatePackage("A") }.AsQueryable());
// Act
var packages = repo.Object.Search("Hello", new[] { ".NETFramework" }, allowPrereleaseVersions: false).ToList();
// Assert
Assert.Equal(1, packages.Count);
Assert.Equal("A", packages[0].Id);
}
[Fact]
public void GetUpdatesReturnsPackagesWithUpdates()
{
// Arrange
var localRepo = GetLocalRepository();
var remoteRepo = GetRemoteRepository();
// Act
var packages = remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false);
// Assert
Assert.True(packages.Any());
Assert.Equal(packages.First().Id, "A");
Assert.Equal(packages.First().Version, SemanticVersion.Parse("1.2"));
}
[Fact]
public void GetUpdatesDoesNotInvokeServiceMethodIfLocalRepositoryDoesNotHaveAnyPackages()
{
// Arrange
var localRepo = new MockPackageRepository();
var serviceRepository = new Mock<IServiceBasedRepository>(MockBehavior.Strict);
var remoteRepo = serviceRepository.As<IPackageRepository>().Object;
// Act
remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false);
// Assert
serviceRepository.Verify(s => s.GetUpdates(It.IsAny<IEnumerable<IPackage>>(), false, false, It.IsAny<IEnumerable<FrameworkName>>(), It.IsAny<IEnumerable<IVersionSpec>>()), Times.Never());
}
[Fact]
public void GetUpdatesReturnsEmptyCollectionWhenSourceRepositoryIsEmpty()
{
// Arrange
var localRepo = GetLocalRepository();
var remoteRepo = GetEmptyRepository();
// Act
var packages = remoteRepo.GetUpdates(localRepo.GetPackages(), includePrerelease: false, includeAllVersions: false);
// Assert
Assert.False(packages.Any());
}
[Fact]
public void FindDependencyPicksHighestVersionIfNotSpecified()
{
// Arrange
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "2.0"),
PackageUtility.CreatePackage("B", "1.0"),
PackageUtility.CreatePackage("B", "1.0.1"),
PackageUtility.CreatePackage("B", "1.0.9"),
PackageUtility.CreatePackage("B", "1.1")
};
var dependency = new PackageDependency("B");
// Act
IPackage package = repository.ResolveDependency(dependency, allowPrereleaseVersions: false, preferListedPackages: false);
// Assert
Assert.Equal("B", package.Id);
Assert.Equal(new SemanticVersion("2.0"), package.Version);
}
[Fact]
public void FindPackageNormalizesVersionBeforeComparing()
{
// Arrange
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "1.0.0"),
PackageUtility.CreatePackage("B", "1.0.0.1")
};
// Act
IPackage package = repository.FindPackage("B", new SemanticVersion("1.0"));
// Assert
Assert.Equal("B", package.Id);
Assert.Equal(new SemanticVersion("1.0.0"), package.Version);
}
[Fact]
public void FindDependencyPicksLowestMajorAndMinorVersionButHighestBuildAndRevision()
{
// Arrange
var repository = new MockPackageRepository() {
PackageUtility.CreatePackage("B", "2.0"),
PackageUtility.CreatePackage("B", "1.0"),
PackageUtility.CreatePackage("B", "1.0.1"),
PackageUtility.CreatePackage("B", "1.0.9"),
PackageUtility.CreatePackage("B", "1.1")
};
// B >= 1.0
PackageDependency dependency1 = PackageDependency.CreateDependency("B", "1.0");
// B >= 1.0.0
PackageDependency dependency2 = PackageDependency.CreateDependency("B", "1.0.0");
// B >= 1.0.0.0
PackageDependency dependency3 = PackageDependency.CreateDependency("B", "1.0.0.0");
// B = 1.0
PackageDependency dependency4 = PackageDependency.CreateDependency("B", "[1.0]");
// B >= 1.0.0 && <= 1.0.8
PackageDependency dependency5 = PackageDependency.CreateDependency("B", "[1.0.0, 1.0.8]");
// Act
IPackage package1 = repository.ResolveDependency(dependency1, allowPrereleaseVersions: false, preferListedPackages: false);
IPackage package2 = repository.ResolveDependency(dependency2, allowPrereleaseVersions: false, preferListedPackages: false);
IPackage package3 = repository.ResolveDependency(dependency3, allowPrereleaseVersions: false, preferListedPackages: false);
IPackage package4 = repository.ResolveDependency(dependency4, allowPrereleaseVersions: false, preferListedPackages: false);
IPackage package5 = repository.ResolveDependency(dependency5, allowPrereleaseVersions: false, preferListedPackages: false);
// Assert
Assert.Equal("B", package1.Id);
Assert.Equal(new SemanticVersion("1.0.9"), package1.Version);
Assert.Equal("B", package2.Id);
Assert.Equal(new SemanticVersion("1.0.9"), package2.Version);
Assert.Equal("B", package3.Id);
Assert.Equal(new SemanticVersion("1.0.9"), package3.Version);
Assert.Equal("B", package4.Id);
Assert.Equal(new SemanticVersion("1.0"), package4.Version);
Assert.Equal("B", package5.Id);
Assert.Equal(new SemanticVersion("1.0.1"), package5.Version);
}
[Fact]
public void ResolveSafeVersionReturnsNullIfPackagesNull()
{
// Act
var package = PackageRepositoryExtensions.ResolveSafeVersion(null);
// Assert
Assert.Null(package);
}
[Fact]
public void ResolveSafeVersionReturnsNullIfEmptyPackages()
{
// Act
var package = PackageRepositoryExtensions.ResolveSafeVersion(Enumerable.Empty<IPackage>());
// Assert
Assert.Null(package);
}
[Fact]
public void ResolveSafeVersionReturnsHighestBuildAndRevisionWithLowestMajorAndMinor()
{
var packages = new[] {
PackageUtility.CreatePackage("A", "0.9"),
PackageUtility.CreatePackage("A", "0.9.3"),
PackageUtility.CreatePackage("A", "1.0"),
PackageUtility.CreatePackage("A", "1.0.2"),
PackageUtility.CreatePackage("A", "1.0.12"),
PackageUtility.CreatePackage("A", "1.0.13"),
};
// Act
var package = PackageRepositoryExtensions.ResolveSafeVersion(packages);
// Assert
Assert.NotNull(package);
Assert.Equal("A", package.Id);
Assert.Equal(new SemanticVersion("0.9.3"), package.Version);
}
private static IPackageRepository GetEmptyRepository()
{
Mock<IPackageRepository> repository = new Mock<IPackageRepository>();
repository.Setup(c => c.GetPackages()).Returns(() => Enumerable.Empty<IPackage>().AsQueryable());
return repository.Object;
}
private static IPackageRepository GetRemoteRepository(bool includePrerelease = false)
{
Mock<IPackageRepository> repository = new Mock<IPackageRepository>();
var packages = new List<IPackage> {
CreateMockPackage("A", "1.0", "scripts style"),
CreateMockPackage("B", "1.0", "testing"),
CreateMockPackage("C", "2.0", "xaml"),
CreateMockPackage("A", "1.2", "a updated desc") };
if (includePrerelease)
{
packages.Add(CreateMockPackage("A", "2.0-alpha", "a prerelease package"));
packages.Add(CreateMockPackage("B", "1.0-beta", "another prerelease package"));
}
repository.Setup(c => c.GetPackages()).Returns(() => packages.AsQueryable());
return repository.Object;
}
private static IPackageRepository GetLocalRepository()
{
Mock<IPackageRepository> repository = new Mock<IPackageRepository>();
var packages = new[] { CreateMockPackage("A", "1.0"), CreateMockPackage("B", "1.0") };
repository.Setup(c => c.GetPackages()).Returns(() => packages.AsQueryable());
return repository.Object;
}
private static IPackage CreateMockPackage(string name, string version, string desc = null, string tags = null)
{
Mock<IPackage> package = new Mock<IPackage>();
package.SetupGet(p => p.Id).Returns(name);
package.SetupGet(p => p.Version).Returns(SemanticVersion.Parse(version));
package.SetupGet(p => p.Description).Returns(desc);
package.SetupGet(p => p.Tags).Returns(tags);
package.SetupGet(p => p.Listed).Returns(true);
return package.Object;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Web.Routing;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Plugins;
using Nop.Plugin.Payments.PurchaseOrder.Controllers;
using Nop.Services.Configuration;
using Nop.Services.Localization;
using Nop.Services.Orders;
using Nop.Services.Payments;
namespace Nop.Plugin.Payments.PurchaseOrder
{
/// <summary>
/// PurchaseOrder payment processor
/// </summary>
public class PurchaseOrderPaymentProcessor : BasePlugin, IPaymentMethod
{
#region Fields
private readonly PurchaseOrderPaymentSettings _purchaseOrderPaymentSettings;
private readonly ISettingService _settingService;
private readonly IOrderTotalCalculationService _orderTotalCalculationService;
#endregion
#region Ctor
public PurchaseOrderPaymentProcessor(PurchaseOrderPaymentSettings purchaseOrderPaymentSettings,
ISettingService settingService, IOrderTotalCalculationService orderTotalCalculationService)
{
this._purchaseOrderPaymentSettings = purchaseOrderPaymentSettings;
this._settingService = settingService;
this._orderTotalCalculationService = orderTotalCalculationService;
}
#endregion
#region Methods
/// <summary>
/// Process a payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
result.NewPaymentStatus = PaymentStatus.Pending;
return result;
}
/// <summary>
/// Post process payment (used by payment gateways that require redirecting to a third-party URL)
/// </summary>
/// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
//nothing
}
/// <summary>
/// Returns a value indicating whether payment method should be hidden during checkout
/// </summary>
/// <param name="cart">Shoping cart</param>
/// <returns>true - hide; false - display.</returns>
public bool HidePaymentMethod(IList<ShoppingCartItem> cart)
{
//you can put any logic here
//for example, hide this payment method if all products in the cart are downloadable
//or hide this payment method if current customer is from certain country
if (_purchaseOrderPaymentSettings.ShippableProductRequired && !cart.RequiresShipping())
return true;
return false;
}
/// <summary>
/// Gets additional handling fee
/// </summary>
/// <param name="cart">Shoping cart</param>
/// <returns>Additional handling fee</returns>
public decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart)
{
var result = this.CalculateAdditionalFee(_orderTotalCalculationService, cart,
_purchaseOrderPaymentSettings.AdditionalFee, _purchaseOrderPaymentSettings.AdditionalFeePercentage);
return result;
}
/// <summary>
/// Captures payment
/// </summary>
/// <param name="capturePaymentRequest">Capture payment request</param>
/// <returns>Capture payment result</returns>
public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
{
var result = new CapturePaymentResult();
result.AddError("Capture method not supported");
return result;
}
/// <summary>
/// Refunds a payment
/// </summary>
/// <param name="refundPaymentRequest">Request</param>
/// <returns>Result</returns>
public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest)
{
var result = new RefundPaymentResult();
result.AddError("Refund method not supported");
return result;
}
/// <summary>
/// Voids a payment
/// </summary>
/// <param name="voidPaymentRequest">Request</param>
/// <returns>Result</returns>
public VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest)
{
var result = new VoidPaymentResult();
result.AddError("Void method not supported");
return result;
}
/// <summary>
/// Process recurring payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
{
var result = new ProcessPaymentResult();
result.AddError("Recurring payment not supported");
return result;
}
/// <summary>
/// Cancels a recurring payment
/// </summary>
/// <param name="cancelPaymentRequest">Request</param>
/// <returns>Result</returns>
public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest)
{
var result = new CancelRecurringPaymentResult();
result.AddError("Recurring payment not supported");
return result;
}
/// <summary>
/// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)
/// </summary>
/// <param name="order">Order</param>
/// <returns>Result</returns>
public bool CanRePostProcessPayment(Order order)
{
if (order == null)
throw new ArgumentNullException("order");
//it's not a redirection payment method. So we always return false
return false;
}
/// <summary>
/// Gets a route for provider configuration
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "Configure";
controllerName = "PaymentPurchaseOrder";
routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Payments.PurchaseOrder.Controllers" }, { "area", null } };
}
/// <summary>
/// Gets a route for payment info
/// </summary>
/// <param name="actionName">Action name</param>
/// <param name="controllerName">Controller name</param>
/// <param name="routeValues">Route values</param>
public void GetPaymentInfoRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues)
{
actionName = "PaymentInfo";
controllerName = "PaymentPurchaseOrder";
routeValues = new RouteValueDictionary { { "Namespaces", "Nop.Plugin.Payments.PurchaseOrder.Controllers" }, { "area", null } };
}
public Type GetControllerType()
{
return typeof(PaymentPurchaseOrderController);
}
/// <summary>
/// Install plugin
/// </summary>
public override void Install()
{
//settings
var settings = new PurchaseOrderPaymentSettings
{
AdditionalFee = 0,
};
_settingService.SaveSetting(settings);
//locales
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.PurchaseOrderNumber", "PO Number");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFee", "Additional fee");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFee.Hint", "The additional fee.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFeePercentage", "Additional fee. Use percentage");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFeePercentage.Hint", "Determines whether to apply a percentage additional fee to the order total. If not enabled, a fixed value is used.");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.ShippableProductRequired", "Shippable product required");
this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.ShippableProductRequired.Hint", "An option indicating whether shippable products are required in order to display this payment method during checkout.");
base.Install();
}
public override void Uninstall()
{
//settings
_settingService.DeleteSetting<PurchaseOrderPaymentSettings>();
//locales
this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.PurchaseOrderNumber");
this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFee");
this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFee.Hint");
this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFeePercentage");
this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFeePercentage.Hint");
this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.ShippableProductRequired");
this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.ShippableProductRequired.Hint");
base.Uninstall();
}
#endregion
#region Properies
/// <summary>
/// Gets a value indicating whether capture is supported
/// </summary>
public bool SupportCapture
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether partial refund is supported
/// </summary>
public bool SupportPartiallyRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether refund is supported
/// </summary>
public bool SupportRefund
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether void is supported
/// </summary>
public bool SupportVoid
{
get
{
return false;
}
}
/// <summary>
/// Gets a recurring payment type of payment method
/// </summary>
public RecurringPaymentType RecurringPaymentType
{
get
{
return RecurringPaymentType.NotSupported;
}
}
/// <summary>
/// Gets a payment method type
/// </summary>
public PaymentMethodType PaymentMethodType
{
get
{
return PaymentMethodType.Standard;
}
}
/// <summary>
/// Gets a value indicating whether we should display a payment information page for this plugin
/// </summary>
public bool SkipPaymentInfo
{
get
{
return false;
}
}
#endregion
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Configuration;
using System.Reflection;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;
namespace log4net.Util
{
/// <summary>
/// Utility class for system specific information.
/// </summary>
/// <remarks>
/// <para>
/// Utility class of static methods for system specific information.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Alexey Solofnenko</author>
public sealed class SystemInfo
{
#region Private Constants
private const string DEFAULT_NULL_TEXT = "(null)";
private const string DEFAULT_NOT_AVAILABLE_TEXT = "NOT AVAILABLE";
#endregion
#region Private Instance Constructors
/// <summary>
/// Private constructor to prevent instances.
/// </summary>
/// <remarks>
/// <para>
/// Only static methods are exposed from this type.
/// </para>
/// </remarks>
private SystemInfo()
{
}
#endregion Private Instance Constructors
#region Public Static Constructor
/// <summary>
/// Initialize default values for private static fields.
/// </summary>
/// <remarks>
/// <para>
/// Only static methods are exposed from this type.
/// </para>
/// </remarks>
static SystemInfo()
{
string nullText = DEFAULT_NULL_TEXT;
string notAvailableText = DEFAULT_NOT_AVAILABLE_TEXT;
#if !NETCF
// Look for log4net.NullText in AppSettings
string nullTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NullText");
if (nullTextAppSettingsKey != null && nullTextAppSettingsKey.Length > 0)
{
LogLog.Debug(declaringType, "Initializing NullText value to [" + nullTextAppSettingsKey + "].");
nullText = nullTextAppSettingsKey;
}
// Look for log4net.NotAvailableText in AppSettings
string notAvailableTextAppSettingsKey = SystemInfo.GetAppSetting("log4net.NotAvailableText");
if (notAvailableTextAppSettingsKey != null && notAvailableTextAppSettingsKey.Length > 0)
{
LogLog.Debug(declaringType, "Initializing NotAvailableText value to [" + notAvailableTextAppSettingsKey + "].");
notAvailableText = notAvailableTextAppSettingsKey;
}
#endif
s_notAvailableText = notAvailableText;
s_nullText = nullText;
}
#endregion
#region Public Static Properties
/// <summary>
/// Gets the system dependent line terminator.
/// </summary>
/// <value>
/// The system dependent line terminator.
/// </value>
/// <remarks>
/// <para>
/// Gets the system dependent line terminator.
/// </para>
/// </remarks>
public static string NewLine
{
get
{
#if NETCF
return "\r\n";
#else
return System.Environment.NewLine;
#endif
}
}
/// <summary>
/// Gets the base directory for this <see cref="AppDomain"/>.
/// </summary>
/// <value>The base directory path for the current <see cref="AppDomain"/>.</value>
/// <remarks>
/// <para>
/// Gets the base directory for this <see cref="AppDomain"/>.
/// </para>
/// <para>
/// The value returned may be either a local file path or a URI.
/// </para>
/// </remarks>
public static string ApplicationBaseDirectory
{
get
{
#if NETCF
return System.IO.Path.GetDirectoryName(SystemInfo.EntryAssemblyLocation) + System.IO.Path.DirectorySeparatorChar;
#else
return AppDomain.CurrentDomain.BaseDirectory;
#endif
}
}
/// <summary>
/// Gets the path to the configuration file for the current <see cref="AppDomain"/>.
/// </summary>
/// <value>The path to the configuration file for the current <see cref="AppDomain"/>.</value>
/// <remarks>
/// <para>
/// The .NET Compact Framework 1.0 does not have a concept of a configuration
/// file. For this runtime, we use the entry assembly location as the root for
/// the configuration file name.
/// </para>
/// <para>
/// The value returned may be either a local file path or a URI.
/// </para>
/// </remarks>
public static string ConfigurationFileLocation
{
get
{
#if NETCF
return SystemInfo.EntryAssemblyLocation+".config";
#else
return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
#endif
}
}
/// <summary>
/// Gets the path to the file that first executed in the current <see cref="AppDomain"/>.
/// </summary>
/// <value>The path to the entry assembly.</value>
/// <remarks>
/// <para>
/// Gets the path to the file that first executed in the current <see cref="AppDomain"/>.
/// </para>
/// </remarks>
public static string EntryAssemblyLocation
{
get
{
#if NETCF
return SystemInfo.NativeEntryAssemblyLocation;
#else
return System.Reflection.Assembly.GetEntryAssembly().Location;
#endif
}
}
/// <summary>
/// Gets the ID of the current thread.
/// </summary>
/// <value>The ID of the current thread.</value>
/// <remarks>
/// <para>
/// On the .NET framework, the <c>AppDomain.GetCurrentThreadId</c> method
/// is used to obtain the thread ID for the current thread. This is the
/// operating system ID for the thread.
/// </para>
/// <para>
/// On the .NET Compact Framework 1.0 it is not possible to get the
/// operating system thread ID for the current thread. The native method
/// <c>GetCurrentThreadId</c> is implemented inline in a header file
/// and cannot be called.
/// </para>
/// <para>
/// On the .NET Framework 2.0 the <c>Thread.ManagedThreadId</c> is used as this
/// gives a stable id unrelated to the operating system thread ID which may
/// change if the runtime is using fibers.
/// </para>
/// </remarks>
public static int CurrentThreadId
{
get
{
#if NETCF_1_0
return System.Threading.Thread.CurrentThread.GetHashCode();
#elif NET_2_0 || NETCF_2_0 || MONO_2_0
return System.Threading.Thread.CurrentThread.ManagedThreadId;
#else
return AppDomain.GetCurrentThreadId();
#endif
}
}
/// <summary>
/// Get the host name or machine name for the current machine
/// </summary>
/// <value>
/// The hostname or machine name
/// </value>
/// <remarks>
/// <para>
/// Get the host name or machine name for the current machine
/// </para>
/// <para>
/// The host name (<see cref="System.Net.Dns.GetHostName"/>) or
/// the machine name (<c>Environment.MachineName</c>) for
/// the current machine, or if neither of these are available
/// then <c>NOT AVAILABLE</c> is returned.
/// </para>
/// </remarks>
public static string HostName
{
get
{
if (s_hostName == null)
{
// Get the DNS host name of the current machine
try
{
// Lookup the host name
s_hostName = System.Net.Dns.GetHostName();
}
catch (System.Net.Sockets.SocketException)
{
LogLog.Debug(declaringType, "Socket exception occurred while getting the dns hostname. Error Ignored.");
}
catch (System.Security.SecurityException)
{
// We may get a security exception looking up the hostname
// You must have Unrestricted DnsPermission to access resource
LogLog.Debug(declaringType, "Security exception occurred while getting the dns hostname. Error Ignored.");
}
catch (Exception ex)
{
LogLog.Debug(declaringType, "Some other exception occurred while getting the dns hostname. Error Ignored.", ex);
}
// Get the NETBIOS machine name of the current machine
if (s_hostName == null || s_hostName.Length == 0)
{
try
{
#if (!SSCLI && !NETCF)
s_hostName = Environment.MachineName;
#endif
}
catch(InvalidOperationException)
{
}
catch(System.Security.SecurityException)
{
// We may get a security exception looking up the machine name
// You must have Unrestricted EnvironmentPermission to access resource
}
}
// Couldn't find a value
if (s_hostName == null || s_hostName.Length == 0)
{
s_hostName = s_notAvailableText;
LogLog.Debug(declaringType, "Could not determine the hostname. Error Ignored. Empty host name will be used");
}
}
return s_hostName;
}
}
/// <summary>
/// Get this application's friendly name
/// </summary>
/// <value>
/// The friendly name of this application as a string
/// </value>
/// <remarks>
/// <para>
/// If available the name of the application is retrieved from
/// the <c>AppDomain</c> using <c>AppDomain.CurrentDomain.FriendlyName</c>.
/// </para>
/// <para>
/// Otherwise the file name of the entry assembly is used.
/// </para>
/// </remarks>
public static string ApplicationFriendlyName
{
get
{
if (s_appFriendlyName == null)
{
try
{
#if !NETCF
s_appFriendlyName = AppDomain.CurrentDomain.FriendlyName;
#endif
}
catch(System.Security.SecurityException)
{
// This security exception will occur if the caller does not have
// some undefined set of SecurityPermission flags.
LogLog.Debug(declaringType, "Security exception while trying to get current domain friendly name. Error Ignored.");
}
if (s_appFriendlyName == null || s_appFriendlyName.Length == 0)
{
try
{
string assemblyLocation = SystemInfo.EntryAssemblyLocation;
s_appFriendlyName = System.IO.Path.GetFileName(assemblyLocation);
}
catch(System.Security.SecurityException)
{
// Caller needs path discovery permission
}
}
if (s_appFriendlyName == null || s_appFriendlyName.Length == 0)
{
s_appFriendlyName = s_notAvailableText;
}
}
return s_appFriendlyName;
}
}
/// <summary>
/// Get the start time for the current process.
/// </summary>
/// <remarks>
/// <para>
/// This is the time at which the log4net library was loaded into the
/// AppDomain. Due to reports of a hang in the call to <c>System.Diagnostics.Process.StartTime</c>
/// this is not the start time for the current process.
/// </para>
/// <para>
/// The log4net library should be loaded by an application early during its
/// startup, therefore this start time should be a good approximation for
/// the actual start time.
/// </para>
/// <para>
/// Note that AppDomains may be loaded and unloaded within the
/// same process without the process terminating, however this start time
/// will be set per AppDomain.
/// </para>
/// </remarks>
public static DateTime ProcessStartTime
{
get { return s_processStartTime; }
}
/// <summary>
/// Text to output when a <c>null</c> is encountered.
/// </summary>
/// <remarks>
/// <para>
/// Use this value to indicate a <c>null</c> has been encountered while
/// outputting a string representation of an item.
/// </para>
/// <para>
/// The default value is <c>(null)</c>. This value can be overridden by specifying
/// a value for the <c>log4net.NullText</c> appSetting in the application's
/// .config file.
/// </para>
/// </remarks>
public static string NullText
{
get { return s_nullText; }
set { s_nullText = value; }
}
/// <summary>
/// Text to output when an unsupported feature is requested.
/// </summary>
/// <remarks>
/// <para>
/// Use this value when an unsupported feature is requested.
/// </para>
/// <para>
/// The default value is <c>NOT AVAILABLE</c>. This value can be overridden by specifying
/// a value for the <c>log4net.NotAvailableText</c> appSetting in the application's
/// .config file.
/// </para>
/// </remarks>
public static string NotAvailableText
{
get { return s_notAvailableText; }
set { s_notAvailableText = value; }
}
#endregion Public Static Properties
#region Public Static Methods
/// <summary>
/// Gets the assembly location path for the specified assembly.
/// </summary>
/// <param name="myAssembly">The assembly to get the location for.</param>
/// <returns>The location of the assembly.</returns>
/// <remarks>
/// <para>
/// This method does not guarantee to return the correct path
/// to the assembly. If only tries to give an indication as to
/// where the assembly was loaded from.
/// </para>
/// </remarks>
public static string AssemblyLocationInfo(Assembly myAssembly)
{
#if NETCF
return "Not supported on Microsoft .NET Compact Framework";
#else
if (myAssembly.GlobalAssemblyCache)
{
return "Global Assembly Cache";
}
else
{
try
{
// This call requires FileIOPermission for access to the path
// if we don't have permission then we just ignore it and
// carry on.
return myAssembly.Location;
}
catch (ArgumentException ex)
{
return "Location Detect Failed (" + ex.Message + ")";
}
catch (System.Security.SecurityException)
{
return "Location Permission Denied";
}
}
#endif
}
/// <summary>
/// Gets the fully qualified name of the <see cref="Type" />, including
/// the name of the assembly from which the <see cref="Type" /> was
/// loaded.
/// </summary>
/// <param name="type">The <see cref="Type" /> to get the fully qualified name for.</param>
/// <returns>The fully qualified name for the <see cref="Type" />.</returns>
/// <remarks>
/// <para>
/// This is equivalent to the <c>Type.AssemblyQualifiedName</c> property,
/// but this method works on the .NET Compact Framework 1.0 as well as
/// the full .NET runtime.
/// </para>
/// </remarks>
public static string AssemblyQualifiedName(Type type)
{
return type.FullName + ", " + type.Assembly.FullName;
}
/// <summary>
/// Gets the short name of the <see cref="Assembly" />.
/// </summary>
/// <param name="myAssembly">The <see cref="Assembly" /> to get the name for.</param>
/// <returns>The short name of the <see cref="Assembly" />.</returns>
/// <remarks>
/// <para>
/// The short name of the assembly is the <see cref="Assembly.FullName" />
/// without the version, culture, or public key. i.e. it is just the
/// assembly's file name without the extension.
/// </para>
/// <para>
/// Use this rather than <c>Assembly.GetName().Name</c> because that
/// is not available on the Compact Framework.
/// </para>
/// <para>
/// Because of a FileIOPermission security demand we cannot do
/// the obvious Assembly.GetName().Name. We are allowed to get
/// the <see cref="Assembly.FullName" /> of the assembly so we
/// start from there and strip out just the assembly name.
/// </para>
/// </remarks>
public static string AssemblyShortName(Assembly myAssembly)
{
string name = myAssembly.FullName;
int offset = name.IndexOf(',');
if (offset > 0)
{
name = name.Substring(0, offset);
}
return name.Trim();
// TODO: Do we need to unescape the assembly name string?
// Doc says '\' is an escape char but has this already been
// done by the string loader?
}
/// <summary>
/// Gets the file name portion of the <see cref="Assembly" />, including the extension.
/// </summary>
/// <param name="myAssembly">The <see cref="Assembly" /> to get the file name for.</param>
/// <returns>The file name of the assembly.</returns>
/// <remarks>
/// <para>
/// Gets the file name portion of the <see cref="Assembly" />, including the extension.
/// </para>
/// </remarks>
public static string AssemblyFileName(Assembly myAssembly)
{
#if NETCF
// This is not very good because it assumes that only
// the entry assembly can be an EXE. In fact multiple
// EXEs can be loaded in to a process.
string assemblyShortName = SystemInfo.AssemblyShortName(myAssembly);
string entryAssemblyShortName = System.IO.Path.GetFileNameWithoutExtension(SystemInfo.EntryAssemblyLocation);
if (string.Compare(assemblyShortName, entryAssemblyShortName, true) == 0)
{
// assembly is entry assembly
return assemblyShortName + ".exe";
}
else
{
// assembly is not entry assembly
return assemblyShortName + ".dll";
}
#else
return System.IO.Path.GetFileName(myAssembly.Location);
#endif
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeType">A sibling type to use to load the type.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified, it will be loaded from the assembly
/// containing the specified relative type. If the type is not found in the assembly
/// then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase);
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the
/// assembly that is directly calling this method. If the type is not found
/// in the assembly then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase);
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeAssembly">An assembly to load the type from.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the specified
/// assembly. If the type is not found in the assembly then all the loaded assemblies
/// will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase)
{
// Check if the type name specifies the assembly name
if(typeName.IndexOf(',') == -1)
{
//LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
#if NETCF
return relativeAssembly.GetType(typeName, throwOnError);
#else
// Attempt to lookup the type from the relativeAssembly
Type type = relativeAssembly.GetType(typeName, false, ignoreCase);
if (type != null)
{
// Found type in relative assembly
//LogLog.Debug(declaringType, "SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
return type;
}
Assembly[] loadedAssemblies = null;
try
{
loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
}
catch(System.Security.SecurityException)
{
// Insufficient permissions to get the list of loaded assemblies
}
if (loadedAssemblies != null)
{
// Search the loaded assemblies for the type
foreach (Assembly assembly in loadedAssemblies)
{
type = assembly.GetType(typeName, false, ignoreCase);
if (type != null)
{
// Found type in loaded assembly
LogLog.Debug(declaringType, "Loaded type ["+typeName+"] from assembly ["+assembly.FullName+"] by searching loaded assemblies.");
return type;
}
}
}
// Didn't find the type
if (throwOnError)
{
throw new TypeLoadException("Could not load type ["+typeName+"]. Tried assembly ["+relativeAssembly.FullName+"] and all loaded assemblies");
}
return null;
#endif
}
else
{
// Includes explicit assembly name
//LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from global Type");
#if NETCF
// In NETCF 2 and 3 arg versions seem to behave differently
// https://issues.apache.org/jira/browse/LOG4NET-113
return Type.GetType(typeName, throwOnError);
#else
return Type.GetType(typeName, throwOnError, ignoreCase);
#endif
}
}
/// <summary>
/// Generate a new guid
/// </summary>
/// <returns>A new Guid</returns>
/// <remarks>
/// <para>
/// Generate a new guid
/// </para>
/// </remarks>
public static Guid NewGuid()
{
#if NETCF_1_0
return PocketGuid.NewGuid();
#else
return Guid.NewGuid();
#endif
}
/// <summary>
/// Create an <see cref="ArgumentOutOfRangeException"/>
/// </summary>
/// <param name="parameterName">The name of the parameter that caused the exception</param>
/// <param name="actualValue">The value of the argument that causes this exception</param>
/// <param name="message">The message that describes the error</param>
/// <returns>the ArgumentOutOfRangeException object</returns>
/// <remarks>
/// <para>
/// Create a new instance of the <see cref="ArgumentOutOfRangeException"/> class
/// with a specified error message, the parameter name, and the value
/// of the argument.
/// </para>
/// <para>
/// The Compact Framework does not support the 3 parameter constructor for the
/// <see cref="ArgumentOutOfRangeException"/> type. This method provides an
/// implementation that works for all platforms.
/// </para>
/// </remarks>
public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message)
{
#if NETCF_1_0
return new ArgumentOutOfRangeException(message + " [param=" + parameterName + "] [value=" + actualValue + "]");
#elif NETCF_2_0
return new ArgumentOutOfRangeException(parameterName, message + " [value=" + actualValue + "]");
#else
return new ArgumentOutOfRangeException(parameterName, actualValue, message);
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int32"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out int val)
{
#if NETCF
val = 0;
try
{
val = int.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt32(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int64"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out long val)
{
#if NETCF
val = 0;
try
{
val = long.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt64(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int16"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out short val)
{
#if NETCF
val = 0;
try
{
val = short.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt16(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Lookup an application setting
/// </summary>
/// <param name="key">the application settings key to lookup</param>
/// <returns>the value for the key, or <c>null</c></returns>
/// <remarks>
/// <para>
/// Configuration APIs are not supported under the Compact Framework
/// </para>
/// </remarks>
public static string GetAppSetting(string key)
{
try
{
#if NETCF
// Configuration APIs are not suported under the Compact Framework
#elif NET_2_0
return ConfigurationManager.AppSettings[key];
#else
return ConfigurationSettings.AppSettings[key];
#endif
}
catch(Exception ex)
{
// If an exception is thrown here then it looks like the config file does not parse correctly.
LogLog.Error(declaringType, "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex);
}
return null;
}
/// <summary>
/// Convert a path into a fully qualified local file path.
/// </summary>
/// <param name="path">The path to convert.</param>
/// <returns>The fully qualified path.</returns>
/// <remarks>
/// <para>
/// Converts the path specified to a fully
/// qualified path. If the path is relative it is
/// taken as relative from the application base
/// directory.
/// </para>
/// <para>
/// The path specified must be a local file path, a URI is not supported.
/// </para>
/// </remarks>
public static string ConvertToFullPath(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
string baseDirectory = "";
try
{
string applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
if (applicationBaseDirectory != null)
{
// applicationBaseDirectory may be a URI not a local file path
Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory);
if (applicationBaseDirectoryUri.IsFile)
{
baseDirectory = applicationBaseDirectoryUri.LocalPath;
}
}
}
catch
{
// Ignore URI exceptions & SecurityExceptions from SystemInfo.ApplicationBaseDirectory
}
if (baseDirectory != null && baseDirectory.Length > 0)
{
// Note that Path.Combine will return the second path if it is rooted
return Path.GetFullPath(Path.Combine(baseDirectory, path));
}
return Path.GetFullPath(path);
}
/// <summary>
/// Creates a new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity.
/// </summary>
/// <returns>A new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity</returns>
/// <remarks>
/// <para>
/// The new Hashtable instance uses the default load factor, the CaseInsensitiveHashCodeProvider, and the CaseInsensitiveComparer.
/// </para>
/// </remarks>
public static Hashtable CreateCaseInsensitiveHashtable()
{
#if NETCF_1_0
return new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default);
#elif NETCF_2_0 || NET_2_0 || MONO_2_0
return new Hashtable(StringComparer.OrdinalIgnoreCase);
#else
return System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable();
#endif
}
#endregion Public Static Methods
#region Private Static Methods
#if NETCF
private static string NativeEntryAssemblyLocation
{
get
{
StringBuilder moduleName = null;
IntPtr moduleHandle = GetModuleHandle(IntPtr.Zero);
if (moduleHandle != IntPtr.Zero)
{
moduleName = new StringBuilder(255);
if (GetModuleFileName(moduleHandle, moduleName, moduleName.Capacity) == 0)
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
}
else
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
return moduleName.ToString();
}
}
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern IntPtr GetModuleHandle(IntPtr ModuleName);
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern Int32 GetModuleFileName(
IntPtr hModule,
StringBuilder ModuleName,
Int32 cch);
#endif
#endregion Private Static Methods
#region Public Static Fields
/// <summary>
/// Gets an empty array of types.
/// </summary>
/// <remarks>
/// <para>
/// The <c>Type.EmptyTypes</c> field is not available on
/// the .NET Compact Framework 1.0.
/// </para>
/// </remarks>
public static readonly Type[] EmptyTypes = new Type[0];
#endregion Public Static Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the SystemInfo class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(SystemInfo);
/// <summary>
/// Cache the host name for the current machine
/// </summary>
private static string s_hostName;
/// <summary>
/// Cache the application friendly name
/// </summary>
private static string s_appFriendlyName;
/// <summary>
/// Text to output when a <c>null</c> is encountered.
/// </summary>
private static string s_nullText;
/// <summary>
/// Text to output when an unsupported feature is requested.
/// </summary>
private static string s_notAvailableText;
/// <summary>
/// Start time for the current process.
/// </summary>
private static DateTime s_processStartTime = DateTime.Now;
#endregion
#region Compact Framework Helper Classes
#if NETCF_1_0
/// <summary>
/// Generate GUIDs on the .NET Compact Framework.
/// </summary>
public class PocketGuid
{
// guid variant types
private enum GuidVariant
{
ReservedNCS = 0x00,
Standard = 0x02,
ReservedMicrosoft = 0x06,
ReservedFuture = 0x07
}
// guid version types
private enum GuidVersion
{
TimeBased = 0x01,
Reserved = 0x02,
NameBased = 0x03,
Random = 0x04
}
// constants that are used in the class
private class Const
{
// number of bytes in guid
public const int ByteArraySize = 16;
// multiplex variant info
public const int VariantByte = 8;
public const int VariantByteMask = 0x3f;
public const int VariantByteShift = 6;
// multiplex version info
public const int VersionByte = 7;
public const int VersionByteMask = 0x0f;
public const int VersionByteShift = 4;
}
// imports for the crypto api functions
private class WinApi
{
public const uint PROV_RSA_FULL = 1;
public const uint CRYPT_VERIFYCONTEXT = 0xf0000000;
[DllImport("CoreDll.dll")]
public static extern bool CryptAcquireContext(
ref IntPtr phProv, string pszContainer, string pszProvider,
uint dwProvType, uint dwFlags);
[DllImport("CoreDll.dll")]
public static extern bool CryptReleaseContext(
IntPtr hProv, uint dwFlags);
[DllImport("CoreDll.dll")]
public static extern bool CryptGenRandom(
IntPtr hProv, int dwLen, byte[] pbBuffer);
}
// all static methods
private PocketGuid()
{
}
/// <summary>
/// Return a new System.Guid object.
/// </summary>
public static Guid NewGuid()
{
IntPtr hCryptProv = IntPtr.Zero;
Guid guid = Guid.Empty;
try
{
// holds random bits for guid
byte[] bits = new byte[Const.ByteArraySize];
// get crypto provider handle
if (!WinApi.CryptAcquireContext(ref hCryptProv, null, null,
WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT))
{
throw new SystemException(
"Failed to acquire cryptography handle.");
}
// generate a 128 bit (16 byte) cryptographically random number
if (!WinApi.CryptGenRandom(hCryptProv, bits.Length, bits))
{
throw new SystemException(
"Failed to generate cryptography random bytes.");
}
// set the variant
bits[Const.VariantByte] &= Const.VariantByteMask;
bits[Const.VariantByte] |=
((int)GuidVariant.Standard << Const.VariantByteShift);
// set the version
bits[Const.VersionByte] &= Const.VersionByteMask;
bits[Const.VersionByte] |=
((int)GuidVersion.Random << Const.VersionByteShift);
// create the new System.Guid object
guid = new Guid(bits);
}
finally
{
// release the crypto provider handle
if (hCryptProv != IntPtr.Zero)
WinApi.CryptReleaseContext(hCryptProv, 0);
}
return guid;
}
}
#endif
#endregion Compact Framework Helper Classes
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Authorization;
using Microsoft.Azure.Management.Authorization.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Authorization
{
/// <summary>
/// Get classic administrator details (see http://TBD for more information)
/// </summary>
internal partial class ClassicAdministratorOperations : IServiceOperations<AuthorizationManagementClient>, IClassicAdministratorOperations
{
/// <summary>
/// Initializes a new instance of the ClassicAdministratorOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ClassicAdministratorOperations(AuthorizationManagementClient client)
{
this._client = client;
}
private AuthorizationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Authorization.AuthorizationManagementClient.
/// </summary>
public AuthorizationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Gets a list of classic administrators for the subscription.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// ClassicAdministrator list result information.
/// </returns>
public async Task<ClassicAdministratorListResult> ListAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.Authorization/classicAdministrators";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-06-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2015-07-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ClassicAdministratorListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ClassicAdministratorListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
ClassicAdministrator classicAdministratorInstance = new ClassicAdministrator();
result.ClassicAdministrators.Add(classicAdministratorInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
classicAdministratorInstance.Id = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
classicAdministratorInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
classicAdministratorInstance.Type = typeInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ClassicAdministratorProperties propertiesInstance = new ClassicAdministratorProperties();
classicAdministratorInstance.Properties = propertiesInstance;
JToken emailAddressValue = propertiesValue["emailAddress"];
if (emailAddressValue != null && emailAddressValue.Type != JTokenType.Null)
{
string emailAddressInstance = ((string)emailAddressValue);
propertiesInstance.EmailAddress = emailAddressInstance;
}
JToken roleValue = propertiesValue["role"];
if (roleValue != null && roleValue.Type != JTokenType.Null)
{
string roleInstance = ((string)roleValue);
propertiesInstance.Role = roleInstance;
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// 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.DirectoryServices.Interop;
namespace System.DirectoryServices
{
/// <devdoc>
/// Contains a list of schema names used for the <see cref='System.DirectoryServices.DirectoryEntries.SchemaFilter'/> property of a <see cref='System.DirectoryServices.DirectoryEntries'/>.
/// </devdoc>
public class SchemaNameCollection : IList
{
private readonly VariantPropGetter _propGetter;
private readonly VariantPropSetter _propSetter;
internal SchemaNameCollection(VariantPropGetter propGetter, VariantPropSetter propSetter)
{
_propGetter = propGetter;
_propSetter = propSetter;
}
/// <devdoc>
/// Gets or sets the object at the given index.
/// </devdoc>
public string this[int index]
{
get
{
object[] values = GetValue();
return (string)values[index];
}
set
{
object[] values = GetValue();
values[index] = value;
_propSetter(values);
}
}
/// <devdoc>
/// Gets the number of objects available on this entry.
/// </devdoc>
public int Count
{
get
{
object[] values = GetValue();
return values.Length;
}
}
/// <devdoc>
/// Appends the value to the collection.
/// </devdoc>
public int Add(string value)
{
object[] oldValues = GetValue();
object[] newValues = new object[oldValues.Length + 1];
for (int i = 0; i < oldValues.Length; i++)
newValues[i] = oldValues[i];
newValues[newValues.Length - 1] = value;
_propSetter(newValues);
return newValues.Length - 1;
}
/// <devdoc>
/// Appends the values to the collection.
/// </devdoc>
public void AddRange(string[] value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
object[] oldValues = GetValue();
object[] newValues = new object[oldValues.Length + value.Length];
for (int i = 0; i < oldValues.Length; i++)
newValues[i] = oldValues[i];
for (int i = oldValues.Length; i < newValues.Length; i++)
newValues[i] = value[i - oldValues.Length];
_propSetter(newValues);
}
public void AddRange(SchemaNameCollection value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
object[] oldValues = GetValue();
object[] newValues = new object[oldValues.Length + value.Count];
for (int i = 0; i < oldValues.Length; i++)
newValues[i] = oldValues[i];
for (int i = oldValues.Length; i < newValues.Length; i++)
newValues[i] = value[i - oldValues.Length];
_propSetter(newValues);
}
/// <devdoc>
/// Removes all items from the collection.
/// </devdoc>
public void Clear()
{
object[] newValues = new object[0];
_propSetter(newValues);
}
/// <devdoc>
/// Determines if the collection contains a specific value.
/// </devdoc>
public bool Contains(string value) => IndexOf(value) != -1;
public void CopyTo(String[] stringArray, int index)
{
object[] values = GetValue();
values.CopyTo(stringArray, index);
}
public IEnumerator GetEnumerator()
{
object[] values = GetValue();
return values.GetEnumerator();
}
private object[] GetValue()
{
object value = _propGetter();
if (value == null)
return new object[0];
else
return (object[])value;
}
/// <devdoc>
/// Determines the index of a specific item in the collection.
/// </devdoc>
public int IndexOf(string value)
{
object[] values = GetValue();
for (int i = 0; i < values.Length; i++)
{
if (value == (string)values[i])
return i;
}
return -1;
}
/// <devdoc>
/// Inserts an item at the specified position in the collection.
/// </devdoc>
public void Insert(int index, string value)
{
ArrayList tmpList = new ArrayList((ICollection)GetValue());
tmpList.Insert(index, value);
_propSetter(tmpList.ToArray());
}
/// <devdoc>
/// Removes an item from the collection.
/// </devdoc>
public void Remove(string value)
{
// this does take two scans of the array, but value isn't guaranteed to be there.
int index = IndexOf(value);
RemoveAt(index);
}
/// <devdoc>
/// Removes the item at the specified index from the collection.
/// </devdoc>
public void RemoveAt(int index)
{
object[] oldValues = GetValue();
if (index >= oldValues.Length || index < 0)
throw new ArgumentOutOfRangeException("index");
object[] newValues = new object[oldValues.Length - 1];
for (int i = 0; i < index; i++)
newValues[i] = oldValues[i];
for (int i = index + 1; i < oldValues.Length; i++)
newValues[i - 1] = oldValues[i];
_propSetter(newValues);
}
bool IList.IsReadOnly => false;
bool IList.IsFixedSize => false;
void ICollection.CopyTo(Array array, int index)
{
object[] values = GetValue();
values.CopyTo(array, index);
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => this;
object IList.this[int index]
{
get => this[index];
set => this[index] = (string)value;
}
int IList.Add(object value) => Add((string)value);
bool IList.Contains(object value) => Contains((string)value);
int IList.IndexOf(object value) => IndexOf((string)value);
void IList.Insert(int index, object value) => Insert(index, (string)value);
void IList.Remove(object value) => Remove((string)value);
internal delegate object VariantPropGetter();
internal delegate void VariantPropSetter(object value);
// this class and HintsDelegateWrapper exist only because you can't create
// a delegate to a property's accessors. You have to supply methods. So these
// classes wrap an object and supply properties as methods.
internal class FilterDelegateWrapper
{
private UnsafeNativeMethods.IAdsContainer _obj;
internal FilterDelegateWrapper(UnsafeNativeMethods.IAdsContainer wrapped)
{
_obj = wrapped;
}
public VariantPropGetter Getter => new VariantPropGetter(GetFilter);
public VariantPropSetter Setter => new VariantPropSetter(SetFilter);
private object GetFilter() => _obj.Filter;
private void SetFilter(object value) => _obj.Filter = value;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ErrorHandling.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using DarkMultiPlayerCommon;
using System.Reflection;
using Contracts;
namespace DarkMultiPlayer
{
public class ScenarioWorker
{
public bool workerEnabled = false;
private static ScenarioWorker singleton;
private Dictionary<string,string> checkData = new Dictionary<string, string>();
private Queue<ScenarioEntry> scenarioQueue = new Queue<ScenarioEntry>();
private bool blockScenarioDataSends = false;
private float lastScenarioSendTime = 0f;
private const float SEND_SCENARIO_DATA_INTERVAL = 30f;
//ScenarioType list to check.
private Dictionary<string, Type> allScenarioTypesInAssemblies;
//System.Reflection hackiness for loading kerbals into the crew roster:
private delegate bool AddCrewMemberToRosterDelegate(ProtoCrewMember pcm);
// Game hooks
private bool registered;
private AddCrewMemberToRosterDelegate AddCrewMemberToRoster;
public static ScenarioWorker fetch
{
get
{
return singleton;
}
}
private void RegisterGameHooks()
{
registered = true;
GameEvents.Contract.onAccepted.Add(OnContractAccepted);
}
private void UnregisterGameHooks()
{
registered = false;
GameEvents.Contract.onAccepted.Remove(OnContractAccepted);
}
private void OnContractAccepted(Contract contract)
{
DarkLog.Debug("Contract accepted, state: " + contract.ContractState);
ConfigNode contractNode = new ConfigNode();
contract.Save(contractNode);
if (contractNode.GetValue("type") == "RecoverAsset")
{
string kerbalName = contractNode.GetValue("kerbalName").Trim();
int kerbalGender = int.Parse(contractNode.GetValue("gender"));
uint partID = uint.Parse(contractNode.GetValue("partID"));
if (!string.IsNullOrEmpty(kerbalName))
{
ProtoCrewMember rescueKerbal = null;
if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName))
{
DarkLog.Debug("Generating missing kerbal " + kerbalName + " for rescue contract");
rescueKerbal = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Unowned);
rescueKerbal.ChangeName(kerbalName);
rescueKerbal.gender = (ProtoCrewMember.Gender)kerbalGender;
rescueKerbal.rosterStatus = ProtoCrewMember.RosterStatus.Assigned;
}
else
{
rescueKerbal = HighLogic.CurrentGame.CrewRoster[kerbalName];
DarkLog.Debug("Kerbal " + kerbalName + " already exists, skipping respawn");
}
if (rescueKerbal != null) VesselWorker.fetch.SendKerbalIfDifferent(rescueKerbal);
}
if (partID != 0)
{
Vessel contractVessel = FinePrint.Utilities.VesselUtilities.FindVesselWithPartIDs(new List<uint> { partID });
if (contractVessel != null) VesselWorker.fetch.SendVesselUpdateIfNeeded(contractVessel);
}
}
else if (contractNode.GetValue("type") == "TourismContract")
{
string tourists = contractNode.GetValue("tourists");
if (tourists != null)
{
string[] touristsNames = tourists.Split(new char[] { '|' });
foreach (string touristName in touristsNames)
{
ProtoCrewMember pcm = null;
if (!HighLogic.CurrentGame.CrewRoster.Exists(touristName))
{
DarkLog.Debug("Spawning missing tourist " + touristName + " for tourism contract");
pcm = HighLogic.CurrentGame.CrewRoster.GetNewKerbal(ProtoCrewMember.KerbalType.Tourist);
pcm.rosterStatus = ProtoCrewMember.RosterStatus.Available;
pcm.ChangeName(touristName);
}
else
{
DarkLog.Debug("Skipped respawn of existing tourist " + touristName);
pcm = HighLogic.CurrentGame.CrewRoster[touristName];
}
if (pcm != null) VesselWorker.fetch.SendKerbalIfDifferent(pcm);
}
}
}
}
private void Update()
{
if (workerEnabled)
{
if (!registered) RegisterGameHooks();
if (!blockScenarioDataSends)
{
if ((UnityEngine.Time.realtimeSinceStartup - lastScenarioSendTime) > SEND_SCENARIO_DATA_INTERVAL)
{
lastScenarioSendTime = UnityEngine.Time.realtimeSinceStartup;
SendScenarioModules(false);
}
}
}
else
{
if (registered) UnregisterGameHooks();
}
}
private void LoadScenarioTypes()
{
allScenarioTypesInAssemblies = new Dictionary<string, Type>();
foreach (AssemblyLoader.LoadedAssembly something in AssemblyLoader.loadedAssemblies)
{
foreach (Type scenarioType in something.assembly.GetTypes())
{
if (scenarioType.IsSubclassOf(typeof(ScenarioModule)))
{
if (!allScenarioTypesInAssemblies.ContainsKey(scenarioType.Name))
{
allScenarioTypesInAssemblies.Add(scenarioType.Name, scenarioType);
}
}
}
}
}
private bool IsScenarioModuleAllowed(string scenarioName)
{
if (scenarioName == null)
{
return false;
}
//Blacklist asteroid module from every game mode
if (scenarioName == "ScenarioDiscoverableObjects")
{
//We hijack this and enable / disable it if we need to.
return false;
}
if (allScenarioTypesInAssemblies == null)
{
//Load type dictionary on first use
LoadScenarioTypes();
}
if (!allScenarioTypesInAssemblies.ContainsKey(scenarioName))
{
//Module missing
return false;
}
Type scenarioType = allScenarioTypesInAssemblies[scenarioName];
KSPScenario[] scenarioAttributes = (KSPScenario[])scenarioType.GetCustomAttributes(typeof(KSPScenario), true);
if (scenarioAttributes.Length > 0)
{
KSPScenario attribute = scenarioAttributes[0];
bool protoAllowed = false;
if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
{
protoAllowed = protoAllowed || attribute.HasCreateOption(ScenarioCreationOptions.AddToExistingCareerGames);
protoAllowed = protoAllowed || attribute.HasCreateOption(ScenarioCreationOptions.AddToNewCareerGames);
}
if (HighLogic.CurrentGame.Mode == Game.Modes.SCIENCE_SANDBOX)
{
protoAllowed = protoAllowed || attribute.HasCreateOption(ScenarioCreationOptions.AddToExistingScienceSandboxGames);
protoAllowed = protoAllowed || attribute.HasCreateOption(ScenarioCreationOptions.AddToNewScienceSandboxGames);
}
if (HighLogic.CurrentGame.Mode == Game.Modes.SANDBOX)
{
protoAllowed = protoAllowed || attribute.HasCreateOption(ScenarioCreationOptions.AddToExistingSandboxGames);
protoAllowed = protoAllowed || attribute.HasCreateOption(ScenarioCreationOptions.AddToNewSandboxGames);
}
return protoAllowed;
}
//Scenario is not marked with KSPScenario - let's load it anyway.
return true;
}
public void SendScenarioModules(bool highPriority)
{
List<string> scenarioName = new List<string>();
List<byte[]> scenarioData = new List<byte[]>();
foreach (ScenarioModule sm in ScenarioRunner.GetLoadedModules())
{
string scenarioType = sm.GetType().Name;
if (!IsScenarioModuleAllowed(scenarioType))
{
continue;
}
ConfigNode scenarioNode = new ConfigNode();
sm.Save(scenarioNode);
byte[] scenarioBytes = ConfigNodeSerializer.fetch.Serialize(scenarioNode);
string scenarioHash = Common.CalculateSHA256Hash(scenarioBytes);
if (scenarioBytes.Length == 0)
{
DarkLog.Debug("Error writing scenario data for " + scenarioType);
continue;
}
if (checkData.ContainsKey(scenarioType) ? (checkData[scenarioType] == scenarioHash) : false)
{
//Data is the same since last time - Skip it.
continue;
}
else
{
checkData[scenarioType] = scenarioHash;
}
if (scenarioBytes != null)
{
scenarioName.Add(scenarioType);
scenarioData.Add(scenarioBytes);
}
}
if (scenarioName.Count > 0)
{
if (highPriority)
{
NetworkWorker.fetch.SendScenarioModuleDataHighPriority(scenarioName.ToArray(), scenarioData.ToArray());
}
else
{
NetworkWorker.fetch.SendScenarioModuleData(scenarioName.ToArray(), scenarioData.ToArray());
}
}
}
public void LoadScenarioDataIntoGame()
{
while (scenarioQueue.Count > 0)
{
ScenarioEntry scenarioEntry = scenarioQueue.Dequeue();
if (scenarioEntry.scenarioName == "ProgressTracking")
{
CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(scenarioEntry.scenarioNode);
}
CheckForBlankSceneSoTheGameDoesntBugOut(scenarioEntry);
ProtoScenarioModule psm = new ProtoScenarioModule(scenarioEntry.scenarioNode);
if (psm != null)
{
if (IsScenarioModuleAllowed(psm.moduleName))
{
DarkLog.Debug("Loading " + psm.moduleName + " scenario data");
HighLogic.CurrentGame.scenarios.Add(psm);
}
else
{
DarkLog.Debug("Skipping " + psm.moduleName + " scenario data in " + Client.fetch.gameMode + " mode");
}
}
}
}
private ConfigNode CreateProcessedPartNode(string part, uint id, params ProtoCrewMember[] crew)
{
ConfigNode configNode = ProtoVessel.CreatePartNode(part, id, crew);
if (part != "kerbalEVA")
{
ConfigNode[] nodes = configNode.GetNodes("RESOURCE");
for (int i = 0; i < nodes.Length; i++)
{
ConfigNode configNode2 = nodes[i];
if (configNode2.HasValue("amount"))
{
configNode2.SetValue("amount", 0.ToString(System.Globalization.CultureInfo.InvariantCulture), false);
}
}
}
configNode.SetValue("flag", "Squad/Flags/default", true);
return configNode;
}
//Defends against bug #172
private void CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(ConfigNode progressTrackingNode)
{
foreach (ConfigNode possibleNode in progressTrackingNode.nodes)
{
//Recursion (noun): See Recursion.
CreateMissingKerbalsInProgressTrackingSoTheGameDoesntBugOut(possibleNode);
}
//The kerbals are kept in a ConfigNode named 'crew', with 'crews' as a comma space delimited array of names.
if (progressTrackingNode.name == "crew")
{
string kerbalNames = progressTrackingNode.GetValue("crews");
if (!String.IsNullOrEmpty(kerbalNames))
{
string[] kerbalNamesSplit = kerbalNames.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
foreach (string kerbalName in kerbalNamesSplit)
{
if (!HighLogic.CurrentGame.CrewRoster.Exists(kerbalName))
{
if (AddCrewMemberToRoster == null)
{
MethodInfo addMemberToCrewRosterMethod = typeof(KerbalRoster).GetMethod("AddCrewMember", BindingFlags.Public | BindingFlags.Instance);
AddCrewMemberToRoster = (AddCrewMemberToRosterDelegate)Delegate.CreateDelegate(typeof(AddCrewMemberToRosterDelegate), HighLogic.CurrentGame.CrewRoster, addMemberToCrewRosterMethod);
}
if (AddCrewMemberToRoster == null)
{
throw new Exception("Failed to initialize AddCrewMemberToRoster for #172 ProgressTracking fix.");
}
DarkLog.Debug("Generating missing kerbal from ProgressTracking: " + kerbalName);
ProtoCrewMember pcm = CrewGenerator.RandomCrewMemberPrototype(ProtoCrewMember.KerbalType.Crew);
pcm.ChangeName(kerbalName);
AddCrewMemberToRoster(pcm);
//Also send it off to the server
VesselWorker.fetch.SendKerbalIfDifferent(pcm);
}
}
}
}
}
//If the scene field is blank, KSP will throw an error while starting the game, meaning players will be unable to join the server.
private void CheckForBlankSceneSoTheGameDoesntBugOut(ScenarioEntry scenarioEntry)
{
if (scenarioEntry.scenarioNode.GetValue("scene") == string.Empty)
{
string nodeName = scenarioEntry.scenarioName;
ScreenMessages.PostScreenMessage(nodeName + " is badly behaved!");
DarkLog.Debug(nodeName + " is badly behaved!");
scenarioEntry.scenarioNode.SetValue("scene", "7, 8, 5, 6, 9");
}
}
public void UpgradeTheAstronautComplexSoTheGameDoesntBugOut()
{
ProtoScenarioModule sm = HighLogic.CurrentGame.scenarios.Find(psm => psm.moduleName == "ScenarioUpgradeableFacilities");
if (sm != null)
{
if (ScenarioUpgradeableFacilities.protoUpgradeables.ContainsKey("SpaceCenter/AstronautComplex"))
{
foreach (Upgradeables.UpgradeableFacility uf in ScenarioUpgradeableFacilities.protoUpgradeables["SpaceCenter/AstronautComplex"].facilityRefs)
{
DarkLog.Debug("Setting astronaut complex to max level");
uf.SetLevel(uf.MaxLevel);
}
}
}
}
public void LoadMissingScenarioDataIntoGame()
{
List<KSPScenarioType> validScenarios = KSPScenarioType.GetAllScenarioTypesInAssemblies();
foreach (KSPScenarioType validScenario in validScenarios)
{
if (HighLogic.CurrentGame.scenarios.Exists(psm => psm.moduleName == validScenario.ModuleType.Name))
{
continue;
}
bool loadModule = false;
if (HighLogic.CurrentGame.Mode == Game.Modes.CAREER)
{
loadModule = validScenario.ScenarioAttributes.HasCreateOption(ScenarioCreationOptions.AddToNewCareerGames);
}
if (HighLogic.CurrentGame.Mode == Game.Modes.SCIENCE_SANDBOX)
{
loadModule = validScenario.ScenarioAttributes.HasCreateOption(ScenarioCreationOptions.AddToNewScienceSandboxGames);
}
if (HighLogic.CurrentGame.Mode == Game.Modes.SANDBOX)
{
loadModule = validScenario.ScenarioAttributes.HasCreateOption(ScenarioCreationOptions.AddToNewSandboxGames);
}
if (loadModule)
{
DarkLog.Debug("Creating new scenario module " + validScenario.ModuleType.Name);
HighLogic.CurrentGame.AddProtoScenarioModule(validScenario.ModuleType, validScenario.ScenarioAttributes.TargetScenes);
}
}
}
public void LoadScenarioData(ScenarioEntry entry)
{
if (!IsScenarioModuleAllowed(entry.scenarioName))
{
DarkLog.Debug("Skipped '" + entry.scenarioName + "' scenario data in " + Client.fetch.gameMode + " mode");
return;
}
//Load data from DMP
if (entry.scenarioNode == null)
{
DarkLog.Debug(entry.scenarioName + " scenario data failed to create a ConfigNode!");
blockScenarioDataSends = true;
return;
}
//Load data into game
bool loaded = false;
foreach (ProtoScenarioModule psm in HighLogic.CurrentGame.scenarios)
{
if (psm.moduleName == entry.scenarioName)
{
DarkLog.Debug("Loading existing " + entry.scenarioName + " scenario module");
try
{
if (psm.moduleRef == null)
{
DarkLog.Debug("Fixing null scenario module!");
psm.moduleRef = new ScenarioModule();
}
psm.moduleRef.Load(entry.scenarioNode);
}
catch (Exception e)
{
DarkLog.Debug("Error loading " + entry.scenarioName + " scenario module, Exception: " + e);
blockScenarioDataSends = true;
}
loaded = true;
}
}
if (!loaded)
{
DarkLog.Debug("Loading new " + entry.scenarioName + " scenario module");
LoadNewScenarioData(entry.scenarioNode);
}
}
public void LoadNewScenarioData(ConfigNode newScenarioData)
{
ProtoScenarioModule newModule = new ProtoScenarioModule(newScenarioData);
try
{
HighLogic.CurrentGame.scenarios.Add(newModule);
newModule.Load(ScenarioRunner.Instance);
}
catch
{
DarkLog.Debug("Error loading scenario data!");
blockScenarioDataSends = true;
}
}
public void QueueScenarioData(string scenarioName, ConfigNode scenarioData)
{
ScenarioEntry entry = new ScenarioEntry();
entry.scenarioName = scenarioName;
entry.scenarioNode = scenarioData;
scenarioQueue.Enqueue(entry);
}
public static void Reset()
{
lock (Client.eventLock)
{
if (singleton != null)
{
singleton.workerEnabled = false;
Client.updateEvent.Remove(singleton.Update);
}
singleton = new ScenarioWorker();
Client.updateEvent.Add(singleton.Update);
}
}
}
public class ScenarioEntry
{
public string scenarioName;
public ConfigNode scenarioNode;
}
}
| |
// 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 Microsoft.Azure.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ApiPolicyOperations operations.
/// </summary>
internal partial class ApiPolicyOperations : IServiceOperations<ApiManagementClient>, IApiPolicyOperations
{
/// <summary>
/// Initializes a new instance of the ApiPolicyOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ApiPolicyOperations(ApiManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the ApiManagementClient
/// </summary>
public ApiManagementClient Client { get; private set; }
/// <summary>
/// Get the policy configuration at the API level.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PolicyCollection,ApiPolicyListByApiHeaders>> ListByApiWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (apiId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "apiId");
}
if (apiId != null)
{
if (apiId.Length > 256)
{
throw new ValidationException(ValidationRules.MaxLength, "apiId", 256);
}
if (apiId.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "apiId", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(apiId, "^[^*#&+:<>?]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "apiId", "^[^*#&+:<>?]+$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("apiId", apiId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByApi", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/policies").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{apiId}", System.Uri.EscapeDataString(apiId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PolicyCollection,ApiPolicyListByApiHeaders>();
_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<PolicyCollection>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<ApiPolicyListByApiHeaders>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get the policy configuration at the API level.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PolicyContract,ApiPolicyGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (apiId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "apiId");
}
if (apiId != null)
{
if (apiId.Length > 256)
{
throw new ValidationException(ValidationRules.MaxLength, "apiId", 256);
}
if (apiId.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "apiId", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(apiId, "^[^*#&+:<>?]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "apiId", "^[^*#&+:<>?]+$");
}
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string policyId = "policy";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("apiId", apiId);
tracingParameters.Add("policyId", policyId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/policies/{policyId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{apiId}", System.Uri.EscapeDataString(apiId));
_url = _url.Replace("{policyId}", System.Uri.EscapeDataString(policyId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PolicyContract,ApiPolicyGetHeaders>();
_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<PolicyContract>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
try
{
_result.Headers = _httpResponse.GetHeadersAsJson().ToObject<ApiPolicyGetHeaders>(JsonSerializer.Create(Client.DeserializationSettings));
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates policy configuration for the API.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='parameters'>
/// The policy contents to apply.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the Api Policy to update. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PolicyContract>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, PolicyContract parameters, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (apiId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "apiId");
}
if (apiId != null)
{
if (apiId.Length > 256)
{
throw new ValidationException(ValidationRules.MaxLength, "apiId", 256);
}
if (apiId.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "apiId", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(apiId, "^[^*#&+:<>?]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "apiId", "^[^*#&+:<>?]+$");
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (ifMatch == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ifMatch");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string policyId = "policy";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("apiId", apiId);
tracingParameters.Add("policyId", policyId);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/policies/{policyId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{apiId}", System.Uri.EscapeDataString(apiId));
_url = _url.Replace("{policyId}", System.Uri.EscapeDataString(policyId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201 && (int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PolicyContract>();
_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 == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PolicyContract>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PolicyContract>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the policy configuration at the Api.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='apiId'>
/// API identifier. Must be unique in the current API Management service
/// instance.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the Api policy to update. A value of "*"
/// can be used for If-Match to unconditionally apply the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, string apiId, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serviceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serviceName");
}
if (serviceName != null)
{
if (serviceName.Length > 50)
{
throw new ValidationException(ValidationRules.MaxLength, "serviceName", 50);
}
if (serviceName.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "serviceName", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(serviceName, "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
{
throw new ValidationException(ValidationRules.Pattern, "serviceName", "^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$");
}
}
if (apiId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "apiId");
}
if (apiId != null)
{
if (apiId.Length > 256)
{
throw new ValidationException(ValidationRules.MaxLength, "apiId", 256);
}
if (apiId.Length < 1)
{
throw new ValidationException(ValidationRules.MinLength, "apiId", 1);
}
if (!System.Text.RegularExpressions.Regex.IsMatch(apiId, "^[^*#&+:<>?]+$"))
{
throw new ValidationException(ValidationRules.Pattern, "apiId", "^[^*#&+:<>?]+$");
}
}
if (ifMatch == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "ifMatch");
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string policyId = "policy";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("apiId", apiId);
tracingParameters.Add("policyId", policyId);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}/policies/{policyId}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serviceName}", System.Uri.EscapeDataString(serviceName));
_url = _url.Replace("{apiId}", System.Uri.EscapeDataString(apiId));
_url = _url.Replace("{policyId}", System.Uri.EscapeDataString(policyId));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
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 != 204)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System {
using System.Text;
using System.Threading;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Diagnostics.Contracts;
/*
Customized format patterns:
P.S. Format in the table below is the internal number format used to display the pattern.
Patterns Format Description Example
========= ========== ===================================== ========
"h" "0" hour (12-hour clock)w/o leading zero 3
"hh" "00" hour (12-hour clock)with leading zero 03
"hh*" "00" hour (12-hour clock)with leading zero 03
"H" "0" hour (24-hour clock)w/o leading zero 8
"HH" "00" hour (24-hour clock)with leading zero 08
"HH*" "00" hour (24-hour clock) 08
"m" "0" minute w/o leading zero
"mm" "00" minute with leading zero
"mm*" "00" minute with leading zero
"s" "0" second w/o leading zero
"ss" "00" second with leading zero
"ss*" "00" second with leading zero
"f" "0" second fraction (1 digit)
"ff" "00" second fraction (2 digit)
"fff" "000" second fraction (3 digit)
"ffff" "0000" second fraction (4 digit)
"fffff" "00000" second fraction (5 digit)
"ffffff" "000000" second fraction (6 digit)
"fffffff" "0000000" second fraction (7 digit)
"F" "0" second fraction (up to 1 digit)
"FF" "00" second fraction (up to 2 digit)
"FFF" "000" second fraction (up to 3 digit)
"FFFF" "0000" second fraction (up to 4 digit)
"FFFFF" "00000" second fraction (up to 5 digit)
"FFFFFF" "000000" second fraction (up to 6 digit)
"FFFFFFF" "0000000" second fraction (up to 7 digit)
"t" first character of AM/PM designator A
"tt" AM/PM designator AM
"tt*" AM/PM designator PM
"d" "0" day w/o leading zero 1
"dd" "00" day with leading zero 01
"ddd" short weekday name (abbreviation) Mon
"dddd" full weekday name Monday
"dddd*" full weekday name Monday
"M" "0" month w/o leading zero 2
"MM" "00" month with leading zero 02
"MMM" short month name (abbreviation) Feb
"MMMM" full month name Febuary
"MMMM*" full month name Febuary
"y" "0" two digit year (year % 100) w/o leading zero 0
"yy" "00" two digit year (year % 100) with leading zero 00
"yyy" "D3" year 2000
"yyyy" "D4" year 2000
"yyyyy" "D5" year 2000
...
"z" "+0;-0" timezone offset w/o leading zero -8
"zz" "+00;-00" timezone offset with leading zero -08
"zzz" "+00;-00" for hour offset, "00" for minute offset full timezone offset -07:30
"zzz*" "+00;-00" for hour offset, "00" for minute offset full timezone offset -08:00
"K" -Local "zzz", e.g. -08:00
-Utc "'Z'", representing UTC
-Unspecified ""
-DateTimeOffset "zzzzz" e.g -07:30:15
"g*" the current era name A.D.
":" time separator : -- DEPRECATED - Insert separator directly into pattern (eg: "H.mm.ss")
"/" date separator /-- DEPRECATED - Insert separator directly into pattern (eg: "M-dd-yyyy")
"'" quoted string 'ABC' will insert ABC into the formatted string.
'"' quoted string "ABC" will insert ABC into the formatted string.
"%" used to quote a single pattern characters E.g.The format character "%y" is to print two digit year.
"\" escaped character E.g. '\d' insert the character 'd' into the format string.
other characters insert the character into the format string.
Pre-defined format characters:
(U) to indicate Universal time is used.
(G) to indicate Gregorian calendar is used.
Format Description Real format Example
========= ================================= ====================== =======================
"d" short date culture-specific 10/31/1999
"D" long data culture-specific Sunday, October 31, 1999
"f" full date (long date + short time) culture-specific Sunday, October 31, 1999 2:00 AM
"F" full date (long date + long time) culture-specific Sunday, October 31, 1999 2:00:00 AM
"g" general date (short date + short time) culture-specific 10/31/1999 2:00 AM
"G" general date (short date + long time) culture-specific 10/31/1999 2:00:00 AM
"m"/"M" Month/Day date culture-specific October 31
(G) "o"/"O" Round Trip XML "yyyy-MM-ddTHH:mm:ss.fffffffK" 1999-10-31 02:00:00.0000000Z
(G) "r"/"R" RFC 1123 date, "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'" Sun, 31 Oct 1999 10:00:00 GMT
(G) "s" Sortable format, based on ISO 8601. "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00
('T' for local time)
"t" short time culture-specific 2:00 AM
"T" long time culture-specific 2:00:00 AM
(G) "u" Universal time with sortable format, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" 1999-10-31 10:00:00Z
based on ISO 8601.
(U) "U" Universal time with full culture-specific Sunday, October 31, 1999 10:00:00 AM
(long date + long time) format
"y"/"Y" Year/Month day culture-specific October, 1999
*/
//This class contains only static members and does not require the serializable attribute.
internal static
class DateTimeFormat {
internal const int MaxSecondsFractionDigits = 7;
internal static readonly TimeSpan NullOffset = TimeSpan.MinValue;
internal static char[] allStandardFormats =
{
'd', 'D', 'f', 'F', 'g', 'G',
'm', 'M', 'o', 'O', 'r', 'R',
's', 't', 'T', 'u', 'U', 'y', 'Y',
};
internal const String RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK";
internal const String RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz";
private const int DEFAULT_ALL_DATETIMES_SIZE = 132;
internal static String[] fixedNumberFormats = new String[] {
"0",
"00",
"000",
"0000",
"00000",
"000000",
"0000000",
};
////////////////////////////////////////////////////////////////////////////
//
// Format the positive integer value to a string and perfix with assigned
// length of leading zero.
//
// Parameters:
// value: The value to format
// len: The maximum length for leading zero.
// If the digits of the value is greater than len, no leading zero is added.
//
// Notes:
// The function can format to Int32.MaxValue.
//
////////////////////////////////////////////////////////////////////////////
internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) {
Contract.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
FormatDigits(outputBuffer, value, len, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
internal unsafe static void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) {
Contract.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
// Limit the use of this function to be two-digits, so that we have the same behavior
// as RTM bits.
if (!overrideLengthLimit && len > 2)
{
len = 2;
}
char* buffer = stackalloc char[16];
char* p = buffer + 16;
int n = value;
do {
*--p = (char)(n % 10 + '0');
n /= 10;
} while ((n != 0)&&(p > buffer));
int digits = (int) (buffer + 16 - p);
//If the repeat count is greater than 0, we're trying
//to emulate the "00" format, so we have to prepend
//a zero if the string only has one character.
while ((digits < len) && (p > buffer)) {
*--p='0';
digits++;
}
outputBuffer.Append(p, digits);
}
private static void HebrewFormatDigits(StringBuilder outputBuffer, int digits) {
outputBuffer.Append(HebrewNumber.ToString(digits));
}
internal static int ParseRepeatPattern(String format, int pos, char patternChar)
{
int len = format.Length;
int index = pos + 1;
while ((index < len) && (format[index] == patternChar))
{
index++;
}
return (index - pos);
}
private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi)
{
Contract.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6");
if (repeat == 3)
{
return (dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek));
}
// Call dtfi.GetDayName() here, instead of accessing DayNames property, because we don't
// want a clone of DayNames, which will hurt perf.
return (dtfi.GetDayName((DayOfWeek)dayOfWeek));
}
private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi)
{
Contract.Assert(month >=1 && month <= 12, "month >=1 && month <= 12");
if (repeatCount == 3)
{
return (dtfi.GetAbbreviatedMonthName(month));
}
// Call GetMonthName() here, instead of accessing MonthNames property, because we don't
// want a clone of MonthNames, which will hurt perf.
return (dtfi.GetMonthName(month));
}
//
// FormatHebrewMonthName
//
// Action: Return the Hebrew month name for the specified DateTime.
// Returns: The month name string for the specified DateTime.
// Arguments:
// time the time to format
// month The month is the value of HebrewCalendar.GetMonth(time).
// repeat Return abbreviated month name if repeat=3, or full month name if repeat=4
// dtfi The DateTimeFormatInfo which uses the Hebrew calendars as its calendar.
// Exceptions: None.
//
/* Note:
If DTFI is using Hebrew calendar, GetMonthName()/GetAbbreviatedMonthName() will return month names like this:
1 Hebrew 1st Month
2 Hebrew 2nd Month
.. ...
6 Hebrew 6th Month
7 Hebrew 6th Month II (used only in a leap year)
8 Hebrew 7th Month
9 Hebrew 8th Month
10 Hebrew 9th Month
11 Hebrew 10th Month
12 Hebrew 11th Month
13 Hebrew 12th Month
Therefore, if we are in a regular year, we have to increment the month name if moth is greater or eqaul to 7.
*/
private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi)
{
Contract.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4");
if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) {
// This month is in a leap year
return (dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3)));
}
// This is in a regular year.
if (month >= 7) {
month++;
}
if (repeatCount == 3) {
return (dtfi.GetAbbreviatedMonthName(month));
}
return (dtfi.GetMonthName(month));
}
//
// The pos should point to a quote character. This method will
// get the string encloed by the quote character.
//
internal static int ParseQuoteString(String format, int pos, StringBuilder result)
{
//
// NOTE : pos will be the index of the quote character in the 'format' string.
//
int formatLen = format.Length;
int beginPos = pos;
char quoteChar = format[pos++]; // Get the character used to quote the following string.
bool foundQuote = false;
while (pos < formatLen)
{
char ch = format[pos++];
if (ch == quoteChar)
{
foundQuote = true;
break;
}
else if (ch == '\\') {
// The following are used to support escaped character.
// Escaped character is also supported in the quoted string.
// Therefore, someone can use a format like "'minute:' mm\"" to display:
// minute: 45"
// because the second double quote is escaped.
if (pos < formatLen) {
result.Append(format[pos++]);
} else {
//
// This means that '\' is at the end of the formatting string.
//
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
} else {
result.Append(ch);
}
}
if (!foundQuote)
{
// Here we can't find the matching quote.
throw new FormatException(
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Format_BadQuote"), quoteChar));
}
//
// Return the character count including the begin/end quote characters and enclosed string.
//
return (pos - beginPos);
}
//
// Get the next character at the index of 'pos' in the 'format' string.
// Return value of -1 means 'pos' is already at the end of the 'format' string.
// Otherwise, return value is the int value of the next character.
//
internal static int ParseNextChar(String format, int pos)
{
if (pos >= format.Length - 1)
{
return (-1);
}
return ((int)format[pos+1]);
}
//
// IsUseGenitiveForm
//
// Actions: Check the format to see if we should use genitive month in the formatting.
// Starting at the position (index) in the (format) string, look back and look ahead to
// see if there is "d" or "dd". In the case like "d MMMM" or "MMMM dd", we can use
// genitive form. Genitive form is not used if there is more than two "d".
// Arguments:
// format The format string to be scanned.
// index Where we should start the scanning. This is generally where "M" starts.
// tokenLen The len of the current pattern character. This indicates how many "M" that we have.
// patternToMatch The pattern that we want to search. This generally uses "d"
//
private static bool IsUseGenitiveForm(String format, int index, int tokenLen, char patternToMatch) {
int i;
int repeat = 0;
//
// Look back to see if we can find "d" or "ddd"
//
// Find first "d".
for (i = index - 1; i >= 0 && format[i] != patternToMatch; i--) { /*Do nothing here */ };
if (i >= 0) {
// Find a "d", so look back to see how many "d" that we can find.
while (--i >= 0 && format[i] == patternToMatch) {
repeat++;
}
//
// repeat == 0 means that we have one (patternToMatch)
// repeat == 1 means that we have two (patternToMatch)
//
if (repeat <= 1) {
return (true);
}
// Note that we can't just stop here. We may find "ddd" while looking back, and we have to look
// ahead to see if there is "d" or "dd".
}
//
// If we can't find "d" or "dd" by looking back, try look ahead.
//
// Find first "d"
for (i = index + tokenLen; i < format.Length && format[i] != patternToMatch; i++) { /* Do nothing here */ };
if (i < format.Length) {
repeat = 0;
// Find a "d", so contine the walk to see how may "d" that we can find.
while (++i < format.Length && format[i] == patternToMatch) {
repeat++;
}
//
// repeat == 0 means that we have one (patternToMatch)
// repeat == 1 means that we have two (patternToMatch)
//
if (repeat <= 1) {
return (true);
}
}
return (false);
}
//
// FormatCustomized
//
// Actions: Format the DateTime instance using the specified format.
//
private static String FormatCustomized(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset) {
Calendar cal = dtfi.Calendar;
StringBuilder result = StringBuilderCache.Acquire();
// This is a flag to indicate if we are format the dates using Hebrew calendar.
bool isHebrewCalendar = (cal.ID == Calendar.CAL_HEBREW);
// This is a flag to indicate if we are formating hour/minute/second only.
bool bTimeOnly = true;
int i = 0;
int tokenLen, hour12;
while (i < format.Length) {
char ch = format[i];
int nextChar;
switch (ch) {
case 'g':
tokenLen = ParseRepeatPattern(format, i, ch);
result.Append(dtfi.GetEraName(cal.GetEra(dateTime)));
break;
case 'h':
tokenLen = ParseRepeatPattern(format, i, ch);
hour12 = dateTime.Hour % 12;
if (hour12 == 0)
{
hour12 = 12;
}
FormatDigits(result, hour12, tokenLen);
break;
case 'H':
tokenLen = ParseRepeatPattern(format, i, ch);
FormatDigits(result, dateTime.Hour, tokenLen);
break;
case 'm':
tokenLen = ParseRepeatPattern(format, i, ch);
FormatDigits(result, dateTime.Minute, tokenLen);
break;
case 's':
tokenLen = ParseRepeatPattern(format, i, ch);
FormatDigits(result, dateTime.Second, tokenLen);
break;
case 'f':
case 'F':
tokenLen = ParseRepeatPattern(format, i, ch);
if (tokenLen <= MaxSecondsFractionDigits) {
long fraction = (dateTime.Ticks % Calendar.TicksPerSecond);
fraction = fraction / (long)Math.Pow(10, 7 - tokenLen);
if (ch == 'f') {
result.Append(((int)fraction).ToString(fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
}
else {
int effectiveDigits = tokenLen;
while (effectiveDigits > 0) {
if (fraction % 10 == 0) {
fraction = fraction / 10;
effectiveDigits--;
}
else {
break;
}
}
if (effectiveDigits > 0) {
result.Append(((int)fraction).ToString(fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
else {
// No fraction to emit, so see if we should remove decimal also.
if (result.Length > 0 && result[result.Length - 1] == '.') {
result.Remove(result.Length - 1, 1);
}
}
}
} else {
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
break;
case 't':
tokenLen = ParseRepeatPattern(format, i, ch);
if (tokenLen == 1)
{
if (dateTime.Hour < 12)
{
if (dtfi.AMDesignator.Length >= 1)
{
result.Append(dtfi.AMDesignator[0]);
}
}
else
{
if (dtfi.PMDesignator.Length >= 1)
{
result.Append(dtfi.PMDesignator[0]);
}
}
}
else
{
result.Append((dateTime.Hour < 12 ? dtfi.AMDesignator : dtfi.PMDesignator));
}
break;
case 'd':
//
// tokenLen == 1 : Day of month as digits with no leading zero.
// tokenLen == 2 : Day of month as digits with leading zero for single-digit months.
// tokenLen == 3 : Day of week as a three-leter abbreviation.
// tokenLen >= 4 : Day of week as its full name.
//
tokenLen = ParseRepeatPattern(format, i, ch);
if (tokenLen <= 2)
{
int day = cal.GetDayOfMonth(dateTime);
if (isHebrewCalendar) {
// For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values.
HebrewFormatDigits(result, day);
} else {
FormatDigits(result, day, tokenLen);
}
}
else
{
int dayOfWeek = (int)cal.GetDayOfWeek(dateTime);
result.Append(FormatDayOfWeek(dayOfWeek, tokenLen, dtfi));
}
bTimeOnly = false;
break;
case 'M':
//
// tokenLen == 1 : Month as digits with no leading zero.
// tokenLen == 2 : Month as digits with leading zero for single-digit months.
// tokenLen == 3 : Month as a three-letter abbreviation.
// tokenLen >= 4 : Month as its full name.
//
tokenLen = ParseRepeatPattern(format, i, ch);
int month = cal.GetMonth(dateTime);
if (tokenLen <= 2)
{
if (isHebrewCalendar) {
// For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values.
HebrewFormatDigits(result, month);
} else {
FormatDigits(result, month, tokenLen);
}
}
else {
if (isHebrewCalendar) {
result.Append(FormatHebrewMonthName(dateTime, month, tokenLen, dtfi));
} else {
if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0 && tokenLen >= 4) {
result.Append(
dtfi.internalGetMonthName(
month,
IsUseGenitiveForm(format, i, tokenLen, 'd')? MonthNameStyles.Genitive : MonthNameStyles.Regular,
false));
} else {
result.Append(FormatMonth(month, tokenLen, dtfi));
}
}
}
bTimeOnly = false;
break;
case 'y':
// Notes about OS behavior:
// y: Always print (year % 100). No leading zero.
// yy: Always print (year % 100) with leading zero.
// yyy/yyyy/yyyyy/... : Print year value. No leading zero.
int year = cal.GetYear(dateTime);
tokenLen = ParseRepeatPattern(format, i, ch);
if (dtfi.HasForceTwoDigitYears) {
FormatDigits(result, year, tokenLen <= 2 ? tokenLen : 2);
}
else if (cal.ID == Calendar.CAL_HEBREW) {
HebrewFormatDigits(result, year);
}
else {
if (tokenLen <= 2) {
FormatDigits(result, year % 100, tokenLen);
}
else {
String fmtPattern = "D" + tokenLen;
result.Append(year.ToString(fmtPattern, CultureInfo.InvariantCulture));
}
}
bTimeOnly = false;
break;
case 'z':
tokenLen = ParseRepeatPattern(format, i, ch);
FormatCustomizedTimeZone(dateTime, offset, format, tokenLen, bTimeOnly, result);
break;
case 'K':
tokenLen = 1;
FormatCustomizedRoundripTimeZone(dateTime, offset, result);
break;
case ':':
result.Append(dtfi.TimeSeparator);
tokenLen = 1;
break;
case '/':
result.Append(dtfi.DateSeparator);
tokenLen = 1;
break;
case '\'':
case '\"':
StringBuilder enquotedString = new StringBuilder();
tokenLen = ParseQuoteString(format, i, enquotedString);
result.Append(enquotedString);
break;
case '%':
// Optional format character.
// For example, format string "%d" will print day of month
// without leading zero. Most of the cases, "%" can be ignored.
nextChar = ParseNextChar(format, i);
// nextChar will be -1 if we already reach the end of the format string.
// Besides, we will not allow "%%" appear in the pattern.
if (nextChar >= 0 && nextChar != (int)'%') {
result.Append(FormatCustomized(dateTime, ((char)nextChar).ToString(), dtfi, offset));
tokenLen = 2;
}
else
{
//
// This means that '%' is at the end of the format string or
// "%%" appears in the format string.
//
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
break;
case '\\':
// Escaped character. Can be used to insert character into the format string.
// For exmple, "\d" will insert the character 'd' into the string.
//
// NOTENOTE : we can remove this format character if we enforce the enforced quote
// character rule.
// That is, we ask everyone to use single quote or double quote to insert characters,
// then we can remove this character.
//
nextChar = ParseNextChar(format, i);
if (nextChar >= 0)
{
result.Append(((char)nextChar));
tokenLen = 2;
}
else
{
//
// This means that '\' is at the end of the formatting string.
//
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
break;
default:
// NOTENOTE : we can remove this rule if we enforce the enforced quote
// character rule.
// That is, if we ask everyone to use single quote or double quote to insert characters,
// then we can remove this default block.
result.Append(ch);
tokenLen = 1;
break;
}
i += tokenLen;
}
return StringBuilderCache.GetStringAndRelease(result);
}
// output the 'z' famliy of formats, which output a the offset from UTC, e.g. "-07:30"
private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, String format, Int32 tokenLen, Boolean timeOnly, StringBuilder result) {
// See if the instance already has an offset
Boolean dateTimeFormat = (offset == NullOffset);
if (dateTimeFormat) {
// No offset. The instance is a DateTime and the output should be the local time zone
if (timeOnly && dateTime.Ticks < Calendar.TicksPerDay) {
// For time only format and a time only input, the time offset on 0001/01/01 is less
// accurate than the system's current offset because of daylight saving time.
offset = TimeZoneInfo.GetLocalUtcOffset(DateTime.Now, TimeZoneInfoOptions.NoThrowOnInvalidTime);
} else if (dateTime.Kind == DateTimeKind.Utc) {
#if FEATURE_CORECLR
offset = TimeSpan.Zero;
#else // FEATURE_CORECLR
// This code path points to a bug in user code. It would make sense to return a 0 offset in this case.
// However, because it was only possible to detect this in Whidbey, there is user code that takes a
// dependency on being serialize a UTC DateTime using the 'z' format, and it will work almost all the
// time if it is offset by an incorrect conversion to local time when parsed. Therefore, we need to
// explicitly emit the local time offset, which we can do by removing the UTC flag.
InvalidFormatForUtc(format, dateTime);
dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Local);
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
#endif // FEATURE_CORECLR
} else {
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
}
if (offset >= TimeSpan.Zero) {
result.Append('+');
}
else {
result.Append('-');
// get a positive offset, so that you don't need a separate code path for the negative numbers.
offset = offset.Negate();
}
if (tokenLen <= 1) {
// 'z' format e.g "-7"
result.AppendFormat(CultureInfo.InvariantCulture, "{0:0}", offset.Hours);
}
else {
// 'zz' or longer format e.g "-07"
result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}", offset.Hours);
if (tokenLen >= 3) {
// 'zzz*' or longer format e.g "-07:30"
result.AppendFormat(CultureInfo.InvariantCulture, ":{0:00}", offset.Minutes);
}
}
}
// output the 'K' format, which is for round-tripping the data
private static void FormatCustomizedRoundripTimeZone(DateTime dateTime, TimeSpan offset, StringBuilder result) {
// The objective of this format is to round trip the data in the type
// For DateTime it should round-trip the Kind value and preserve the time zone.
// DateTimeOffset instance, it should do so by using the internal time zone.
if (offset == NullOffset) {
// source is a date time, so behavior depends on the kind.
switch (dateTime.Kind) {
case DateTimeKind.Local:
// This should output the local offset, e.g. "-07:30"
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
// fall through to shared time zone output code
break;
case DateTimeKind.Utc:
// The 'Z' constant is a marker for a UTC date
result.Append("Z");
return;
default:
// If the kind is unspecified, we output nothing here
return;
}
}
if (offset >= TimeSpan.Zero) {
result.Append('+');
}
else {
result.Append('-');
// get a positive offset, so that you don't need a separate code path for the negative numbers.
offset = offset.Negate();
}
result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}:{1:00}", offset.Hours, offset.Minutes);
}
internal static String GetRealFormat(String format, DateTimeFormatInfo dtfi)
{
String realFormat = null;
switch (format[0])
{
case 'd': // Short Date
realFormat = dtfi.ShortDatePattern;
break;
case 'D': // Long Date
realFormat = dtfi.LongDatePattern;
break;
case 'f': // Full (long date + short time)
realFormat = dtfi.LongDatePattern + " " + dtfi.ShortTimePattern;
break;
case 'F': // Full (long date + long time)
realFormat = dtfi.FullDateTimePattern;
break;
case 'g': // General (short date + short time)
realFormat = dtfi.GeneralShortTimePattern;
break;
case 'G': // General (short date + long time)
realFormat = dtfi.GeneralLongTimePattern;
break;
case 'm':
case 'M': // Month/Day Date
realFormat = dtfi.MonthDayPattern;
break;
case 'o':
case 'O':
realFormat = RoundtripFormat;
break;
case 'r':
case 'R': // RFC 1123 Standard
realFormat = dtfi.RFC1123Pattern;
break;
case 's': // Sortable without Time Zone Info
realFormat = dtfi.SortableDateTimePattern;
break;
case 't': // Short Time
realFormat = dtfi.ShortTimePattern;
break;
case 'T': // Long Time
realFormat = dtfi.LongTimePattern;
break;
case 'u': // Universal with Sortable format
realFormat = dtfi.UniversalSortableDateTimePattern;
break;
case 'U': // Universal with Full (long date + long time) format
realFormat = dtfi.FullDateTimePattern;
break;
case 'y':
case 'Y': // Year/Month Date
realFormat = dtfi.YearMonthPattern;
break;
default:
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
return (realFormat);
}
// Expand a pre-defined format string (like "D" for long date) to the real format that
// we are going to use in the date time parsing.
// This method also convert the dateTime if necessary (e.g. when the format is in Universal time),
// and change dtfi if necessary (e.g. when the format should use invariant culture).
//
private static String ExpandPredefinedFormat(String format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi, ref TimeSpan offset) {
switch (format[0]) {
case 'o':
case 'O': // Round trip format
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'r':
case 'R': // RFC 1123 Standard
if (offset != NullOffset) {
// Convert to UTC invariants mean this will be in range
dateTime = dateTime - offset;
}
else if (dateTime.Kind == DateTimeKind.Local) {
InvalidFormatForLocal(format, dateTime);
}
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 's': // Sortable without Time Zone Info
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'u': // Universal time in sortable format.
if (offset != NullOffset) {
// Convert to UTC invariants mean this will be in range
dateTime = dateTime - offset;
}
else if (dateTime.Kind == DateTimeKind.Local) {
InvalidFormatForLocal(format, dateTime);
}
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'U': // Universal time in culture dependent format.
if (offset != NullOffset) {
// This format is not supported by DateTimeOffset
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
// Universal time is always in Greogrian calendar.
//
// Change the Calendar to be Gregorian Calendar.
//
dtfi = (DateTimeFormatInfo)dtfi.Clone();
if (dtfi.Calendar.GetType() != typeof(GregorianCalendar)) {
dtfi.Calendar = GregorianCalendar.GetDefaultInstance();
}
dateTime = dateTime.ToUniversalTime();
break;
}
format = GetRealFormat(format, dtfi);
return (format);
}
internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi) {
return Format(dateTime, format, dtfi, NullOffset);
}
internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset)
{
Contract.Requires(dtfi != null);
if (format==null || format.Length==0) {
Boolean timeOnlySpecialCase = false;
if (dateTime.Ticks < Calendar.TicksPerDay) {
// If the time is less than 1 day, consider it as time of day.
// Just print out the short time format.
//
// This is a workaround for VB, since they use ticks less then one day to be
// time of day. In cultures which use calendar other than Gregorian calendar, these
// alternative calendar may not support ticks less than a day.
// For example, Japanese calendar only supports date after 1868/9/8.
// This will pose a problem when people in VB get the time of day, and use it
// to call ToString(), which will use the general format (short date + long time).
// Since Japanese calendar does not support Gregorian year 0001, an exception will be
// thrown when we try to get the Japanese year for Gregorian year 0001.
// Therefore, the workaround allows them to call ToString() for time of day from a DateTime by
// formatting as ISO 8601 format.
switch (dtfi.Calendar.ID) {
case Calendar.CAL_JAPAN:
case Calendar.CAL_TAIWAN:
case Calendar.CAL_HIJRI:
case Calendar.CAL_HEBREW:
case Calendar.CAL_JULIAN:
case Calendar.CAL_UMALQURA:
timeOnlySpecialCase = true;
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
}
}
if (offset == NullOffset) {
// Default DateTime.ToString case.
if (timeOnlySpecialCase) {
format = "s";
}
else {
format = "G";
}
}
else {
// Default DateTimeOffset.ToString case.
if (timeOnlySpecialCase) {
format = RoundtripDateTimeUnfixed;
}
else {
format = dtfi.DateTimeOffsetPattern;
}
}
}
if (format.Length == 1) {
format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, ref offset);
}
return (FormatCustomized(dateTime, format, dtfi, offset));
}
internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi)
{
Contract.Requires(dtfi != null);
String [] allFormats = null;
String [] results = null;
switch (format)
{
case 'd':
case 'D':
case 'f':
case 'F':
case 'g':
case 'G':
case 'm':
case 'M':
case 't':
case 'T':
case 'y':
case 'Y':
allFormats = dtfi.GetAllDateTimePatterns(format);
results = new String[allFormats.Length];
for (int i = 0; i < allFormats.Length; i++)
{
results[i] = Format(dateTime, allFormats[i], dtfi);
}
break;
case 'U':
DateTime universalTime = dateTime.ToUniversalTime();
allFormats = dtfi.GetAllDateTimePatterns(format);
results = new String[allFormats.Length];
for (int i = 0; i < allFormats.Length; i++)
{
results[i] = Format(universalTime, allFormats[i], dtfi);
}
break;
//
// The following ones are special cases because these patterns are read-only in
// DateTimeFormatInfo.
//
case 'r':
case 'R':
case 'o':
case 'O':
case 's':
case 'u':
results = new String[] {Format(dateTime, new String(new char[] {format}), dtfi)};
break;
default:
throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
}
return (results);
}
internal static String[] GetAllDateTimes(DateTime dateTime, DateTimeFormatInfo dtfi)
{
List<String> results = new List<String>(DEFAULT_ALL_DATETIMES_SIZE);
for (int i = 0; i < allStandardFormats.Length; i++)
{
String[] strings = GetAllDateTimes(dateTime, allStandardFormats[i], dtfi);
for (int j = 0; j < strings.Length; j++)
{
results.Add(strings[j]);
}
}
String[] value = new String[results.Count];
results.CopyTo(0, value, 0, results.Count);
return (value);
}
// This is a placeholder for an MDA to detect when the user is using a
// local DateTime with a format that will be interpreted as UTC.
internal static void InvalidFormatForLocal(String format, DateTime dateTime) {
}
// This is an MDA for cases when the user is using a local format with
// a Utc DateTime.
[System.Security.SecuritySafeCritical] // auto-generated
internal static void InvalidFormatForUtc(String format, DateTime dateTime) {
#if MDA_SUPPORTED
Mda.DateTimeInvalidLocalFormat();
#endif
}
}
}
| |
using System.IO;
using System.Resources;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Signum.Utilities;
public static class StreamExtensions
{
public static byte[] ReadAllBytes(this Stream str)
{
using (MemoryStream ms = new MemoryStream())
{
str.CopyTo(ms);
return ms.ToArray();
}
}
public static async Task<byte[]> ReadAllBytesAsync(this Stream str)
{
using (MemoryStream ms = new MemoryStream())
{
await str.CopyToAsync(ms);
return ms.ToArray();
}
}
public static void WriteAllBytes(this Stream str, byte[] data)
{
str.Write(data, 0, data.Length);
}
public static string ReadResourceStream(this Assembly assembly, string name, Encoding? encoding = null)
{
using (Stream? stream = assembly.GetManifestResourceStream(name))
{
if (stream == null)
throw new MissingManifestResourceException("{0} not found on {1}".FormatWith(name, assembly));
using (StreamReader reader = encoding == null ? new StreamReader(stream) : new StreamReader(stream, encoding))
return reader.ReadToEnd();
}
}
static int BytesToRead = sizeof(Int64);
public static bool StreamsAreEqual(Stream first, Stream second)
{
int iterations = (int)Math.Ceiling((double)first.Length / BytesToRead);
byte[] one = new byte[BytesToRead];
byte[] two = new byte[BytesToRead];
for (int i = 0; i < iterations; i++)
{
first.Read(one, 0, BytesToRead);
second.Read(two, 0, BytesToRead);
if (BitConverter.ToInt64(one, 0) != BitConverter.ToInt64(two, 0))
return false;
}
return true;
}
public static bool FilesAreEqual(FileInfo first, FileInfo second)
{
if (first.Length != second.Length)
return false;
using (FileStream s1 = first.OpenRead())
using (FileStream s2 = second.OpenRead())
{
return StreamsAreEqual(s1, s2);
}
}
[DebuggerStepThrough]
public static R Using<T, R>(this T disposable, Func<T, R> function)
where T : IDisposable?
{
//using (disposable)
// return function(disposable);
try
{
return function(disposable);
}
catch (Exception e)
{
if (disposable is IDisposableException de)
de.OnException(e);
throw;
}
finally
{
if (disposable != null)
disposable.Dispose();
}
}
[DebuggerStepThrough]
public static void EndUsing<T>(this T disposable, Action<T> action)
where T : IDisposable?
{
try
{
action(disposable);
}
catch (Exception e)
{
if (disposable is IDisposableException de)
de.OnException(e);
throw;
}
finally
{
if (disposable != null)
disposable.Dispose();
}
}
}
public interface IDisposableException : IDisposable
{
void OnException(Exception ex);
}
public class ProgressStream : Stream
{
readonly Stream InnerStream;
public event EventHandler? ProgressChanged;
public ProgressStream(Stream innerStream)
{
this.InnerStream = innerStream;
}
public double GetProgress()
{
return ((double)Position) / Length;
}
public override bool CanRead
{
get { return InnerStream.CanRead; }
}
public override bool CanSeek
{
get { return InnerStream.CanSeek; }
}
public override bool CanWrite
{
get { return InnerStream.CanWrite; }
}
public override void Flush()
{
InnerStream.Flush();
}
public override long Length
{
get { return InnerStream.Length; }
}
public override long Position
{
get { return InnerStream.Position; }
set { InnerStream.Position = value; }
}
public override int Read(byte[] buffer, int offset, int count)
{
int result = InnerStream.Read(buffer, offset, count);
ProgressChanged?.Invoke(this, EventArgs.Empty);
return result;
}
public override long Seek(long offset, SeekOrigin origin)
{
return InnerStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
InnerStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
InnerStream.Write(buffer, offset, count);
ProgressChanged?.Invoke(this, EventArgs.Empty);
}
public override void Close()
{
InnerStream.Close();
}
}
| |
//
// WidgetView.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
// Hywel Thomas <hywel.w.thomas@gmail.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 MonoMac.AppKit;
using MonoMac.CoreGraphics;
namespace Xwt.Mac
{
/// <summary>
/// Handles Events generated by NSView and TrackingArea
/// and dispatches these using context and eventSink
/// </summary>
class WidgetView: NSView, IViewObject
{
IWidgetEventSink eventSink;
protected ApplicationContext context;
NSTrackingArea trackingArea; // Captures Mouse Entered, Exited, and Moved events
public WidgetView (IWidgetEventSink eventSink, ApplicationContext context)
{
this.context = context;
this.eventSink = eventSink;
}
public ViewBackend Backend { get; set; }
public NSView View {
get { return this; }
}
public override bool IsFlipped {
get {
return true;
}
}
public override bool AcceptsFirstResponder ()
{
return Backend.CanGetFocus;
}
public override void DrawRect (System.Drawing.RectangleF dirtyRect)
{
CGContext ctx = NSGraphicsContext.CurrentContext.GraphicsPort;
//fill BackgroundColor
ctx.SetFillColor (Backend.Frontend.BackgroundColor.ToCGColor ());
ctx.FillRect (Bounds);
}
public override void UpdateTrackingAreas ()
{
if (trackingArea != null) {
RemoveTrackingArea (trackingArea);
trackingArea.Dispose ();
}
System.Drawing.RectangleF viewBounds = this.Bounds;
var options = NSTrackingAreaOptions.MouseMoved | NSTrackingAreaOptions.ActiveInKeyWindow | NSTrackingAreaOptions.MouseEnteredAndExited;
trackingArea = new NSTrackingArea (viewBounds, options, this, null);
AddTrackingArea (trackingArea);
}
public override void RightMouseDown (NSEvent theEvent)
{
var p = ConvertPointFromView (theEvent.LocationInWindow, null);
ButtonEventArgs args = new ButtonEventArgs ();
args.X = p.X;
args.Y = p.Y;
args.Button = PointerButton.Right;
context.InvokeUserCode (delegate {
eventSink.OnButtonPressed (args);
});
}
public override void RightMouseUp (NSEvent theEvent)
{
var p = ConvertPointFromView (theEvent.LocationInWindow, null);
ButtonEventArgs args = new ButtonEventArgs ();
args.X = p.X;
args.Y = p.Y;
args.Button = PointerButton.Right;
context.InvokeUserCode (delegate {
eventSink.OnButtonReleased (args);
});
}
public override void MouseDown (NSEvent theEvent)
{
var p = ConvertPointFromView (theEvent.LocationInWindow, null);
ButtonEventArgs args = new ButtonEventArgs ();
args.X = p.X;
args.Y = p.Y;
args.Button = PointerButton.Left;
context.InvokeUserCode (delegate {
eventSink.OnButtonPressed (args);
});
}
public override void MouseUp (NSEvent theEvent)
{
var p = ConvertPointFromView (theEvent.LocationInWindow, null);
ButtonEventArgs args = new ButtonEventArgs ();
args.X = p.X;
args.Y = p.Y;
args.Button = (PointerButton) theEvent.ButtonNumber + 1;
context.InvokeUserCode (delegate {
eventSink.OnButtonReleased (args);
});
}
public override void MouseEntered (NSEvent theEvent)
{
context.InvokeUserCode (delegate {
eventSink.OnMouseEntered ();
});
}
public override void MouseExited (NSEvent theEvent)
{
context.InvokeUserCode (delegate {
eventSink.OnMouseExited ();
});
}
public override void MouseMoved (NSEvent theEvent)
{
var p = ConvertPointFromView (theEvent.LocationInWindow, null);
MouseMovedEventArgs args = new MouseMovedEventArgs ((long) TimeSpan.FromSeconds (theEvent.Timestamp).TotalMilliseconds, p.X, p.Y);
context.InvokeUserCode (delegate {
eventSink.OnMouseMoved (args);
});
}
public override void MouseDragged (NSEvent theEvent)
{
var p = ConvertPointFromView (theEvent.LocationInWindow, null);
MouseMovedEventArgs args = new MouseMovedEventArgs ((long) TimeSpan.FromSeconds (theEvent.Timestamp).TotalMilliseconds, p.X, p.Y);
context.InvokeUserCode (delegate {
eventSink.OnMouseMoved (args);
});
}
public override void KeyDown (NSEvent theEvent)
{
var keyArgs = theEvent.ToXwtKeyEventArgs ();
context.InvokeUserCode (delegate {
eventSink.OnKeyPressed (keyArgs);
});
if (keyArgs.Handled)
return;
var textArgs = new PreviewTextInputEventArgs (theEvent.Characters);
if (!String.IsNullOrEmpty(theEvent.Characters))
context.InvokeUserCode (delegate {
eventSink.OnPreviewTextInput (textArgs);
});
if (textArgs.Handled)
return;
base.KeyDown (theEvent);
}
public override void KeyUp (NSEvent theEvent)
{
var keyArgs = theEvent.ToXwtKeyEventArgs ();
context.InvokeUserCode (delegate {
eventSink.OnKeyReleased (keyArgs);
});
if (!keyArgs.Handled)
base.KeyUp (theEvent);
}
public override void SetFrameSize (System.Drawing.SizeF newSize)
{
bool changed = !newSize.Equals (Frame.Size);
base.SetFrameSize (newSize);
if (changed) {
context.InvokeUserCode (delegate {
eventSink.OnBoundsChanged ();
});
}
}
public override void ResetCursorRects ()
{
base.ResetCursorRects ();
if (Backend.Cursor != null)
AddCursorRect (Bounds, Backend.Cursor);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Database.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace TQVaultAE.Data
{
using Microsoft.Extensions.Logging;
using System;
using System.Globalization;
using System.IO;
using System.Text;
using TQVaultAE.Config;
using TQVaultAE.Domain.Contracts.Providers;
using TQVaultAE.Domain.Contracts.Services;
using TQVaultAE.Domain.Entities;
using TQVaultAE.Domain.Helpers;
using TQVaultAE.Logs;
/// <summary>
/// Reads a Titan Quest database file.
/// </summary>
public class Database : IDatabase
{
private readonly ILogger Log = null;
#region Database Fields
/// <summary>
/// Dictionary of all database info records
/// </summary>
private LazyConcurrentDictionary<string, Info> infoDB = new LazyConcurrentDictionary<string, Info>();
/// <summary>
/// Dictionary of all text database entries
/// </summary>
private LazyConcurrentDictionary<string, string> textDB = new LazyConcurrentDictionary<string, string>();
/// <summary>
/// Dictionary of all associated arc files in the database.
/// </summary>
private LazyConcurrentDictionary<string, ArcFile> arcFiles = new LazyConcurrentDictionary<string, ArcFile>();
/// <summary>
/// Game language to support setting language in UI
/// </summary>
private string gameLanguage;
private readonly IArcFileProvider arcProv;
private readonly IArzFileProvider arzProv;
private readonly IItemAttributeProvider ItemAttributeProvider;
private readonly IGamePathService GamePathResolver;
private readonly ITQDataService TQData;
#endregion Database Fields
/// <summary>
/// Initializes a new instance of the Database class.
/// </summary>
public Database(
ILogger<Database> log
, IArcFileProvider arcFileProvider
, IArzFileProvider arzFileProvider
, IItemAttributeProvider itemAttributeProvider
, IGamePathService gamePathResolver
, ITQDataService tQData
)
{
this.Log = log;
this.AutoDetectLanguage = Config.Settings.Default.AutoDetectLanguage;
this.TQLanguage = Config.Settings.Default.TQLanguage;
this.arcProv = arcFileProvider;
this.arzProv = arzFileProvider;
this.ItemAttributeProvider = itemAttributeProvider;
this.GamePathResolver = gamePathResolver;
this.TQData = tQData;
this.LoadDBFile();
}
#region Database Properties
/// <summary>
/// Gets or sets a value indicating whether the game language is being auto detected.
/// </summary>
public bool AutoDetectLanguage { get; set; }
/// <summary>
/// Gets or sets the game language from the config file.
/// </summary>
public string TQLanguage { get; set; }
/// <summary>
/// Gets the instance of the Titan Quest Database ArzFile.
/// </summary>
public ArzFile ArzFile { get; private set; }
/// <summary>
/// Gets the instance of the Immortal Throne Database ArzFile.
/// </summary>
public ArzFile ArzFileIT { get; private set; }
/// <summary>
/// Gets the instance of a custom map Database ArzFile.
/// </summary>
public ArzFile ArzFileMod { get; private set; }
/// <summary>
/// Gets the game language setting as a an English DisplayName.
/// </summary>
/// <remarks>Changed to property by VillageIdiot to support changing of Language in UI</remarks>
public string GameLanguage
{
get
{
// Added by VillageIdiot
// Check if the user configured the language
if (this.gameLanguage == null)
{
if (!this.AutoDetectLanguage)
this.gameLanguage = this.TQLanguage;
}
// Try to read the language from the settings file
if (string.IsNullOrEmpty(this.gameLanguage))
{
try
{
string optionsFile = GamePathResolver.TQSettingsFile;
if (File.Exists(optionsFile))
{
using (StreamReader reader = new StreamReader(optionsFile))
{
// scan the file for the language line
string line;
char delims = '=';
while ((line = reader.ReadLine()) != null)
{
// Split the line on the = sign
string[] fields = line.Split(delims);
if (fields.Length < 2)
continue;
string key = fields[0].Trim();
string val = fields[1].Trim();
if (key.ToUpperInvariant().Equals("LANGUAGE"))
{
this.gameLanguage = val.ToUpperInvariant();
return this.gameLanguage;
}
}
return null;
}
}
return null;
}
catch (IOException exception)
{
Log.ErrorException(exception);
return null;
}
}
// Added by VillageIdiot
// We have something so we need to return it
// This was added to support setting the language in the config file
return this.gameLanguage;
}
}
#endregion Database Properties
#region Database Public Methods
#region Database Public Static Methods
/// <summary>
/// Used to Extract an ARC file into the destination directory.
/// The ARC file will not be added to the cache.
/// </summary>
/// <remarks>Added by VillageIdiot</remarks>
/// <param name="arcFileName">Name of the arc file</param>
/// <param name="destination">Destination path for extracted data</param>
/// <returns>Returns true on success otherwise false</returns>
public bool ExtractArcFile(string arcFileName, string destination)
{
bool result = false;
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Database.ExtractARCFile('{0}', '{1}')", arcFileName, destination);
try
{
ArcFile arcFile = new ArcFile(arcFileName);
// Extract the files
result = arcProv.ExtractArcFile(arcFile, destination);
}
catch (IOException exception)
{
Log.LogError(exception, "Exception occurred");
result = false;
}
if (TQDebug.DatabaseDebugLevel > 1)
Log.LogDebug("Extraction Result = {0}", result);
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Exiting Database.ReadARCFile()");
return result;
}
#endregion Database Public Static Methods
/// <summary>
/// Gets the Infor for a specific item id.
/// </summary>
/// <param name="itemId">Item ID which we are looking up. Will be normalized internally.</param>
/// <returns>Returns Infor for item ID and NULL if not found.</returns>
public Info GetInfo(string itemId)
{
if (string.IsNullOrEmpty(itemId))
return null;
itemId = TQData.NormalizeRecordPath(itemId);
return this.infoDB.GetOrAddAtomic(itemId, k =>
{
DBRecordCollection record = null;
// Add support for searching a custom map database
if (this.ArzFileMod != null)
record = arzProv.GetItem(this.ArzFileMod, k);
// Try the expansion pack database first.
if (record == null && this.ArzFileIT != null)
record = arzProv.GetItem(this.ArzFileIT, k);
// Try looking in TQ database now
if (record == null || this.ArzFileIT == null)
record = arzProv.GetItem(this.ArzFile, k);
if (record == null)
return null;
return new Info(record);
});
}
/// <summary>
/// Uses the text database to convert the tag to a name in the localized language.
/// The tag is normalized to upper case internally.
/// </summary>
/// <param name="tagId">Tag to be looked up in the text database normalized to upper case.</param>
/// <returns>Returns localized string, empty string if it cannot find a string or "?ErrorName?" in case of uncaught exception.</returns>
public string GetFriendlyName(string tagId)
=> this.textDB.TryGetValue(tagId.ToUpperInvariant(), out var text) ? text.Value : string.Empty;
/// <summary>
/// Gets the formatted string for the variable attribute.
/// </summary>
/// <param name="variable">variable for which we are making a nice string.</param>
/// <returns>Formatted string in the format of: Attribute: value</returns>
public string VariableToStringNice(Variable variable)
=> $"{this.GetItemAttributeFriendlyText(variable.Name)}: {variable.ToStringValue()}";
/// <summary>
/// Converts the item attribute to a name in the localized language
/// </summary>
/// <param name="itemAttribute">Item attribure to be looked up.</param>
/// <param name="addVariable">Flag for whether the variable is added to the text string.</param>
/// <returns>Returns localized item attribute</returns>
public string GetItemAttributeFriendlyText(string itemAttribute, bool addVariable = true)
{
ItemAttributesData data = ItemAttributeProvider.GetAttributeData(itemAttribute);
if (data == null)
{
this.Log.LogDebug($"Attribute unknown : {itemAttribute}");
return string.Concat("?", itemAttribute, "?");
}
string attributeTextTag = ItemAttributeProvider.GetAttributeTextTag(data);
if (string.IsNullOrEmpty(attributeTextTag))
{
this.Log.LogDebug($"Attribute unknown : {itemAttribute}");
return string.Concat("?", itemAttribute, "?");
}
string textFromTag = this.GetFriendlyName(attributeTextTag);
if (string.IsNullOrEmpty(textFromTag))
{
textFromTag = string.Concat("ATTR<", itemAttribute, "> TAG<");
textFromTag = string.Concat(textFromTag, attributeTextTag, ">");
}
if (addVariable && data.Variable.Length > 0)
textFromTag = string.Concat(textFromTag, " ", data.Variable);
return textFromTag;
}
/// <summary>
/// Load our data from the db file.
/// </summary>
private void LoadDBFile()
{
this.LoadTextDB();
this.LoadARZFile();
}
/// <summary>
/// Gets a DBRecord for the specified item ID string.
/// </summary>
/// <remarks>
/// Changed by VillageIdiot
/// Changed search order so that IT records have precedence of TQ records.
/// Add Custom Map database. Custom Map records have precedence over IT records.
/// </remarks>
/// <param name="itemId">Item Id which we are looking up</param>
/// <returns>Returns the DBRecord for the item Id</returns>
public DBRecordCollection GetRecordFromFile(string itemId)
{
itemId = TQData.NormalizeRecordPath(itemId);
if (this.ArzFileMod != null)
{
DBRecordCollection recordMod = arzProv.GetItem(this.ArzFileMod, itemId);
if (recordMod != null)
{
// Custom Map records have highest precedence.
return recordMod;
}
}
if (this.ArzFileIT != null)
{
// see if it's in IT ARZ file
DBRecordCollection recordIT = arzProv.GetItem(this.ArzFileIT, itemId);
if (recordIT != null)
{
// IT file takes precedence over TQ.
return recordIT;
}
}
return arzProv.GetItem(ArzFile, itemId);
}
/// <summary>
/// Gets a resource from the database using the resource Id.
/// Modified by VillageIdiot to support loading resources from a custom map folder.
/// </summary>
/// <param name="resourceId">Resource which we are fetching</param>
/// <returns>Retruns a byte array of the resource.</returns>
public byte[] LoadResource(string resourceId)
{
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Database.LoadResource({0})", resourceId);
resourceId = TQData.NormalizeRecordPath(resourceId);
if (TQDebug.DatabaseDebugLevel > 1)
Log.LogDebug(" Normalized({0})", resourceId);
// First we need to figure out the correct file to
// open, by grabbing it off the front of the resourceID
int backslashLocation = resourceId.IndexOf('\\');
// not a proper resourceID.
if (backslashLocation <= 0)
return null;
string arcFileBase = resourceId.Substring(0, backslashLocation);
if (TQDebug.DatabaseDebugLevel > 1)
Log.LogDebug("arcFileBase = {0}", arcFileBase);
string rootFolder;
string arcFile;
byte[] arcFileData = null;
// Added by VillageIdiot
// Check the mod folder for the image resource.
if (GamePathResolver.IsCustom)
{
if (TQDebug.DatabaseDebugLevel > 1)
Log.LogDebug("Checking Custom Resources.");
rootFolder = Path.Combine(GamePathResolver.MapName, "resources");
arcFile = Path.Combine(rootFolder, Path.ChangeExtension(arcFileBase, ".arc"));
arcFileData = this.ReadARCFile(arcFile, resourceId);
}
// We either didn't load the resource or didn't find what we were looking for so check the normal game resources.
if (arcFileData == null)
{
// See if this guy is from Immortal Throne expansion pack.
if (TQDebug.DatabaseDebugLevel > 1)
Log.LogDebug("Checking IT Resources.");
rootFolder = GamePathResolver.ImmortalThronePath;
bool xpack = false;
if (arcFileBase.ToUpperInvariant().Equals("XPACK"))
{
// Comes from Immortal Throne
xpack = true;
rootFolder = Path.Combine(rootFolder, "Resources", "XPack");
}
else if (arcFileBase.ToUpperInvariant().Equals("XPACK2"))
{
// Comes from Ragnarok
xpack = true;
rootFolder = Path.Combine(rootFolder, "Resources", "XPack2");
}
else if (arcFileBase.ToUpperInvariant().Equals("XPACK3"))
{
// Comes from Atlantis
xpack = true;
rootFolder = Path.Combine(rootFolder, "Resources", "XPack3");
}
else if (arcFileBase.ToUpperInvariant().Equals("XPACK4"))
{
// Comes from Eternal Embers
xpack = true;
rootFolder = Path.Combine(rootFolder, "Resources", "XPack4");
}
if (xpack == true)
{
// throw away that value and use the next field.
int previousBackslash = backslashLocation;
backslashLocation = resourceId.IndexOf('\\', backslashLocation + 1);
if (backslashLocation <= 0)
return null;// not a proper resourceID
arcFileBase = resourceId.Substring(previousBackslash + 1, backslashLocation - previousBackslash - 1);
resourceId = resourceId.Substring(previousBackslash + 1);
}
else
{
// Changed by VillageIdiot to search the IT resources folder for updated resources
// if IT is installed otherwise just the TQ folder.
rootFolder = Path.Combine(rootFolder, "Resources");
}
arcFile = Path.Combine(rootFolder, Path.ChangeExtension(arcFileBase, ".arc"));
arcFileData = this.ReadARCFile(arcFile, resourceId);
}
// Added by VillageIdiot
// Maybe the arc file is in the XPack folder even though the record does not state it.
// Also could be that it says xpack in the record but the file is in the root.
if (arcFileData == null)
{
rootFolder = Path.Combine(GamePathResolver.ImmortalThronePath, "Resources", "XPack");
arcFile = Path.Combine(rootFolder, Path.ChangeExtension(arcFileBase, ".arc"));
arcFileData = this.ReadARCFile(arcFile, resourceId);
}
// Now, let's check if the item is in Ragnarok DLC
if (arcFileData == null && GamePathResolver.IsRagnarokInstalled)
{
rootFolder = Path.Combine(GamePathResolver.ImmortalThronePath, "Resources", "XPack2");
arcFile = Path.Combine(rootFolder, Path.ChangeExtension(arcFileBase, ".arc"));
arcFileData = this.ReadARCFile(arcFile, resourceId);
}
if (arcFileData == null && GamePathResolver.IsAtlantisInstalled)
{
rootFolder = Path.Combine(GamePathResolver.ImmortalThronePath, "Resources", "XPack3");
arcFile = Path.Combine(rootFolder, Path.ChangeExtension(arcFileBase, ".arc"));
arcFileData = this.ReadARCFile(arcFile, resourceId);
}
if (arcFileData == null && GamePathResolver.IsEmbersInstalled)
{
rootFolder = Path.Combine(GamePathResolver.ImmortalThronePath, "Resources", "XPack4");
arcFile = Path.Combine(rootFolder, Path.ChangeExtension(arcFileBase, ".arc"));
arcFileData = this.ReadARCFile(arcFile, resourceId);
}
if (arcFileData == null)
{
// We are either vanilla TQ or have not found our resource yet.
// from the original TQ folder
if (TQDebug.DatabaseDebugLevel > 1)
Log.LogDebug("Checking TQ Resources.");
rootFolder = GamePathResolver.TQPath;
rootFolder = Path.Combine(rootFolder, "Resources");
arcFile = Path.Combine(rootFolder, Path.ChangeExtension(arcFileBase, ".arc"));
arcFileData = this.ReadARCFile(arcFile, resourceId);
}
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Exiting Database.LoadResource()");
return arcFileData;
}
#endregion Database Public Methods
#region Database Private Methods
/// <summary>
/// Reads data from an ARC file and puts it into a Byte array
/// </summary>
/// <param name="arcFileName">Name of the arc file.</param>
/// <param name="dataId">Id of data which we are getting from the arc file</param>
/// <returns>Byte array of the data from the arc file.</returns>
private byte[] ReadARCFile(string arcFileName, string dataId)
{
// See if we have this arcfile already and if not create it.
try
{
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Database.ReadARCFile('{0}', '{1}')", arcFileName, dataId);
ArcFile arcFile = this.arcFiles.GetOrAddAtomic(arcFileName, k =>
{
var file = new ArcFile(k);
arcProv.ReadARCToC(file);// Heavy lifting in GetOrAddAtomic
return file;
});
// Now retrieve the data
byte[] ans = arcProv.GetData(arcFile, dataId);
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Exiting Database.ReadARCFile()");
return ans;
}
catch (Exception e)
{
Log.LogError(e, "Exception occurred");
throw;
}
}
/// <summary>
/// Tries to determine the name of the text database file.
/// This is based on the game language and the UI language.
/// Will use English if all else fails.
/// </summary>
/// <param name="isImmortalThrone">Signals whether we are looking for Immortal Throne files or vanilla Titan Quest files.</param>
/// <returns>Path to the text db file</returns>
private string FigureDBFileToUse(bool isImmortalThrone)
{
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Database.FigureDBFileToUse({0})", isImmortalThrone);
string rootFolder;
if (isImmortalThrone)
{
if (GamePathResolver.ImmortalThronePath.Contains("Anniversary"))
rootFolder = Path.Combine(GamePathResolver.ImmortalThronePath, "Text");
else
rootFolder = Path.Combine(GamePathResolver.ImmortalThronePath, "Resources");
if (TQDebug.DatabaseDebugLevel > 1)
{
Log.LogDebug("Detecting Immortal Throne text files");
Log.LogDebug("rootFolder = {0}", rootFolder);
}
}
else
{
// from the original TQ folder
rootFolder = Path.Combine(GamePathResolver.TQPath, "Text");
if (TQDebug.DatabaseDebugLevel > 1)
{
Log.LogDebug("Detecting Titan Quest text files");
Log.LogDebug("rootFolder = {0}", rootFolder);
}
}
// make sure the damn directory exists
if (!Directory.Exists(rootFolder))
{
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Error - Root Folder does not exist");
return null; // silently fail
}
string baseFile = Path.Combine(rootFolder, "Text_");
string suffix = ".arc";
// Added explicit set to null though may not be needed
string cultureID = null;
// Moved this declaration since the first use is inside of the loop.
string filename = null;
// First see if we can use the game setting
string gameLanguage = this.GameLanguage;
if (TQDebug.DatabaseDebugLevel > 1)
{
Log.LogDebug("gameLanguage = {0}", gameLanguage == null ? "NULL" : gameLanguage);
Log.LogDebug("baseFile = {0}", baseFile);
}
if (gameLanguage != null)
{
// Try this method of getting the culture
if (TQDebug.DatabaseDebugLevel > 2)
Log.LogDebug("Try looking up cultureID");
foreach (CultureInfo cultureInfo in CultureInfo.GetCultures(CultureTypes.NeutralCultures))
{
if (TQDebug.DatabaseDebugLevel > 2)
Log.LogDebug("Trying {0}", cultureInfo.EnglishName.ToUpperInvariant());
if (cultureInfo.EnglishName.ToUpperInvariant().Equals(gameLanguage.ToUpperInvariant()) || cultureInfo.DisplayName.ToUpperInvariant().Equals(gameLanguage.ToUpperInvariant()))
{
cultureID = cultureInfo.TwoLetterISOLanguageName;
break;
}
}
// Titan Quest doesn't use the ISO language code for some languages
// Added null check to fix exception when there is no culture found.
if (cultureID != null)
{
if (cultureID.ToUpperInvariant() == "CS")
{
// Force Czech to use CZ instead of CS for the 2 letter code.
cultureID = "CZ";
}
else if (cultureID.ToUpperInvariant() == "PT")
{
// Force brazilian portuguese to use BR instead of PT
cultureID = "BR";
}
}
if (TQDebug.DatabaseDebugLevel > 1)
Log.LogDebug("cultureID = {0}", cultureID);
// Moved this inital check for the file into the loop
// and added a check to verify that we actually have a cultureID
if (cultureID != null)
{
filename = string.Concat(baseFile, cultureID, suffix);
if (TQDebug.DatabaseDebugLevel > 1)
{
Log.LogDebug("Detected cultureID from gameLanguage");
Log.LogDebug("filename = {0}", filename);
}
if (File.Exists(filename))
{
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Exiting Database.FigureDBFileToUse()");
return filename;
}
}
}
// try to use the default culture for the OS
cultureID = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
if (TQDebug.DatabaseDebugLevel > 1)
{
Log.LogDebug("Using cultureID from OS");
Log.LogDebug("cultureID = {0}", cultureID);
}
// Added a check to verify that we actually have a cultureID
// though it may not be needed
if (cultureID != null)
{
filename = string.Concat(baseFile, cultureID, suffix);
if (TQDebug.DatabaseDebugLevel > 1)
Log.LogDebug("filename = {0}", filename);
if (File.Exists(filename))
{
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Exiting Database.FigureDBFileToUse()");
return filename;
}
}
// Now just try EN
cultureID = "EN";
filename = string.Concat(baseFile, cultureID, suffix);
if (TQDebug.DatabaseDebugLevel > 1)
{
Log.LogDebug("Forcing English Language");
Log.LogDebug("cultureID = {0}", cultureID);
Log.LogDebug("filename = {0}", filename);
}
if (File.Exists(filename))
{
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Database.Exiting FigureDBFileToUse()");
return filename;
}
// Now just see if we can find anything.
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Detection Failed - searching for files");
string[] files = Directory.GetFiles(rootFolder, "Text_??.arc");
// Added check that files is not null.
if (files != null && files.Length > 0)
{
if (TQDebug.DatabaseDebugLevel > 1)
{
Log.LogDebug("Found some files");
Log.LogDebug("filename = {0}", files[0]);
}
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Exiting Database.FigureDBFileToUse()");
return files[0];
}
if (TQDebug.DatabaseDebugLevel > 0)
{
Log.LogDebug("Failed to determine Language file!");
Log.LogDebug("Exiting Database.FigureDBFileToUse()");
}
return null;
}
/// <summary>
/// Loads the Text database
/// </summary>
private void LoadTextDB()
{
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Database.LoadTextDB()");
string databaseFile = this.FigureDBFileToUse(false);
if (TQDebug.DatabaseDebugLevel > 1)
{
Log.LogDebug("Find Titan Quest text file");
Log.LogDebug("dbFile = {0}", databaseFile);
}
if (databaseFile != null)
{
// Try to suck what we want into memory and then parse it.
this.ParseTextDB(databaseFile, "text\\commonequipment.txt");
this.ParseTextDB(databaseFile, "text\\uniqueequipment.txt");
this.ParseTextDB(databaseFile, "text\\quest.txt");
this.ParseTextDB(databaseFile, "text\\ui.txt");
this.ParseTextDB(databaseFile, "text\\skills.txt");
this.ParseTextDB(databaseFile, "text\\monsters.txt"); // Added by VillageIdiot
this.ParseTextDB(databaseFile, "text\\menu.txt"); // Added by VillageIdiot
this.ParseTextDB(databaseFile, "text\\tutorial.txt");
// Immortal Throne data
this.ParseTextDB(databaseFile, "text\\xcommonequipment.txt");
this.ParseTextDB(databaseFile, "text\\xuniqueequipment.txt");
this.ParseTextDB(databaseFile, "text\\xquest.txt");
this.ParseTextDB(databaseFile, "text\\xui.txt");
this.ParseTextDB(databaseFile, "text\\xskills.txt");
this.ParseTextDB(databaseFile, "text\\xmonsters.txt"); // Added by VillageIdiot
this.ParseTextDB(databaseFile, "text\\xmenu.txt"); // Added by VillageIdiot
this.ParseTextDB(databaseFile, "text\\xnpc.txt"); // Added by VillageIdiot
this.ParseTextDB(databaseFile, "text\\modstrings.txt"); // Added by VillageIdiot
if (GamePathResolver.IsRagnarokInstalled)
{
this.ParseTextDB(databaseFile, "text\\x2commonequipment.txt");
this.ParseTextDB(databaseFile, "text\\x2uniqueequipment.txt");
this.ParseTextDB(databaseFile, "text\\x2quest.txt");
this.ParseTextDB(databaseFile, "text\\x2ui.txt");
this.ParseTextDB(databaseFile, "text\\x2skills.txt");
this.ParseTextDB(databaseFile, "text\\x2monsters.txt"); // Added by VillageIdiot
this.ParseTextDB(databaseFile, "text\\x2menu.txt"); // Added by VillageIdiot
this.ParseTextDB(databaseFile, "text\\x2npc.txt"); // Added by VillageIdiot
}
if (GamePathResolver.IsAtlantisInstalled)
{
this.ParseTextDB(databaseFile, "text\\x3basegame_nonvoiced.txt");
this.ParseTextDB(databaseFile, "text\\x3items_nonvoiced.txt");
this.ParseTextDB(databaseFile, "text\\x3mainquest_nonvoiced.txt");
this.ParseTextDB(databaseFile, "text\\x3misctags_nonvoiced.txt");
this.ParseTextDB(databaseFile, "text\\x3sidequests_nonvoiced.txt");
}
if (GamePathResolver.IsEmbersInstalled)
{
this.ParseTextDB(databaseFile, "text\\x4basegame_nonvoiced.txt");
this.ParseTextDB(databaseFile, "text\\x4items_nonvoiced.txt");
this.ParseTextDB(databaseFile, "text\\x4mainquest_nonvoiced.txt");
this.ParseTextDB(databaseFile, "text\\x4misctags_nonvoiced.txt");
this.ParseTextDB(databaseFile, "text\\x4nametags_nonvoiced.txt");
this.ParseTextDB(databaseFile, "text\\x4sidequests_nonvoiced.txt");
}
}
// For loading custom map text database.
if (GamePathResolver.IsCustom)
{
databaseFile = Path.Combine(GamePathResolver.MapName, "resources", "text.arc");
if (TQDebug.DatabaseDebugLevel > 1)
{
Log.LogDebug("Find Custom Map text file");
Log.LogDebug("dbFile = {0}", databaseFile);
}
if (databaseFile != null)
this.ParseTextDB(databaseFile, "text\\modstrings.txt");
}
// Added this check to see if anything was loaded.
if (this.textDB.Count == 0)
{
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Exception - Could not load Text DB.");
throw new FileLoadException("Could not load Text DB.");
}
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Exiting Database.LoadTextDB()");
}
/// <summary>
/// Parses the text database to put the entries into a hash table.
/// </summary>
/// <param name="databaseFile">Database file name (arc file)</param>
/// <param name="filename">Name of the text DB file within the arc file</param>
private void ParseTextDB(string databaseFile, string filename)
{
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Database.ParseTextDB({0}, {1})", databaseFile, filename);
byte[] data = this.ReadARCFile(databaseFile, filename);
if (data == null)
{
// Changed for mod support. Sometimes the text file has more entries than just the x or non-x prefix files.
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Error in ARC File: {0} does not contain an entry for '{1}'", databaseFile, filename);
return;
}
// now read it like a text file
// Changed to system default encoding since there might be extended ascii (or something else) in the text db.
using (StreamReader reader = new StreamReader(new MemoryStream(data), Encoding.Default))
{
char delimiter = '=';
string line;
while ((line = reader.ReadLine()) != null)
{
line = line.Trim();
// delete short lines
if (line.Length < 2)
continue;
// comment line
if (line.StartsWith("//", StringComparison.Ordinal))
continue;
// split on the equal sign
string[] fields = line.Split(delimiter);
// bad line
if (fields.Length < 2)
continue;
string label = fields[1].Trim();
// Now for the foreign languages there is a bunch of crap in here so the proper version of the adjective can be used with the proper
// noun form. I don' want to code all that so this next code will just take the first version of the adjective and then
// throw away all the metadata.
if (label.IndexOf('[') != -1)
{
// find first [xxx]
int textStart = label.IndexOf(']') + 1;
// find second [xxx]
int textEnd = label.IndexOf('[', textStart);
if (textEnd == -1)
// If it was the only [...] tag in the string then take the whole string after the tag
label = label.Substring(textStart);
else
// else take the string between the first 2 [...] tags
label = label.Substring(textStart, textEnd - textStart);
label = label.Trim();
}
// If this field is already in the db, then replace it
string key = fields[0].Trim().ToUpperInvariant();
this.textDB.AddOrUpdateAtomic(key, label);
}
}
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Exiting Database.ParseTextDB()");
}
/// <summary>
/// Loads a database arz file.
/// </summary>
private void LoadARZFile()
{
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Database.LoadARZFile()");
// from the original TQ folder
string file = Path.Combine(Path.Combine(GamePathResolver.TQPath, "Database"), "database.arz");
if (TQDebug.DatabaseDebugLevel > 1)
{
Log.LogDebug("Load Titan Quest database arz file");
Log.LogDebug("file = {0}", file);
}
this.ArzFile = new ArzFile(file);
arzProv.Read(this.ArzFile);
// now Immortal Throne expansion pack
this.ArzFileIT = this.ArzFile;
// Added to load a custom map database file.
if (GamePathResolver.IsCustom)
{
file = Path.Combine(GamePathResolver.MapName, "database", $"{Path.GetFileName(GamePathResolver.MapName)}.arz");
if (TQDebug.DatabaseDebugLevel > 1)
{
Log.LogDebug("Load Custom Map database arz file");
Log.LogDebug("file = {0}", file);
}
if (File.Exists(file))
{
this.ArzFileMod = new ArzFile(file);
arzProv.Read(this.ArzFileMod);
}
else
this.ArzFileMod = null;
}
if (TQDebug.DatabaseDebugLevel > 0)
Log.LogDebug("Exiting Database.LoadARZFile()");
}
#endregion Database Private Methods
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Prime31;
using System.Reflection;
public class Facebook : P31RestKit
{
public string accessToken;
public string appAccessToken;
public bool useSessionBabysitter = true;
private static Facebook _instance = null;
public static Facebook instance
{
get
{
if( _instance == null )
_instance = new Facebook();
return _instance;
}
}
public Facebook()
{
_baseUrl = "https://graph.facebook.com/";
forceJsonResponse = true;
}
#region Private
protected override IEnumerator send( string path, HTTPVerb httpVerb, Dictionary<string,object> parameters, Action<string, object> onComplete )
{
if( parameters == null )
parameters = new Dictionary<string, object>();
// add the access token if we dont have one in the dictionary
if( !parameters.ContainsKey( "access_token" ) )
parameters.Add( "access_token", accessToken );
if( httpVerb == HTTPVerb.PUT || httpVerb == HTTPVerb.DELETE )
parameters.Add( "method", httpVerb.ToString() );
return base.send( path, httpVerb, parameters, onComplete );
}
protected bool shouldSendRequest()
{
// if the session babysitter is not enabled always return true
if( !useSessionBabysitter )
return true;
// if we dont have the babysitter available then always send the request. This also protects against Windows Store/Phone Type class issues
try
{
#if UNITY_IPHONE
var type = typeof( Facebook ).Assembly.GetType( "FacebookBinding" );
#elif UNITY_ANDROID
var type = typeof( Facebook ).Assembly.GetType( "FacebookAndroid" );
#endif
#if UNITY_IPHONE || UNITY_ANDROID
// this will pass for iOS and Android when the SocialNetworking Plugin is present
if( type != null )
{
var method = type.GetMethod( "isSessionValid", BindingFlags.Static | BindingFlags.Public );
var result = method.Invoke( null, null );
return (bool)result;
}
#endif
}
catch( Exception )
{}
return true;
}
#endregion
public void prepareForMetroUse( GameObject go, MonoBehaviour mb )
{
GameObject.DontDestroyOnLoad( go );
surrogateGameObject = go;
surrogateMonobehaviour = mb;
}
#region Public
// Sends off a graph request. The completion handler will return a Dictionary<string,object> or List<object> if successful depending on the path called.
// See Facebook's documentation for the returned data and parameters
public void graphRequest( string path, Action<string, object> completionHandler )
{
graphRequest( path, HTTPVerb.GET, completionHandler );
}
public void graphRequest( string path, HTTPVerb verb, Action<string, object> completionHandler )
{
graphRequest( path, verb, null, completionHandler );
}
public void graphRequest( string path, HTTPVerb verb, Dictionary<string, object> parameters, Action<string, object> completionHandler )
{
// in the editor, we allow requests to be sent as long as we have an access token
#if UNITY_EDITOR
if( ( accessToken != null && accessToken.Length > 0 ) || shouldSendRequest() )
#else
if( shouldSendRequest() )
#endif
{
surrogateMonobehaviour.StartCoroutine( send( path, verb, parameters, completionHandler ) );
}
else
{
// if we have an auth helper we will use it because we are not logged in
// auth helpers are classes in the FacebookBinding and FacebookAndroid files
try
{
#if UNITY_IPHONE
var type = typeof( Facebook ).Assembly.GetType( "FacebookBinding" );
#elif UNITY_ANDROID
var type = typeof( Facebook ).Assembly.GetType( "FacebookAndroid" );
#endif
#if UNITY_IPHONE || UNITY_ANDROID
// this will pass for iOS and Android when the SocialNetworking Plugin is present
if( type != null )
{
var method = type.GetMethod( "babysitRequest", BindingFlags.Static | BindingFlags.NonPublic );
if( method != null )
{
Action action = () => { surrogateMonobehaviour.StartCoroutine( send( path, verb, parameters, completionHandler ) ); };
method.Invoke( null, new object[] { verb == HTTPVerb.POST, action } );
}
}
#endif
}
catch( Exception )
{}
}
}
public void graphRequestBatch( IEnumerable<FacebookBatchRequest> requests, Action<string, object> completionHandler )
{
var parameters = new Dictionary<string,object>();
var requestList = new List<Dictionary<string,object>>();
foreach( var r in requests )
requestList.Add( r.requestDictionary() );
parameters.Add( "batch", Json.encode( requestList ) );
surrogateMonobehaviour.StartCoroutine( send( string.Empty, HTTPVerb.POST, parameters, completionHandler ) );
}
// Fetches a profile image for the user with userId. completionHandler will fire with the Texture2D or null
public void fetchProfileImageForUserId( string userId, Action<Texture2D> completionHandler )
{
var url = "http://graph.facebook.com/" + userId + "/picture?type=large";
surrogateMonobehaviour.StartCoroutine( fetchImageAtUrl( url, completionHandler ) );
}
// Fetches an image for the url. completionHandler will fire with the Texture2D or null
public IEnumerator fetchImageAtUrl( string url, Action<Texture2D> completionHandler )
{
var www = new WWW( url );
yield return www;
if( !string.IsNullOrEmpty( www.error ) )
{
Debug.Log( "Error attempting to load profile image: " + www.error );
if( completionHandler != null )
completionHandler( null );
}
else
{
if( completionHandler != null )
completionHandler( www.texture );
}
}
#endregion
#region Graph API Examples
// Posts the message to the user's wall
public void postMessage( string message, Action<string, object> completionHandler )
{
var parameters = new Dictionary<string,object>
{
{ "message", message }
};
graphRequest( "me/feed", HTTPVerb.POST, parameters, completionHandler );
}
// Posts the message to the user's wall with a link and a name for the link
public void postMessageWithLink( string message, string link, string linkName, Action<string, object> completionHandler )
{
var parameters = new Dictionary<string,object>
{
{ "message", message },
{ "link", link },
{ "name", linkName }
};
graphRequest( "me/feed", HTTPVerb.POST, parameters, completionHandler );
}
// Posts the message to the user's wall with a link, a name for the link, a link to an image and a caption for the image
public void postMessageWithLinkAndLinkToImage( string message, string link, string linkName, string linkToImage, string caption, Action<string, object> completionHandler )
{
var parameters = new Dictionary<string,object>
{
{ "message", message },
{ "link", link },
{ "name", linkName },
{ "picture", linkToImage },
{ "caption", caption }
};
graphRequest( "me/feed", HTTPVerb.POST, parameters, completionHandler );
}
// Posts an image on the user's wall along with a caption.
public void postImage( byte[] image, string message, Action<string, object> completionHandler )
{
var parameters = new Dictionary<string,object>()
{
{ "picture", image },
{ "message", message }
};
graphRequest( "me/photos", HTTPVerb.POST, parameters, completionHandler );
}
// Posts an image to a specific album along with a caption.
public void postImageToAlbum( byte[] image, string caption, string albumId, Action<string, object> completionHandler )
{
var parameters = new Dictionary<string,object>()
{
{ "picture", image },
{ "message", caption }
};
graphRequest( albumId, HTTPVerb.POST, parameters, completionHandler );
}
// Sends a request to fetch the currently logged in users details
public void getMe( Action<string,FacebookMeResult> completionHandler )
{
graphRequest( "me", ( error, obj ) =>
{
if( completionHandler == null )
return;
if( error != null )
completionHandler( error, null );
else
completionHandler( null, Json.decodeObject<FacebookMeResult>( obj ) );
});
}
// Sends a request to fetch the currently logged in users friends
public void getFriends( Action<string,FacebookFriendsResult> completionHandler )
{
graphRequest( "me/friends", ( error, obj ) =>
{
if( completionHandler == null )
return;
if( error != null )
completionHandler( error, null );
else
completionHandler( null, Json.decodeObject<FacebookFriendsResult>( obj ) );
});
}
// Extends a short lived access token. Completion handler returns either the expiry date or null if unsuccessful. Note that it is highly recommended to
// only call this from a server. Your app secret should not be included with your application
public void extendAccessToken( string appId, string appSecret, Action<DateTime?> completionHandler )
{
if( Facebook.instance.accessToken == null )
{
Debug.LogError( "There is no access token to extend. The user must be autenticated before attempting to extend their access token" );
return;
}
var parameters = new Dictionary<string,object>()
{
{ "client_id", appId },
{ "client_secret", appSecret },
{ "grant_type", "fb_exchange_token" },
{ "fb_exchange_token", Facebook.instance.accessToken }
};
get( "oauth/access_token", parameters, ( error, obj ) =>
{
if( obj is string )
{
var text = obj as string;
if( text.StartsWith( "access_token=" ) )
{
var paramDict = text.parseQueryString();
Facebook.instance.accessToken = paramDict["access_token"];
var expires = double.Parse( paramDict["expires"] );
completionHandler( DateTime.Now.AddSeconds( expires ) );
}
else
{
Debug.LogError( "error extending access token: " + text );
completionHandler( null );
}
}
else
{
Debug.LogError( "error extending access token: " + error );
completionHandler( null );
}
});
}
// Checks the validity of a session on Facebook's servers. This is the authoritative way to check a session's validity.
public void checkSessionValidityOnServer( Action<bool> completionHandler )
{
/*
// first see if we have an access token
if( ( accessToken == null || ( accessToken != null && accessToken.Length == 0 ) ) || !shouldSendRequest() )
{
Debug.Log( "no access token locally so aborting request" );
completionHandler( false );
return;
}
*/
get( "me", ( error, obj ) =>
{
if( error == null && obj != null && obj is IDictionary )
completionHandler( true );
else
completionHandler( false );
});
}
// Fetches the session permissions directly from Facebook's servers. This is the authoritative way to get a session's granted permissions.
public void getSessionPermissionsOnServer( Action<string, List<string>> completionHandler )
{
get( "me/permissions", ( error, obj ) =>
{
if( error == null && obj != null && obj is IDictionary )
{
var resultDict = obj as IDictionary;
var dataDict = resultDict["data"] as IList;
var rawPermissionsList = dataDict[0] as IDictionary;
var grantedPermissions = new List<string>();
foreach( DictionaryEntry kv in rawPermissionsList )
{
if( kv.Value.ToString() == "1" )
grantedPermissions.Add( kv.Key.ToString() );
}
completionHandler( null, grantedPermissions );
}
else
{
completionHandler( error, null );
}
});
}
#endregion
#region App Access Token
// Fetches the app access token. Note that it is highly recommended to only call this from a server. Your app secret should not be included
// with your application
public void getAppAccessToken( string appId, string appSecret, Action<string> completionHandler )
{
var parameters = new Dictionary<string,object>()
{
{ "client_id", appId },
{ "client_secret", appSecret },
{ "grant_type", "client_credentials" }
};
get( "oauth/access_token", parameters, ( error, obj ) =>
{
if( obj is string )
{
var text = obj as string;
if( text.StartsWith( "access_token=" ) )
{
appAccessToken = text.Replace( "access_token=", string.Empty );
completionHandler( appAccessToken );
}
else
{
completionHandler( null );
}
}
else
{
completionHandler( null );
}
});
}
// Posts a score for the current user
public void postScore( int score, Action<bool> completionHandler )
{
// post the score to the proper path
var parameters = new Dictionary<string,object>()
{
{ "score", score.ToString() }
};
post( "me/scores", parameters, ( error, obj ) =>
{
if( error == null && obj is string )
{
completionHandler( ((string)obj).ToLower() == "true" );
}
else
{
completionHandler( false );
}
});
}
// Retrieves the scores for your app
public void getScores( string userId, Action<string, object> onComplete )
{
var path = userId + "/scores";
graphRequest( path, onComplete );
}
#endregion
}
| |
namespace Antlr.Runtime
{
using System.Collections.Generic;
using ArgumentException = System.ArgumentException;
using ArgumentOutOfRangeException = System.ArgumentOutOfRangeException;
using ArgumentNullException = System.ArgumentNullException;
#if !SILVERLIGHT
[System.Serializable]
#endif
internal class ANTLRStringStream : ICharStream
{
protected char[] data;
protected int n;
protected int p = 0;
int line = 1;
int charPositionInLine = 0;
protected int markDepth = 0;
protected IList<CharStreamState> markers;
protected int lastMarker;
public string name;
public ANTLRStringStream( string input )
: this( input, null )
{
}
public ANTLRStringStream( string input, string sourceName )
: this( input.ToCharArray(), input.Length, sourceName )
{
}
public ANTLRStringStream( char[] data, int numberOfActualCharsInArray )
: this( data, numberOfActualCharsInArray, null )
{
}
public ANTLRStringStream( char[] data, int numberOfActualCharsInArray, string sourceName )
{
if (data == null)
throw new ArgumentNullException("data");
if (numberOfActualCharsInArray < 0)
throw new ArgumentOutOfRangeException();
if (numberOfActualCharsInArray > data.Length)
throw new ArgumentException();
this.data = data;
this.n = numberOfActualCharsInArray;
this.name = sourceName;
}
protected ANTLRStringStream()
{
this.data = new char[0];
}
public virtual int Index
{
get
{
return p;
}
}
public virtual int Line
{
get
{
return line;
}
set
{
line = value;
}
}
public virtual int CharPositionInLine
{
get
{
return charPositionInLine;
}
set
{
charPositionInLine = value;
}
}
public virtual void Reset()
{
p = 0;
line = 1;
charPositionInLine = 0;
markDepth = 0;
}
public virtual void Consume()
{
//System.out.println("prev p="+p+", c="+(char)data[p]);
if ( p < n )
{
charPositionInLine++;
if ( data[p] == '\n' )
{
line++;
charPositionInLine = 0;
}
p++;
//System.out.println("p moves to "+p+" (c='"+(char)data[p]+"')");
}
}
public virtual int LA( int i )
{
if ( i == 0 )
{
return 0; // undefined
}
if ( i < 0 )
{
i++; // e.g., translate LA(-1) to use offset i=0; then data[p+0-1]
if ( ( p + i - 1 ) < 0 )
{
return CharStreamConstants.EndOfFile; // invalid; no char before first char
}
}
if ( ( p + i - 1 ) >= n )
{
//System.out.println("char LA("+i+")=EOF; p="+p);
return CharStreamConstants.EndOfFile;
}
//System.out.println("char LA("+i+")="+(char)data[p+i-1]+"; p="+p);
//System.out.println("LA("+i+"); p="+p+" n="+n+" data.length="+data.length);
return data[p + i - 1];
}
public virtual int LT( int i )
{
return LA( i );
}
public virtual int Count
{
get
{
return n;
}
}
public virtual int Mark()
{
if ( markers == null )
{
markers = new List<CharStreamState>();
markers.Add( null ); // depth 0 means no backtracking, leave blank
}
markDepth++;
CharStreamState state = null;
if ( markDepth >= markers.Count )
{
state = new CharStreamState();
markers.Add( state );
}
else
{
state = markers[markDepth];
}
state.p = p;
state.line = line;
state.charPositionInLine = charPositionInLine;
lastMarker = markDepth;
return markDepth;
}
public virtual void Rewind( int m )
{
if (m < 0)
throw new ArgumentOutOfRangeException();
//if (m > markDepth)
// throw new ArgumentException();
CharStreamState state = markers[m];
// restore stream state
Seek( state.p );
line = state.line;
charPositionInLine = state.charPositionInLine;
Release( m );
}
public virtual void Rewind()
{
Rewind( lastMarker );
}
public virtual void Release( int marker )
{
// unwind any other markers made after m and release m
markDepth = marker;
// release this marker
markDepth--;
}
public virtual void Seek( int index )
{
if ( index <= p )
{
p = index; // just jump; don't update stream state (line, ...)
return;
}
// seek forward, consume until p hits index
while ( p < index )
{
Consume();
}
}
public virtual string Substring( int start, int length )
{
if (start < 0)
throw new ArgumentOutOfRangeException();
if (length < 0)
throw new ArgumentOutOfRangeException();
if (start + length > data.Length)
throw new ArgumentException();
if (length == 0)
return string.Empty;
return new string( data, start, length );
}
public virtual string SourceName
{
get
{
return name;
}
}
public override string ToString()
{
return new string(data);
}
}
}
| |
S/W Version Information
Model: Ref.Device-PQ
Tizen-Version: 2.2.1
Build-Number: Tizen_Ref.Device-PQ_20131107.2323
Build-Date: 2013.11.07 23:23:19
Crash Information
Process Name: QRDemo
PID: 27274
Date: 2013-11-30 12:06:06(GMT+0400)
Executable File Path: /opt/apps/vd84JCg9vN/bin/QRDemo
This process is multi-thread process
pid=27274 tid=27274
Signal: 11
(SIGSEGV)
si_code: -6
signal sent by tkill (sent by pid 27274, uid 5000)
Register Information
r0 = 0x00000010, r1 = 0xabf09f78
r2 = 0xabf09f78, r3 = 0x0016f76e
r4 = 0x00000010, r5 = 0xabf09f78
r6 = 0x001e69d8, r7 = 0x0020bd80
r8 = 0xabf59330, r9 = 0x000e4860
r10 = 0xb447c940, fp = 0xbebc8d10
ip = 0xb430d1c5, sp = 0xbebc8cd8
lr = 0xb26ac220, pc = 0xb430d1cc
cpsr = 0x60000030
Memory Information
MemTotal: 797320 KB
MemFree: 12832 KB
Buffers: 5376 KB
Cached: 170072 KB
VmPeak: 265100 KB
VmSize: 229716 KB
VmLck: 0 KB
VmHWM: 40980 KB
VmRSS: 40980 KB
VmData: 113824 KB
VmStk: 136 KB
VmExe: 32 KB
VmLib: 79928 KB
VmPTE: 168 KB
VmSwap: 0 KB
Maps Information
00008000 00010000 r-xp /usr/bin/launchpad_preloading_preinitializing_daemon
00018000 000dc000 rw-p [heap]
000dc000 0030d000 rw-p [heap]
ac993000 ac9c6000 r-xp /usr/lib/gstreamer-0.10/libgstcoreelements.so
ac9cf000 aca05000 r-xp /usr/lib/gstreamer-0.10/libgstcamerasrc.so
ae35a000 ae35d000 r-xp /usr/lib/bufmgr/libtbm_exynos4412.so.0.0.0
afba5000 afbf0000 r-xp /usr/lib/libGLESv1_CM.so.1.1
afbf9000 afc21000 r-xp /usr/lib/evas/modules/engines/gl_x11/linux-gnueabi-armv7l-1.7.99/module.so
afd77000 afd83000 r-xp /usr/lib/libtzsvc.so.0.0.1
afd90000 afd92000 r-xp /usr/lib/libemail-network.so.1.1.0
afd9a000 afe44000 r-xp /usr/lib/libuw-imap-toolkit.so.0.0.0
afe52000 afe56000 r-xp /usr/lib/libss-client.so.1.0.0
afe5e000 afe63000 r-xp /usr/lib/libmmutil_jpeg.so.0.0.0
afe6c000 afe86000 r-xp /usr/lib/libnfc.so.1.0.0
afe8e000 afe9f000 r-xp /usr/lib/libnfc-common-lib.so.1.0.0
afea8000 afece000 r-xp /usr/lib/libbluetooth-api.so.1.0.0
afed7000 afefd000 r-xp /usr/lib/libzmq.so.3.0.0
aff07000 aff10000 r-xp /usr/lib/libpims-ipc.so.0.0.30
aff18000 aff1d000 r-xp /usr/lib/libmemenv.so.1.1.0
aff25000 aff63000 r-xp /usr/lib/libleveldb.so.1.1.0
aff6c000 aff74000 r-xp /usr/lib/libgstfft-0.10.so.0.25.0
aff7c000 affa6000 r-xp /usr/lib/libgstaudio-0.10.so.0.25.0
affaf000 affbe000 r-xp /usr/lib/libgstvideo-0.10.so.0.25.0
affc6000 affde000 r-xp /usr/lib/libgstpbutils-0.10.so.0.25.0
affe0000 b0005000 r-xp /usr/lib/libxslt.so.1.1.16
b000e000 b0012000 r-xp /usr/lib/libeukit.so.1.7.99
b001a000 b0022000 r-xp /usr/lib/libui-gadget-1.so.0.1.0
b002a000 b0033000 r-xp /usr/lib/libmsg_vobject.so
b003c000 b0046000 r-xp /usr/lib/libdrm-client.so.0.0.1
b004e000 b0067000 r-xp /usr/lib/libmsg_plugin_manager.so
b0070000 b00a9000 r-xp /usr/lib/libmsg_framework_handler.so
b00b2000 b00e6000 r-xp /usr/lib/libmsg_transaction_proxy.so
b00ef000 b012f000 r-xp /usr/lib/libmsg_utils.so
b0130000 b013f000 r-xp /usr/lib/libemail-common-use.so.1.1.0
b0148000 b01c3000 r-xp /usr/lib/libemail-core.so.1.1.0
b01d3000 b021c000 r-xp /usr/lib/libemail-storage.so.1.1.0
b0225000 b0232000 r-xp /usr/lib/libemail-ipc.so.1.1.0
b023a000 b0264000 r-xp /usr/lib/libSLP-location.so.0.0.0
b026d000 b0276000 r-xp /usr/lib/libdownload-provider-interface.so.1.1.6
b027e000 b0285000 r-xp /usr/lib/libmedia-utils.so.0.0.0
b028d000 b028f000 r-xp /usr/lib/libmedia-hash.so.1.0.0
b0297000 b02b0000 r-xp /usr/lib/libmedia-thumbnail.so.1.0.0
b02b8000 b02ba000 r-xp /usr/lib/libmedia-svc-hash.so.1.0.0
b02c2000 b02da000 r-xp /usr/lib/libmedia-service.so.1.0.0
b02e2000 b02f6000 r-xp /usr/lib/libnetwork.so.0.0.0
b02ff000 b030a000 r-xp /usr/lib/libstt.so
b0312000 b0318000 r-xp /usr/lib/libbadge.so.0.0.1
b0320000 b0326000 r-xp /usr/lib/libcapi-appfw-app-manager.so.0.1.0
b032e000 b0334000 r-xp /usr/lib/libshortcut.so.0.0.1
b033d000 b0340000 r-xp /usr/lib/libminicontrol-provider.so.0.0.1
b0348000 b0353000 r-xp /usr/lib/liblivebox-service.so.0.0.1
b035b000 b0370000 r-xp /usr/lib/liblivebox-viewer.so.0.0.1
b0378000 b037c000 r-xp /usr/lib/libcapi-appfw-package-manager.so.0.0.30
b0384000 b05a1000 r-xp /usr/lib/libface-engine-plugin.so
b05ff000 b0605000 r-xp /usr/lib/libcapi-network-nfc.so.0.0.11
b060e000 b0625000 r-xp /usr/lib/libcapi-network-bluetooth.so.0.1.40
b062d000 b0635000 r-xp /usr/lib/libcapi-network-wifi.so.0.1.2_24
b063d000 b0656000 r-xp /usr/lib/libaccounts-svc.so.0.2.66
b065e000 b06d0000 r-xp /usr/lib/libcontacts-service2.so.0.9.114.7
b06ef000 b0732000 r-xp /usr/lib/libcalendar-service2.so.0.1.44
b073c000 b0744000 r-xp /usr/lib/libcapi-web-favorites.so
b0745000 b1947000 r-xp /usr/lib/libewebkit2.so.0.11.113
b1a2c000 b1a34000 r-xp /usr/lib/libpush.so.0.2.12
b1a3c000 b1a57000 r-xp /usr/lib/libmsg_mapi.so.0.1.0
b1a60000 b1a78000 r-xp /usr/lib/libemail-api.so.1.1.0
b1a80000 b1a89000 r-xp /usr/lib/libcapi-system-sensor.so.0.1.17
b1a92000 b1a95000 r-xp /usr/lib/libcapi-telephony-sim.so.0.1.7
b1a9d000 b1aa0000 r-xp /usr/lib/libcapi-telephony-network-info.so.0.1.0
b1aa9000 b1ab4000 r-xp /usr/lib/libcapi-location-manager.so.0.1.11
b1abc000 b1ac0000 r-xp /usr/lib/libcapi-web-url-download.so.0.1.0
b1ac8000 b1ae9000 r-xp /usr/lib/libcapi-content-media-content.so.0.2.59
b1af1000 b1af3000 r-xp /usr/lib/libcamsrcjpegenc.so.0.0.0
b1afb000 b1b0f000 r-xp /usr/lib/libwifi-direct.so.0.0
b1b17000 b1b1f000 r-xp /usr/lib/libcapi-network-tethering.so.0.1.0
b1b20000 b1b29000 r-xp /usr/lib/libcapi-network-connection.so.0.1.3_18
b1b31000 b1b65000 r-xp /usr/lib/libopenal.so.1.13.0
b1b6e000 b1b71000 r-xp /usr/lib/libalut.so.0.1.0
b1b7b000 b1b80000 r-xp /usr/lib/osp/libosp-speech-stt.so.1.2.2.0
b1b88000 b1ba6000 r-xp /usr/lib/osp/libosp-shell-core.so.1.2.2.1
b1baf000 b1c20000 r-xp /usr/lib/osp/libosp-shell.so.1.2.2.1
b1c32000 b1c38000 r-xp /usr/lib/osp/libosp-speech-tts.so.1.2.2.0
b1c40000 b1c63000 r-xp /usr/lib/osp/libosp-face.so.1.2.2.0
b1c6d000 b1ccb000 r-xp /usr/lib/osp/libosp-nfc.so.1.2.2.0
b1cd7000 b1d32000 r-xp /usr/lib/osp/libosp-bluetooth.so.1.2.2.0
b1d3e000 b1db1000 r-xp /usr/lib/osp/libosp-wifi.so.1.2.2.0
b1dbd000 b1e7e000 r-xp /usr/lib/osp/libosp-social.so.1.2.2.0
b1e88000 b1efd000 r-xp /usr/lib/osp/libosp-web.so.1.2.2.0
b1f0b000 b1f58000 r-xp /usr/lib/osp/libosp-messaging.so.1.2.2.0
b1f62000 b1f7f000 r-xp /usr/lib/osp/libosp-uix.so.1.2.2.0
b1f89000 b1fa8000 r-xp /usr/lib/osp/libosp-telephony.so.1.2.2.0
b1fb1000 b1fca000 r-xp /usr/lib/osp/libosp-locations.so.1.2.2.3
b1fd3000 b2030000 r-xp /usr/lib/osp/libosp-content.so.1.2.2.0
b2039000 b204b000 r-xp /usr/lib/osp/libosp-ime.so.1.2.2.0
b2054000 b206e000 r-xp /usr/lib/osp/libosp-json.so.1.2.2.0
b2078000 b208a000 r-xp /usr/lib/libmmfile_utils.so.0.0.0
b2092000 b2097000 r-xp /usr/lib/libmmffile.so.0.0.0
b209f000 b2103000 r-xp /usr/lib/libmmfcamcorder.so.0.0.0
b2110000 b21d5000 r-xp /usr/lib/osp/libosp-net.so.1.2.2.0
b21e3000 b2406000 r-xp /usr/lib/osp/libarengine.so
b2482000 b2487000 r-xp /usr/lib/libcapi-media-metadata-extractor.so
b248f000 b2494000 r-xp /usr/lib/libcapi-media-recorder.so.0.1.3
b249c000 b24a7000 r-xp /usr/lib/libcapi-media-camera.so.0.1.4
b24af000 b24b2000 r-xp /usr/lib/libcapi-media-sound-manager.so.0.1.1
b24ba000 b24c8000 r-xp /usr/lib/libcapi-media-player.so.0.1.1
b24d0000 b24f1000 r-xp /usr/lib/libopencore-amrnb.so.0.0.2
b24fa000 b24fe000 r-xp /usr/lib/libogg.so.0.7.1
b2506000 b2528000 r-xp /usr/lib/libvorbis.so.0.4.3
b2530000 b2534000 r-xp /usr/lib/libcapi-media-audio-io.so.0.2.0
b253c000 b255a000 r-xp /usr/lib/osp/libosp-image.so.1.2.2.0
b2563000 b2581000 r-xp /usr/lib/osp/libosp-vision.so.1.2.2.0
b258a000 b2681000 r-xp /usr/lib/osp/libosp-media.so.1.2.2.0
b2693000 b269d000 r-xp /usr/lib/evas/modules/engines/software_generic/linux-gnueabi-armv7l-1.7.99/module.so
b26a5000 b26b4000 r-xp /opt/usr/apps/vd84JCg9vN/bin/QRDemo.exe
b26bd000 b272f000 r-xp /usr/lib/libosp-env-config.so.1.2.2.1
b2737000 b2771000 r-xp /usr/lib/libpulsecommon-0.9.23.so
b277a000 b277e000 r-xp /usr/lib/libmmfsoundcommon.so.0.0.0
b2786000 b27b7000 r-xp /usr/lib/libpulse.so.0.12.4
b27bf000 b2822000 r-xp /usr/lib/libasound.so.2.0.0
b282c000 b282f000 r-xp /usr/lib/libpulse-simple.so.0.0.3
b2837000 b283b000 r-xp /usr/lib/libascenario-0.2.so.0.0.0
b2844000 b2861000 r-xp /usr/lib/libavsysaudio.so.0.0.1
b2869000 b2877000 r-xp /usr/lib/libmmfsound.so.0.1.0
b287f000 b291b000 r-xp /usr/lib/libgstreamer-0.10.so.0.30.0
b2927000 b2968000 r-xp /usr/lib/libgstbase-0.10.so.0.30.0
b2971000 b297a000 r-xp /usr/lib/libgstapp-0.10.so.0.25.0
b2982000 b298f000 r-xp /usr/lib/libgstinterfaces-0.10.so.0.25.0
b2998000 b299e000 r-xp /usr/lib/libUMP.so
b29a6000 b29a9000 r-xp /usr/lib/libmm_ta.so.0.0.0
b29b1000 b29c0000 r-xp /usr/lib/libICE.so.6.3.0
b29ca000 b29cf000 r-xp /usr/lib/libSM.so.6.0.1
b29d7000 b29d8000 r-xp /usr/lib/libmmfkeysound.so.0.0.0
b29e0000 b29e8000 r-xp /usr/lib/libmmfcommon.so.0.0.0
b29f0000 b29f8000 r-xp /usr/lib/libaudio-session-mgr.so.0.0.0
b2a03000 b2a06000 r-xp /usr/lib/libmmfsession.so.0.0.0
b2a0e000 b2a52000 r-xp /usr/lib/libmmfplayer.so.0.0.0
b2a5b000 b2a6e000 r-xp /usr/lib/libEGL_platform.so
b2a77000 b2b4e000 r-xp /usr/lib/libMali.so
b2b59000 b2b5f000 r-xp /usr/lib/libxcb-render.so.0.0.0
b2b67000 b2b68000 r-xp /usr/lib/libxcb-shm.so.0.0.0
b2b71000 b2baf000 r-xp /usr/lib/libGLESv2.so.2.0
b2bb7000 b2c02000 r-xp /usr/lib/libtiff.so.5.1.0
b2c0d000 b2c36000 r-xp /usr/lib/libturbojpeg.so
b2c4f000 b2c55000 r-xp /usr/lib/libmmutil_imgp.so.0.0.0
b2c5d000 b2c63000 r-xp /usr/lib/libgif.so.4.1.6
b2c6b000 b2c8d000 r-xp /usr/lib/libavutil.so.51.73.101
b2c9c000 b2cca000 r-xp /usr/lib/libswscale.so.2.1.101
b2cd3000 b2fca000 r-xp /usr/lib/libavcodec.so.54.59.100
b32f1000 b330a000 r-xp /usr/lib/libpng12.so.0.50.0
b3313000 b3319000 r-xp /usr/lib/libfeedback.so.0.1.4
b3321000 b332d000 r-xp /usr/lib/libtts.so
b3335000 b334c000 r-xp /usr/lib/libEGL.so.1.4
b3355000 b340c000 r-xp /usr/lib/libcairo.so.2.11200.12
b3416000 b3430000 r-xp /usr/lib/osp/libosp-image-core.so.1.2.2.0
b3439000 b3d37000 r-xp /usr/lib/osp/libosp-uifw.so.1.2.2.1
b3daa000 b3daf000 r-xp /usr/lib/libslp_devman_plugin.so
b3db8000 b3dbb000 r-xp /usr/lib/libsyspopup_caller.so.0.1.0
b3dc3000 b3dc7000 r-xp /usr/lib/libsysman.so.0.2.0
b3dcf000 b3de0000 r-xp /usr/lib/libsecurity-server-commons.so.1.0.0
b3de9000 b3deb000 r-xp /usr/lib/libsystemd-daemon.so.0.0.1
b3df3000 b3df5000 r-xp /usr/lib/libdeviced.so.0.1.0
b3dfd000 b3e13000 r-xp /usr/lib/libpkgmgr_parser.so.0.1.0
b3e1b000 b3e1d000 r-xp /usr/lib/libpkgmgr_installer_status_broadcast_server.so.0.1.0
b3e25000 b3e28000 r-xp /usr/lib/libpkgmgr_installer_client.so.0.1.0
b3e30000 b3e33000 r-xp /usr/lib/libdevice-node.so.0.1
b3e3b000 b3e3f000 r-xp /usr/lib/libheynoti.so.0.0.2
b3e47000 b3e8c000 r-xp /usr/lib/libsoup-2.4.so.1.5.0
b3e95000 b3eaa000 r-xp /usr/lib/libsecurity-server-client.so.1.0.1
b3eb3000 b3eb7000 r-xp /usr/lib/libcapi-system-info.so.0.2.0
b3ebf000 b3ec4000 r-xp /usr/lib/libcapi-system-system-settings.so.0.0.2
b3ecc000 b3ecd000 r-xp /usr/lib/libcapi-system-power.so.0.1.1
b3ed6000 b3ed9000 r-xp /usr/lib/libcapi-system-device.so.0.1.0
b3ee1000 b3ee4000 r-xp /usr/lib/libcapi-system-runtime-info.so.0.0.3
b3eed000 b3ef0000 r-xp /usr/lib/libcapi-network-serial.so.0.0.8
b3ef8000 b3ef9000 r-xp /usr/lib/libcapi-content-mime-type.so.0.0.2
b3f01000 b3f0f000 r-xp /usr/lib/libcapi-appfw-application.so.0.1.0
b3f18000 b3f3a000 r-xp /usr/lib/libSLP-tapi.so.0.0.0
b3f42000 b3f45000 r-xp /usr/lib/libuuid.so.1.3.0
b3f4e000 b3f6c000 r-xp /usr/lib/libpkgmgr-info.so.0.0.17
b3f74000 b3f8b000 r-xp /usr/lib/libpkgmgr-client.so.0.1.68
b3f94000 b3f95000 r-xp /usr/lib/libpmapi.so.1.2
b3f9d000 b3fa5000 r-xp /usr/lib/libminizip.so.1.0.0
b3fad000 b3fb8000 r-xp /usr/lib/libmessage-port.so.1.2.2.1
b3fc0000 b4098000 r-xp /usr/lib/libxml2.so.2.7.8
b40a5000 b40c3000 r-xp /usr/lib/libpcre.so.0.0.1
b40cb000 b40ce000 r-xp /usr/lib/libiniparser.so.0
b40d7000 b40db000 r-xp /usr/lib/libhaptic.so.0.1
b40e3000 b40ee000 r-xp /usr/lib/libcryptsvc.so.0.0.1
b40fb000 b4100000 r-xp /usr/lib/libdevman.so.0.1
b4109000 b410d000 r-xp /usr/lib/libchromium.so.1.0
b4115000 b411b000 r-xp /usr/lib/libappsvc.so.0.1.0
b4123000 b4124000 r-xp /usr/lib/osp/libappinfo.so.1.2.2.1
b4134000 b4136000 r-xp /opt/usr/apps/vd84JCg9vN/bin/QRDemo
b413e000 b4144000 r-xp /usr/lib/libalarm.so.0.0.0
b414d000 b415f000 r-xp /usr/lib/libprivacy-manager-client.so.0.0.5
b4167000 b4467000 r-xp /usr/lib/osp/libosp-appfw.so.1.2.2.1
b4486000 b4490000 r-xp /lib/libnss_files-2.13.so
b4499000 b44a2000 r-xp /lib/libnss_nis-2.13.so
b44ab000 b44bc000 r-xp /lib/libnsl-2.13.so
b44c7000 b44cd000 r-xp /lib/libnss_compat-2.13.so
b44d6000 b44df000 r-xp /usr/lib/libcapi-security-privilege-manager.so.0.0.3
b4807000 b4818000 r-xp /usr/lib/libcom-core.so.0.0.1
b4820000 b4822000 r-xp /usr/lib/libdri2.so.0.0.0
b482a000 b4832000 r-xp /usr/lib/libdrm.so.2.4.0
b483a000 b483e000 r-xp /usr/lib/libtbm.so.1.0.0
b4846000 b4849000 r-xp /usr/lib/libXv.so.1.0.0
b4851000 b491c000 r-xp /usr/lib/libscim-1.0.so.8.2.3
b4932000 b4942000 r-xp /usr/lib/libnotification.so.0.1.0
b494a000 b496e000 r-xp /usr/lib/ecore/immodules/libisf-imf-module.so
b4977000 b4987000 r-xp /lib/libresolv-2.13.so
b498b000 b498d000 r-xp /usr/lib/libgmodule-2.0.so.0.3200.3
b4995000 b4ae8000 r-xp /usr/lib/libcrypto.so.1.0.0
b4b06000 b4b52000 r-xp /usr/lib/libssl.so.1.0.0
b4b5e000 b4b8a000 r-xp /usr/lib/libidn.so.11.5.44
b4b93000 b4b9d000 r-xp /usr/lib/libcares.so.2.0.0
b4ba5000 b4bbc000 r-xp /lib/libexpat.so.1.5.2
b4bc6000 b4bea000 r-xp /usr/lib/libicule.so.48.1
b4bf3000 b4bfb000 r-xp /usr/lib/libsf_common.so
b4c03000 b4c9e000 r-xp /usr/lib/libstdc++.so.6.0.14
b4cb1000 b4d8e000 r-xp /usr/lib/libgio-2.0.so.0.3200.3
b4d99000 b4dbe000 r-xp /usr/lib/libexif.so.12.3.3
b4dd2000 b4ddc000 r-xp /usr/lib/libethumb.so.1.7.99
b4de4000 b4e28000 r-xp /usr/lib/libsndfile.so.1.0.25
b4e36000 b4e38000 r-xp /usr/lib/libctxdata.so.0.0.0
b4e40000 b4e4e000 r-xp /usr/lib/libremix.so.0.0.0
b4e56000 b4e57000 r-xp /usr/lib/libecore_imf_evas.so.1.7.99
b4e5f000 b4e78000 r-xp /usr/lib/liblua-5.1.so
b4e81000 b4e88000 r-xp /usr/lib/libembryo.so.1.7.99
b4e91000 b4e94000 r-xp /usr/lib/libecore_input_evas.so.1.7.99
b4e9c000 b4ed9000 r-xp /usr/lib/libcurl.so.4.3.0
b4ee3000 b4ee7000 r-xp /usr/lib/libecore_ipc.so.1.7.99
b4ef0000 b4f5a000 r-xp /usr/lib/libpixman-1.so.0.28.2
b4f67000 b4f8b000 r-xp /usr/lib/libfontconfig.so.1.5.0
b4f94000 b4ff0000 r-xp /usr/lib/libharfbuzz.so.0.907.0
b5002000 b5016000 r-xp /usr/lib/libfribidi.so.0.3.1
b501e000 b5073000 r-xp /usr/lib/libfreetype.so.6.8.1
b507e000 b50a2000 r-xp /usr/lib/libjpeg.so.8.0.2
b50ba000 b50d1000 r-xp /lib/libz.so.1.2.5
b50d9000 b50e6000 r-xp /usr/lib/libsensor.so.1.1.0
b50f1000 b50f3000 r-xp /usr/lib/libapp-checker.so.0.1.0
b50fb000 b5101000 r-xp /usr/lib/libxdgmime.so.1.1.0
b6218000 b6300000 r-xp /usr/lib/libicuuc.so.48.1
b630d000 b642d000 r-xp /usr/lib/libicui18n.so.48.1
b643b000 b643e000 r-xp /usr/lib/libSLP-db-util.so.0.1.0
b6446000 b644f000 r-xp /usr/lib/libvconf.so.0.2.45
b6457000 b6465000 r-xp /usr/lib/libail.so.0.1.0
b646d000 b6485000 r-xp /usr/lib/libdbus-glib-1.so.2.2.2
b6486000 b648b000 r-xp /usr/lib/libffi.so.5.0.10
b6493000 b6494000 r-xp /usr/lib/libgthread-2.0.so.0.3200.3
b649c000 b64a6000 r-xp /usr/lib/libXext.so.6.4.0
b64af000 b64b2000 r-xp /usr/lib/libXtst.so.6.1.0
b64ba000 b64c0000 r-xp /usr/lib/libXrender.so.1.3.0
b64c8000 b64ce000 r-xp /usr/lib/libXrandr.so.2.2.0
b64d6000 b64d7000 r-xp /usr/lib/libXinerama.so.1.0.0
b64e0000 b64e9000 r-xp /usr/lib/libXi.so.6.1.0
b64f1000 b64f4000 r-xp /usr/lib/libXfixes.so.3.1.0
b64fc000 b64fe000 r-xp /usr/lib/libXgesture.so.7.0.0
b6506000 b6508000 r-xp /usr/lib/libXcomposite.so.1.0.0
b6510000 b6511000 r-xp /usr/lib/libXdamage.so.1.1.0
b651a000 b6521000 r-xp /usr/lib/libXcursor.so.1.0.2
b6529000 b6531000 r-xp /usr/lib/libemotion.so.1.7.99
b6539000 b6554000 r-xp /usr/lib/libecore_con.so.1.7.99
b655d000 b6562000 r-xp /usr/lib/libecore_imf.so.1.7.99
b656b000 b6573000 r-xp /usr/lib/libethumb_client.so.1.7.99
b657b000 b657d000 r-xp /usr/lib/libefreet_trash.so.1.7.99
b6585000 b6589000 r-xp /usr/lib/libefreet_mime.so.1.7.99
b6592000 b65a8000 r-xp /usr/lib/libefreet.so.1.7.99
b65b2000 b65bb000 r-xp /usr/lib/libedbus.so.1.7.99
b65c3000 b65c8000 r-xp /usr/lib/libecore_fb.so.1.7.99
b65d1000 b662d000 r-xp /usr/lib/libedje.so.1.7.99
b6637000 b664e000 r-xp /usr/lib/libecore_input.so.1.7.99
b6669000 b666e000 r-xp /usr/lib/libecore_file.so.1.7.99
b6676000 b6693000 r-xp /usr/lib/libecore_evas.so.1.7.99
b669c000 b66db000 r-xp /usr/lib/libeina.so.1.7.99
b66e4000 b6793000 r-xp /usr/lib/libevas.so.1.7.99
b67b5000 b67c8000 r-xp /usr/lib/libeet.so.1.7.99
b67d1000 b683b000 r-xp /lib/libm-2.13.so
b6847000 b684e000 r-xp /usr/lib/libutilX.so.1.1.0
b6856000 b685b000 r-xp /usr/lib/libappcore-common.so.1.1
b6863000 b686e000 r-xp /usr/lib/libaul.so.0.1.0
b6877000 b68ab000 r-xp /usr/lib/libgobject-2.0.so.0.3200.3
b68b4000 b68e4000 r-xp /usr/lib/libecore_x.so.1.7.99
b68ed000 b6902000 r-xp /usr/lib/libecore.so.1.7.99
b6919000 b6a39000 r-xp /usr/lib/libelementary.so.1.7.99
b6a4c000 b6a4f000 r-xp /lib/libattr.so.1.1.0
b6a57000 b6a59000 r-xp /usr/lib/libXau.so.6.0.0
b6a61000 b6a67000 r-xp /lib/librt-2.13.so
b6a70000 b6a78000 r-xp /lib/libcrypt-2.13.so
b6aa8000 b6aab000 r-xp /lib/libcap.so.2.21
b6ab3000 b6ab5000 r-xp /usr/lib/libiri.so
b6abd000 b6ad2000 r-xp /usr/lib/libxcb.so.1.1.0
b6ada000 b6ae5000 r-xp /lib/libunwind.so.8.0.1
b6b13000 b6c30000 r-xp /lib/libc-2.13.so
b6c3e000 b6c47000 r-xp /lib/libgcc_s-4.5.3.so.1
b6c4f000 b6c52000 r-xp /usr/lib/libsmack.so.1.0.0
b6c5a000 b6c86000 r-xp /usr/lib/libdbus-1.so.3.7.2
b6c8f000 b6c93000 r-xp /usr/lib/libbundle.so.0.1.22
b6c9b000 b6c9d000 r-xp /lib/libdl-2.13.so
b6ca6000 b6d80000 r-xp /usr/lib/libglib-2.0.so.0.3200.3
b6d89000 b6df3000 r-xp /usr/lib/libsqlite3.so.0.8.6
b6dfd000 b6e0a000 r-xp /usr/lib/libprivilege-control.so.0.0.2
b6e13000 b6ef9000 r-xp /usr/lib/libX11.so.6.3.0
b6f04000 b6f18000 r-xp /lib/libpthread-2.13.so
b6f28000 b6f2c000 r-xp /usr/lib/libappcore-efl.so.1.1
b6f35000 b6f36000 r-xp /usr/lib/libdlog.so.0.0.0
b6f3e000 b6f42000 r-xp /usr/lib/libsys-assert.so
b6f4a000 b6f67000 r-xp /lib/ld-2.13.so
bebaa000 bebcb000 rwxp [stack]
End of Maps Information
Callstack Information (PID:27274)
Call Stack Count: 24
0: Tizen::Io::RemoteMessagePort::SendMessage(Tizen::Base::Collection::IMap const*) + 0x7 (0xb430d1cc) [/usr/lib/osp/libosp-appfw.so] + 0x1a61cc
1: QRMessagePort::SendMessage(Tizen::Base::Collection::IMap const*) + 0x8c (0xb26ac220) [/opt/apps/vd84JCg9vN/bin/QRDemo.exe] + 0x7220
2: Tracker::OnCameraPreviewed(Tizen::Base::ByteBuffer&, unsigned long) + 0x710 (0xb26b1458) [/opt/apps/vd84JCg9vN/bin/QRDemo.exe] + 0xc458
End of Call Stack
Package Information
Package Name: vd84JCg9vN.QRDemo
Package ID : vd84JCg9vN
Version: 1.0.0
Package Type: tpk
App Name: QRDemo
App ID: vd84JCg9vN.QRDemo
Type: Application
Categories: (NULL)
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using Krystals4ObjectLibrary;
using Moritz.Algorithm;
using Moritz.Globals;
using Moritz.Palettes;
using Moritz.Spec;
using Moritz.Symbols;
using Moritz.Xml;
namespace Moritz.Composer
{
public partial class ComposableScore : SvgScore
{
public ComposableScore(string folder, string scoreFolderName, CompositionAlgorithm algorithm, string keywords, string comment, PageFormat pageFormat)
: base(folder, scoreFolderName, keywords, comment, pageFormat)
{
_algorithm = algorithm;
}
/// <summary>
/// Called by the derived class after setting _algorithm and Notator.
/// Returns false if systems cannot be fit vertically on the page. Otherwise true.
/// </summary>
protected bool CreateScore(List<Krystal> krystals, List<Palette> palettes)
{
List<Bar> bars = _algorithm.DoAlgorithm(krystals, palettes);
CheckBars(bars);
this.ScoreData = _algorithm.SetScoreRegionsData(bars);
InsertInitialClefDefs(bars, _pageFormat.InitialClefPerMIDIChannel);
CreateEmptySystems(bars); // one system per bar
bool success = true;
if(_pageFormat.ChordSymbolType != "none") // set by AudioButtonsControl
{
Notator.ConvertVoiceDefsToNoteObjects(this.Systems);
FinalizeSystemStructure(); // adds barlines, joins bars to create systems, etc.
/// The systems do not yet contain Metrics info.
/// The systems are given Metrics inside the following function then justified internally,
/// both horizontally and vertically.
Notator.CreateMetricsAndJustifySystems(this.Systems);
success = CreatePages();
}
CheckSystems(this.Systems);
return success;
}
/// <summary>
/// Inserts a ClefDef at the beginning of each Trk in each bar, taking any cautionaryChordDefs into account.
/// </summary>
/// <param name="bars"></param>
/// <param name="initialClefPerMIDIChannel">The clefs at the beginning of the score.</param>
private void InsertInitialClefDefs(List<Bar> bars, List<string> initialClefPerMIDIChannel)
{
// bars can currently contain cautionary clefs, but no initial clefs
List<string> currentClefs = new List<string>(initialClefPerMIDIChannel);
int nBars = bars.Count;
int nVoiceDefs = bars[0].VoiceDefs.Count;
Debug.Assert(nVoiceDefs == initialClefPerMIDIChannel.Count); // VoiceDefs are both Trks and InputVoiceDefs
foreach (Bar bar in bars)
{
for (int i = 0; i < nVoiceDefs; ++i)
{
ClefDef initialClefDef = new ClefDef(currentClefs[i], 0); // msPos is set later in Notator.ConvertVoiceDefsToNoteObjects()
bar.VoiceDefs[i].Insert(0, initialClefDef);
List<IUniqueDef> iuds = bar.VoiceDefs[i].UniqueDefs;
for (int j = 1; j < iuds.Count; ++j)
{
if (iuds[j] is ClefDef cautionaryClefDef)
{
currentClefs[i] = cautionaryClefDef.ClefType;
}
}
}
}
}
private void CheckBars(List<Bar> bars)
{
string errorString = null;
if(bars.Count == 0)
errorString = "The algorithm has not created any bars!";
else
{
errorString = BasicChecks(bars);
}
if(string.IsNullOrEmpty(errorString))
{
errorString = CheckCCSettings(bars);
}
Debug.Assert(string.IsNullOrEmpty(errorString), errorString);
}
#region private to CheckBars(...)
private string BasicChecks(List<Bar> bars)
{
string errorString = null;
//List<int> visibleLowerVoiceIndices = new List<int>();
//Dictionary<int, string> upperVoiceClefDict = GetUpperVoiceClefDict(bars[0], _pageFormat, /*sets*/ visibleLowerVoiceIndices);
for (int barIndex = 0; barIndex < bars.Count; ++barIndex)
{
Bar bar = bars[barIndex];
IReadOnlyList<VoiceDef> voiceDefs = bar.VoiceDefs;
string barNumber = (barIndex + 1).ToString();
if(voiceDefs.Count == 0)
{
errorString = $"Bar {barNumber} contains no voices.";
break;
}
if(!(voiceDefs[0] is Trk))
{
errorString = "The top (first) voice in every bar must be an output voice.";
break;
}
for(int voiceIndex = 0; voiceIndex < voiceDefs.Count; ++voiceIndex)
{
VoiceDef voiceDef = voiceDefs[voiceIndex];
string voiceNumber = (voiceIndex + 1).ToString();
if(voiceDef.UniqueDefs.Count == 0)
{
errorString = $"Voice number {voiceNumber} in Bar {barNumber} has an empty UniqueDefs list.";
break;
}
}
errorString = CheckThatLowerVoicesHaveNoSmallClefs(voiceDefs);
if(!string.IsNullOrEmpty(errorString))
break;
}
return errorString;
}
private string CheckThatLowerVoicesHaveNoSmallClefs(IReadOnlyList<VoiceDef> voiceDefs)
{
string errorString = "";
List<int> lowerVoiceIndices = GetOutputAndInputLowerVoiceIndices();
foreach(int lowerVoiceIndex in lowerVoiceIndices)
{
var uniqueDefs = voiceDefs[lowerVoiceIndex].UniqueDefs;
foreach(IUniqueDef iud in uniqueDefs)
{
if(iud is ClefDef)
{
errorString = "Small Clefs may not be defined for lower voices on a staff.";
break;
}
}
if(!string.IsNullOrEmpty(errorString))
break;
}
return errorString;
}
private List<int> GetOutputAndInputLowerVoiceIndices()
{
List<int> lowerVoiceIndices = new List<int>();
int voiceIndex = 0;
List<List<byte>> outputChPerStaff = _pageFormat.OutputMIDIChannelsPerStaff;
for(int staffIndex = 0; staffIndex < outputChPerStaff.Count; ++staffIndex)
{
if(outputChPerStaff[staffIndex].Count > 1)
{
voiceIndex++;
lowerVoiceIndices.Add(voiceIndex);
}
voiceIndex++;
}
List<List<byte>> inputChPerStaff = _pageFormat.InputMIDIChannelsPerStaff;
int nStaves = inputChPerStaff.Count + outputChPerStaff.Count;
for(int staffIndex = 0; staffIndex < inputChPerStaff.Count; ++staffIndex)
{
if(inputChPerStaff[staffIndex].Count > 1)
{
voiceIndex++;
lowerVoiceIndices.Add(voiceIndex);
}
voiceIndex++;
}
return lowerVoiceIndices;
}
private int NOutputVoices(List<VoiceDef> bar1)
{
int nOutputVoices = 0;
foreach(VoiceDef voiceDef in bar1)
{
if(voiceDef is Trk)
{
nOutputVoices++;
}
}
return nOutputVoices;
}
private int NInputVoices(List<VoiceDef> bar1)
{
int nInputVoices = 0;
foreach(VoiceDef voiceDef in bar1)
{
if(voiceDef is InputVoiceDef)
{
nInputVoices++;
}
}
return nInputVoices;
}
/// <summary>
/// Synchronous continuous controller settings (ccSettings) are not allowed.
/// </summary>
private string CheckCCSettings(List<Bar> bars)
{
string errorString = null;
List<InputVoiceDef> ivds = new List<InputVoiceDef>();
List<int> ccSettingsMsPositions = new List<int>();
foreach(Bar bar in bars)
{
ccSettingsMsPositions.Clear();
foreach(VoiceDef voice in bar.VoiceDefs)
{
if(voice is InputVoiceDef ivd)
{
foreach(IUniqueDef iud in ivd.UniqueDefs)
{
if(iud is InputChordDef icd && icd.CCSettings != null)
{
int msPos = icd.MsPositionReFirstUD;
if(ccSettingsMsPositions.Contains(msPos))
{
errorString = "\nSynchronous continuous controller settings (ccSettings) are not allowed.";
break;
}
else
{
ccSettingsMsPositions.Add(msPos);
}
}
}
if(!string.IsNullOrEmpty(errorString))
{
break;
}
}
}
if(!string.IsNullOrEmpty(errorString))
{
break;
}
}
return errorString;
}
#endregion
/// <summary>
/// Check that each output track index (top to bottom) is the same as its MidiChannel (error is fatal)
/// </summary>
/// <param name="systems"></param>
private void CheckSystems(List<SvgSystem> systems)
{
var outputTrackMidiChannels = new List<int>();
for(int systemIndex = 0; systemIndex < systems.Count; systemIndex++)
{
var staves = systems[systemIndex].Staves;
outputTrackMidiChannels.Clear();
for (int staffIndex = 0; staffIndex < staves.Count; staffIndex++)
{
var voices = staves[staffIndex].Voices;
foreach(var voice in voices)
{
if(voice is OutputVoice)
{
outputTrackMidiChannels.Add(voice.MidiChannel);
}
else break;
}
}
for (int trackIndex = 0; trackIndex < outputTrackMidiChannels.Count; trackIndex++)
{
Debug.Assert(trackIndex == outputTrackMidiChannels[trackIndex], "Track index and MidiChannel must be identical.");
}
}
}
/// <summary>
/// Creates one System per bar (=list of VoiceDefs) in the argument.
/// The Systems are complete with staves and voices of the correct type:
/// Each InputStaff is allocated parallel (empty) InputVoice fields.
/// Each OutputStaff is allocated parallel (empty) OutputVoice fields.
/// Each Voice has a VoiceDef field that is allocated to the corresponding
/// VoiceDef from the argument.
/// The OutputVoices have MIDIChannels arranged according to _pageFormat.OutputMIDIChannelsPerStaff.
/// The InputVoices have MIDIChannels arranged according to _pageFormat.InputMIDIChannelsPerStaff.
/// OutputVoices are given a midi channel allocated from top to bottom in the printed score.
/// </summary>
public void CreateEmptySystems(List<Bar> bars)
{
foreach(Bar bar in bars)
{
SvgSystem system = new SvgSystem(this);
this.Systems.Add(system);
}
CreateEmptyOutputStaves(bars);
CreateEmptyInputStaves(bars);
}
private void CreateEmptyOutputStaves(List<Bar> bars)
{
int nStaves = _pageFormat.OutputMIDIChannelsPerStaff.Count;
for(int systemIndex = 0; systemIndex < Systems.Count; systemIndex++)
{
SvgSystem system = Systems[systemIndex];
IReadOnlyList<VoiceDef> voiceDefs = bars[systemIndex].VoiceDefs;
#region create visible staves
for(int staffIndex = 0; staffIndex < nStaves; staffIndex++)
{
string staffname = StaffName(systemIndex, staffIndex);
OutputStaff outputStaff = new OutputStaff(system, staffname, _pageFormat.StafflinesPerStaff[staffIndex], _pageFormat.Gap, _pageFormat.StafflineStemStrokeWidth);
List<byte> outputVoiceIndices = _pageFormat.OutputMIDIChannelsPerStaff[staffIndex];
for(int ovIndex = 0; ovIndex < outputVoiceIndices.Count; ++ovIndex)
{
Trk trkDef = voiceDefs[outputVoiceIndices[ovIndex]] as Trk;
Debug.Assert(trkDef != null);
OutputVoice outputVoice = new OutputVoice(outputStaff, trkDef.MidiChannel)
{
VoiceDef = trkDef
};
outputStaff.Voices.Add(outputVoice);
}
SetStemDirections(outputStaff);
system.Staves.Add(outputStaff);
}
#endregion
}
}
private void CreateEmptyInputStaves(List<Bar> bars)
{
int nPrintedOutputStaves = _pageFormat.OutputMIDIChannelsPerStaff.Count;
int nPrintedInputStaves = _pageFormat.InputMIDIChannelsPerStaff.Count;
int nStaffNames = _pageFormat.ShortStaffNames.Count;
for(int i = 0; i < Systems.Count; i++)
{
SvgSystem system = Systems[i];
IReadOnlyList<VoiceDef> voiceDefs = bars[i].VoiceDefs;
for(int staffIndex = 0; staffIndex < nPrintedInputStaves; staffIndex++)
{
int staffNameIndex = nPrintedOutputStaves + staffIndex;
string staffname = StaffName(i, staffNameIndex);
float gap = _pageFormat.Gap * _pageFormat.InputSizeFactor;
float stafflineStemStrokeWidth = _pageFormat.StafflineStemStrokeWidth * _pageFormat.InputSizeFactor;
InputStaff inputStaff = new InputStaff(system, staffname, _pageFormat.StafflinesPerStaff[staffIndex], gap, stafflineStemStrokeWidth);
List<byte> inputVoiceIndices = _pageFormat.InputMIDIChannelsPerStaff[staffIndex];
for(int ivIndex = 0; ivIndex < inputVoiceIndices.Count; ++ivIndex)
{
InputVoiceDef inputVoiceDef = voiceDefs[inputVoiceIndices[ivIndex] + _algorithm.MidiChannelPerOutputVoice.Count] as InputVoiceDef;
Debug.Assert(inputVoiceDef != null);
InputVoice inputVoice = new InputVoice(inputStaff)
{
VoiceDef = inputVoiceDef
};
inputStaff.Voices.Add(inputVoice);
}
SetStemDirections(inputStaff);
system.Staves.Add(inputStaff);
}
}
}
private void AdjustOutputVoiceRefs(List<SvgSystem> systems, List<int> outputMidiChannelSubstitutions)
{
Debug.Assert(_algorithm.MidiChannelPerInputVoice != null);
foreach(var system in systems)
{
foreach(var staff in system.Staves)
{
if(staff is InputStaff inputStaff)
{
foreach(var voice in inputStaff.Voices)
{
if(voice is InputVoice inputVoice)
{
DoMidiChannelSubstitution(inputVoice, outputMidiChannelSubstitutions);
}
}
}
}
}
}
private void DoMidiChannelSubstitution(InputVoice inputVoice, List<int> outputMidiChannelSubstitutions)
{
foreach(var noteObject in inputVoice.NoteObjects)
{
if(noteObject is InputChordSymbol ics)
{
var inputNoteDefs = ics.InputChordDef.InputNoteDefs;
foreach(var inputNoteDef in inputNoteDefs)
{
var noteOnTrkRefs = inputNoteDef.NoteOn.SeqRef.TrkRefs; // each TrkRef has a midiChannel
foreach(var trkRef in noteOnTrkRefs)
{
trkRef.TrkIndex = outputMidiChannelSubstitutions[trkRef.TrkIndex];
}
var noteOffTrkOffs = inputNoteDef.NoteOff.TrkOffs; // trkOffs is a list of trk indices
for(int index = 0; index < noteOffTrkOffs.Count; index++)
{
noteOffTrkOffs[index] = outputMidiChannelSubstitutions[noteOffTrkOffs[index]];
}
}
}
}
}
private string StaffName(int systemIndex, int staffIndex)
{
if(systemIndex == 0)
{
return _pageFormat.LongStaffNames[staffIndex];
}
else
{
return _pageFormat.ShortStaffNames[staffIndex];
}
}
private void SetStemDirections(Staff staff)
{
if(staff.Voices.Count == 1)
{
staff.Voices[0].StemDirection = VerticalDir.none;
}
else
{
Debug.Assert(staff.Voices.Count == 2);
staff.Voices[0].StemDirection = VerticalDir.up;
staff.Voices[1].StemDirection = VerticalDir.down;
}
}
protected CompositionAlgorithm _algorithm = null;
}
}
| |
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Runtime.Serialization;
using System.Windows;
using System.Security;
using System.Diagnostics;
namespace WPCordovaClassLib.Cordova.Commands
{
public class FileTransfer : BaseCommand
{
public class DownloadRequestState
{
// This class stores the State of the request.
public HttpWebRequest request;
public TransferOptions options;
public bool isCancelled;
public DownloadRequestState()
{
request = null;
options = null;
isCancelled = false;
}
}
public class TransferOptions
{
/// File path to upload OR File path to download to
public string FilePath { get; set; }
public string Url { get; set; }
/// Flag to recognize if we should trust every host (only in debug environments)
public bool TrustAllHosts { get; set; }
public string Id { get; set; }
public string Headers { get; set; }
public string CallbackId { get; set; }
public bool ChunkedMode { get; set; }
/// Server address
public string Server { get; set; }
/// File key
public string FileKey { get; set; }
/// File name on the server
public string FileName { get; set; }
/// File Mime type
public string MimeType { get; set; }
/// Additional options
public string Params { get; set; }
public string Method { get; set; }
public TransferOptions()
{
FileKey = "file";
FileName = "image.jpg";
MimeType = "image/jpeg";
}
}
/// <summary>
/// Boundary symbol
/// </summary>
private string Boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
// Error codes
public const int FileNotFoundError = 1;
public const int InvalidUrlError = 2;
public const int ConnectionError = 3;
public const int AbortError = 4; // not really an error, but whatevs
private static Dictionary<string, DownloadRequestState> InProcDownloads = new Dictionary<string,DownloadRequestState>();
/// <summary>
/// Uploading response info
/// </summary>
[DataContract]
public class FileUploadResult
{
/// <summary>
/// Amount of sent bytes
/// </summary>
[DataMember(Name = "bytesSent")]
public long BytesSent { get; set; }
/// <summary>
/// Server response code
/// </summary>
[DataMember(Name = "responseCode")]
public long ResponseCode { get; set; }
/// <summary>
/// Server response
/// </summary>
[DataMember(Name = "response", EmitDefaultValue = false)]
public string Response { get; set; }
/// <summary>
/// Creates FileUploadResult object with response values
/// </summary>
/// <param name="bytesSent">Amount of sent bytes</param>
/// <param name="responseCode">Server response code</param>
/// <param name="response">Server response</param>
public FileUploadResult(long bytesSent, long responseCode, string response)
{
this.BytesSent = bytesSent;
this.ResponseCode = responseCode;
this.Response = response;
}
}
/// <summary>
/// Represents transfer error codes for callback
/// </summary>
[DataContract]
public class FileTransferError
{
/// <summary>
/// Error code
/// </summary>
[DataMember(Name = "code", IsRequired = true)]
public int Code { get; set; }
/// <summary>
/// The source URI
/// </summary>
[DataMember(Name = "source", IsRequired = true)]
public string Source { get; set; }
/// <summary>
/// The target URI
/// </summary>
///
[DataMember(Name = "target", IsRequired = true)]
public string Target { get; set; }
[DataMember(Name = "body", IsRequired = true)]
public string Body { get; set; }
/// <summary>
/// The http status code response from the remote URI
/// </summary>
[DataMember(Name = "http_status", IsRequired = true)]
public int HttpStatus { get; set; }
/// <summary>
/// Creates FileTransferError object
/// </summary>
/// <param name="errorCode">Error code</param>
public FileTransferError(int errorCode)
{
this.Code = errorCode;
this.Source = null;
this.Target = null;
this.HttpStatus = 0;
this.Body = "";
}
public FileTransferError(int errorCode, string source, string target, int status, string body = "")
{
this.Code = errorCode;
this.Source = source;
this.Target = target;
this.HttpStatus = status;
this.Body = body;
}
}
/// <summary>
/// Represents a singular progress event to be passed back to javascript
/// </summary>
[DataContract]
public class FileTransferProgress
{
/// <summary>
/// Is the length of the response known?
/// </summary>
[DataMember(Name = "lengthComputable", IsRequired = true)]
public bool LengthComputable { get; set; }
/// <summary>
/// amount of bytes loaded
/// </summary>
[DataMember(Name = "loaded", IsRequired = true)]
public long BytesLoaded { get; set; }
/// <summary>
/// Total bytes
/// </summary>
[DataMember(Name = "total", IsRequired = false)]
public long BytesTotal { get; set; }
public FileTransferProgress(long bTotal = 0, long bLoaded = 0)
{
LengthComputable = bTotal > 0;
BytesLoaded = bLoaded;
BytesTotal = bTotal;
}
}
/// <summary>
/// Upload options
/// </summary>
//private TransferOptions uploadOptions;
/// <summary>
/// Bytes sent
/// </summary>
private long bytesSent;
/// <summary>
/// sends a file to a server
/// </summary>
/// <param name="options">Upload options</param>
/// exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
public void upload(string options)
{
options = options.Replace("{}", ""); // empty objects screw up the Deserializer
string callbackId = "";
TransferOptions uploadOptions = null;
HttpWebRequest webRequest = null;
try
{
try
{
string[] args = JSON.JsonHelper.Deserialize<string[]>(options);
uploadOptions = new TransferOptions();
uploadOptions.FilePath = args[0];
uploadOptions.Server = args[1];
uploadOptions.FileKey = args[2];
uploadOptions.FileName = args[3];
uploadOptions.MimeType = args[4];
uploadOptions.Params = args[5];
bool trustAll = false;
bool.TryParse(args[6],out trustAll);
uploadOptions.TrustAllHosts = trustAll;
bool doChunked = false;
bool.TryParse(args[7], out doChunked);
uploadOptions.ChunkedMode = doChunked;
//8 : Headers
//9 : id
//10: method
uploadOptions.Headers = args[8];
uploadOptions.Id = args[9];
uploadOptions.Method = args[10];
uploadOptions.CallbackId = callbackId = args[11];
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
Uri serverUri;
try
{
serverUri = new Uri(uploadOptions.Server);
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(InvalidUrlError, uploadOptions.Server, null, 0)));
return;
}
webRequest = (HttpWebRequest)WebRequest.Create(serverUri);
webRequest.ContentType = "multipart/form-data; boundary=" + Boundary;
webRequest.Method = uploadOptions.Method;
if (!string.IsNullOrEmpty(uploadOptions.Headers))
{
Dictionary<string, string> headers = parseHeaders(uploadOptions.Headers);
foreach (string key in headers.Keys)
{
webRequest.Headers[key] = headers[key];
}
}
DownloadRequestState reqState = new DownloadRequestState();
reqState.options = uploadOptions;
reqState.request = webRequest;
InProcDownloads[uploadOptions.Id] = reqState;
webRequest.BeginGetRequestStream(uploadCallback, reqState);
}
catch (Exception /*ex*/)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)),callbackId);
}
}
// example : "{\"Authorization\":\"Basic Y29yZG92YV91c2VyOmNvcmRvdmFfcGFzc3dvcmQ=\"}"
protected Dictionary<string,string> parseHeaders(string jsonHeaders)
{
try
{
Dictionary<string, string> result = new Dictionary<string, string>();
string temp = jsonHeaders.StartsWith("{") ? jsonHeaders.Substring(1) : jsonHeaders;
temp = temp.EndsWith("}") ? temp.Substring(0, temp.Length - 1) : temp;
string[] strHeaders = temp.Split(',');
for (int n = 0; n < strHeaders.Length; n++)
{
// we need to use indexOf in order to WP7 compatible
int splitIndex = strHeaders[n].IndexOf(':');
if (splitIndex > 0)
{
string[] split = new string[2];
split[0] = strHeaders[n].Substring(0, splitIndex);
split[1] = strHeaders[n].Substring(splitIndex + 1);
split[0] = JSON.JsonHelper.Deserialize<string>(split[0]);
split[1] = JSON.JsonHelper.Deserialize<string>(split[1]);
result[split[0]] = split[1];
}
}
return result;
}
catch (Exception)
{
Debug.WriteLine("Failed to parseHeaders from string :: " + jsonHeaders);
}
return null;
}
public void download(string options)
{
TransferOptions downloadOptions = null;
HttpWebRequest webRequest = null;
string callbackId;
try
{
// source, target, trustAllHosts, this._id, headers
string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options);
downloadOptions = new TransferOptions();
downloadOptions.Url = optionStrings[0];
downloadOptions.FilePath = optionStrings[1];
bool trustAll = false;
bool.TryParse(optionStrings[2],out trustAll);
downloadOptions.TrustAllHosts = trustAll;
downloadOptions.Id = optionStrings[3];
downloadOptions.Headers = optionStrings[4];
downloadOptions.CallbackId = callbackId = optionStrings[5];
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
return;
}
try
{
// is the URL a local app file?
if (downloadOptions.Url.StartsWith("x-wmapp0") || downloadOptions.Url.StartsWith("file:"))
{
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
string cleanUrl = downloadOptions.Url.Replace("x-wmapp0:", "").Replace("file:", "").Replace("//","");
// pre-emptively create any directories in the FilePath that do not exist
string directoryName = getDirectoryName(downloadOptions.FilePath);
if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
{
isoFile.CreateDirectory(directoryName);
}
// just copy from one area of iso-store to another ...
if (isoFile.FileExists(downloadOptions.Url))
{
isoFile.CopyFile(downloadOptions.Url, downloadOptions.FilePath);
}
else
{
// need to unpack resource from the dll
Uri uri = new Uri(cleanUrl, UriKind.Relative);
var resource = Application.GetResourceStream(uri);
if (resource != null)
{
// create the file destination
if (!isoFile.FileExists(downloadOptions.FilePath))
{
var destFile = isoFile.CreateFile(downloadOptions.FilePath);
destFile.Close();
}
using (FileStream fileStream = new IsolatedStorageFileStream(downloadOptions.FilePath, FileMode.Open, FileAccess.Write, isoFile))
{
long totalBytes = resource.Stream.Length;
int bytesRead = 0;
using (BinaryReader reader = new BinaryReader(resource.Stream))
{
using (BinaryWriter writer = new BinaryWriter(fileStream))
{
int BUFFER_SIZE = 1024;
byte[] buffer;
while (true)
{
buffer = reader.ReadBytes(BUFFER_SIZE);
// fire a progress event ?
bytesRead += buffer.Length;
if (buffer.Length > 0)
{
writer.Write(buffer);
DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
}
else
{
writer.Close();
reader.Close();
fileStream.Close();
break;
}
}
}
}
}
}
}
}
File.FileEntry entry = File.FileEntry.GetEntry(downloadOptions.FilePath);
if (entry != null)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, File.NOT_FOUND_ERR), callbackId);
}
return;
}
else
{
// otherwise it is web-bound, we will actually download it
//Debug.WriteLine("Creating WebRequest for url : " + downloadOptions.Url);
webRequest = (HttpWebRequest)WebRequest.Create(downloadOptions.Url);
}
}
catch (Exception /*ex*/)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
new FileTransferError(InvalidUrlError, downloadOptions.Url, null, 0)));
return;
}
if (downloadOptions != null && webRequest != null)
{
DownloadRequestState state = new DownloadRequestState();
state.options = downloadOptions;
state.request = webRequest;
InProcDownloads[downloadOptions.Id] = state;
if (!string.IsNullOrEmpty(downloadOptions.Headers))
{
Dictionary<string, string> headers = parseHeaders(downloadOptions.Headers);
foreach (string key in headers.Keys)
{
webRequest.Headers[key] = headers[key];
}
}
try
{
webRequest.BeginGetResponse(new AsyncCallback(downloadCallback), state);
}
catch (WebException)
{
// eat it
}
// dispatch an event for progress ( 0 )
lock (state)
{
if (!state.isCancelled)
{
var plugRes = new PluginResult(PluginResult.Status.OK, new FileTransferProgress());
plugRes.KeepCallback = true;
plugRes.CallbackId = callbackId;
DispatchCommandResult(plugRes, callbackId);
}
}
}
}
public void abort(string options)
{
Debug.WriteLine("Abort :: " + options);
string[] optionStrings = JSON.JsonHelper.Deserialize<string[]>(options);
string id = optionStrings[0];
string callbackId = optionStrings[1];
if (InProcDownloads.ContainsKey(id))
{
DownloadRequestState state = InProcDownloads[id];
if (!state.isCancelled)
{ // prevent multiple callbacks for the same abort
state.isCancelled = true;
if (!state.request.HaveResponse)
{
state.request.Abort();
InProcDownloads.Remove(id);
//callbackId = state.options.CallbackId;
//state = null;
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
new FileTransferError(FileTransfer.AbortError)),
state.options.CallbackId);
}
}
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.IO_EXCEPTION), callbackId); // TODO: is it an IO exception?
}
}
private void DispatchFileTransferProgress(long bytesLoaded, long bytesTotal, string callbackId, bool keepCallback = true)
{
Debug.WriteLine("DispatchFileTransferProgress : " + callbackId);
// send a progress change event
FileTransferProgress progEvent = new FileTransferProgress(bytesTotal);
progEvent.BytesLoaded = bytesLoaded;
PluginResult plugRes = new PluginResult(PluginResult.Status.OK, progEvent);
plugRes.KeepCallback = keepCallback;
plugRes.CallbackId = callbackId;
DispatchCommandResult(plugRes, callbackId);
}
/// <summary>
///
/// </summary>
/// <param name="asynchronousResult"></param>
private void downloadCallback(IAsyncResult asynchronousResult)
{
DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
HttpWebRequest request = reqState.request;
string callbackId = reqState.options.CallbackId;
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
// send a progress change event
DispatchFileTransferProgress(0, response.ContentLength, callbackId);
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
// create any directories in the path that do not exist
string directoryName = getDirectoryName(reqState.options.FilePath);
if (!string.IsNullOrEmpty(directoryName) && !isoFile.DirectoryExists(directoryName))
{
isoFile.CreateDirectory(directoryName);
}
// create the file if not exists
if (!isoFile.FileExists(reqState.options.FilePath))
{
var file = isoFile.CreateFile(reqState.options.FilePath);
file.Close();
}
using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, FileAccess.Write, isoFile))
{
long totalBytes = response.ContentLength;
int bytesRead = 0;
using (BinaryReader reader = new BinaryReader(response.GetResponseStream()))
{
using (BinaryWriter writer = new BinaryWriter(fileStream))
{
int BUFFER_SIZE = 1024;
byte[] buffer;
while (true)
{
buffer = reader.ReadBytes(BUFFER_SIZE);
// fire a progress event ?
bytesRead += buffer.Length;
if (buffer.Length > 0 && !reqState.isCancelled)
{
writer.Write(buffer);
DispatchFileTransferProgress(bytesRead, totalBytes, callbackId);
}
else
{
writer.Close();
reader.Close();
fileStream.Close();
break;
}
System.Threading.Thread.Sleep(1);
}
}
}
}
if (reqState.isCancelled)
{
isoFile.DeleteFile(reqState.options.FilePath);
}
}
if (reqState.isCancelled)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(AbortError)),
callbackId);
}
else
{
File.FileEntry entry = new File.FileEntry(reqState.options.FilePath);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, entry), callbackId);
}
}
catch (IsolatedStorageException)
{
// Trying to write the file somewhere within the IsoStorage.
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)),
callbackId);
}
catch (SecurityException)
{
// Trying to write the file somewhere not allowed.
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError)),
callbackId);
}
catch (WebException webex)
{
// TODO: probably need better work here to properly respond with all http status codes back to JS
// Right now am jumping through hoops just to detect 404.
HttpWebResponse response = (HttpWebResponse)webex.Response;
if ((webex.Status == WebExceptionStatus.ProtocolError && response.StatusCode == HttpStatusCode.NotFound)
|| webex.Status == WebExceptionStatus.UnknownError)
{
// Weird MSFT detection of 404... seriously... just give us the f(*&#$@ status code as a number ffs!!!
// "Numbers for HTTP status codes? Nah.... let's create our own set of enums/structs to abstract that stuff away."
// FACEPALM
// Or just cast it to an int, whiner ... -jm
int statusCode = (int)response.StatusCode;
string body = "";
using (Stream streamResponse = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(streamResponse))
{
body = streamReader.ReadToEnd();
}
}
FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode, body);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError),
callbackId);
}
else
{
lock (reqState)
{
if (!reqState.isCancelled)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
new FileTransferError(ConnectionError)),
callbackId);
}
else
{
Debug.WriteLine("It happened");
}
}
}
}
catch (Exception)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
new FileTransferError(FileNotFoundError)),
callbackId);
}
//System.Threading.Thread.Sleep(1000);
if (InProcDownloads.ContainsKey(reqState.options.Id))
{
InProcDownloads.Remove(reqState.options.Id);
}
}
/// <summary>
/// Read file from Isolated Storage and sends it to server
/// </summary>
/// <param name="asynchronousResult"></param>
private void uploadCallback(IAsyncResult asynchronousResult)
{
DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
HttpWebRequest webRequest = reqState.request;
string callbackId = reqState.options.CallbackId;
try
{
using (Stream requestStream = (webRequest.EndGetRequestStream(asynchronousResult)))
{
string lineStart = "--";
string lineEnd = Environment.NewLine;
byte[] boundaryBytes = System.Text.Encoding.UTF8.GetBytes(lineStart + Boundary + lineEnd);
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"" + lineEnd + lineEnd + "{1}" + lineEnd;
if (!string.IsNullOrEmpty(reqState.options.Params))
{
Dictionary<string, string> paramMap = parseHeaders(reqState.options.Params);
foreach (string key in paramMap.Keys)
{
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
string formItem = string.Format(formdataTemplate, key, paramMap[key]);
byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(formItem);
requestStream.Write(formItemBytes, 0, formItemBytes.Length);
}
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
}
using (IsolatedStorageFile isoFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoFile.FileExists(reqState.options.FilePath))
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(FileNotFoundError, reqState.options.Server, reqState.options.FilePath, 0)));
return;
}
byte[] endRequest = System.Text.Encoding.UTF8.GetBytes(lineEnd + lineStart + Boundary + lineStart + lineEnd);
long totalBytesToSend = 0;
using (FileStream fileStream = new IsolatedStorageFileStream(reqState.options.FilePath, FileMode.Open, isoFile))
{
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + lineEnd + "Content-Type: {2}" + lineEnd + lineEnd;
string header = string.Format(headerTemplate, reqState.options.FileKey, reqState.options.FileName, reqState.options.MimeType);
byte[] headerBytes = System.Text.Encoding.UTF8.GetBytes(header);
byte[] buffer = new byte[4096];
int bytesRead = 0;
//sent bytes needs to be reseted before new upload
bytesSent = 0;
totalBytesToSend = fileStream.Length;
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
requestStream.Write(headerBytes, 0, headerBytes.Length);
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
if (!reqState.isCancelled)
{
requestStream.Write(buffer, 0, bytesRead);
bytesSent += bytesRead;
DispatchFileTransferProgress(bytesSent, totalBytesToSend, callbackId);
System.Threading.Thread.Sleep(1);
}
else
{
throw new Exception("UploadCancelledException");
}
}
}
requestStream.Write(endRequest, 0, endRequest.Length);
}
}
// webRequest
webRequest.BeginGetResponse(ReadCallback, reqState);
}
catch (Exception /*ex*/)
{
if (!reqState.isCancelled)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, new FileTransferError(ConnectionError)), callbackId);
}
}
}
/// <summary>
/// Reads response into FileUploadResult
/// </summary>
/// <param name="asynchronousResult"></param>
private void ReadCallback(IAsyncResult asynchronousResult)
{
DownloadRequestState reqState = (DownloadRequestState)asynchronousResult.AsyncState;
try
{
HttpWebRequest webRequest = reqState.request;
string callbackId = reqState.options.CallbackId;
if (InProcDownloads.ContainsKey(reqState.options.Id))
{
InProcDownloads.Remove(reqState.options.Id);
}
using (HttpWebResponse response = (HttpWebResponse)webRequest.EndGetResponse(asynchronousResult))
{
using (Stream streamResponse = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(streamResponse))
{
string responseString = streamReader.ReadToEnd();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, new FileUploadResult(bytesSent, (long)response.StatusCode, responseString)));
});
}
}
}
}
catch (WebException webex)
{
// TODO: probably need better work here to properly respond with all http status codes back to JS
// Right now am jumping through hoops just to detect 404.
if ((webex.Status == WebExceptionStatus.ProtocolError && ((HttpWebResponse)webex.Response).StatusCode == HttpStatusCode.NotFound)
|| webex.Status == WebExceptionStatus.UnknownError)
{
int statusCode = (int)((HttpWebResponse)webex.Response).StatusCode;
FileTransferError ftError = new FileTransferError(ConnectionError, null, null, statusCode);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, ftError), reqState.options.CallbackId);
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR,
new FileTransferError(ConnectionError)),
reqState.options.CallbackId);
}
}
catch (Exception /*ex*/)
{
FileTransferError transferError = new FileTransferError(ConnectionError, reqState.options.Server, reqState.options.FilePath, 403);
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, transferError), reqState.options.CallbackId);
}
}
// Gets the full path without the filename
private string getDirectoryName(String filePath)
{
string directoryName;
try
{
directoryName = filePath.Substring(0, filePath.LastIndexOf('/'));
}
catch
{
directoryName = "";
}
return directoryName;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace YAF.Lucene.Net.Search.Spans
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = YAF.Lucene.Net.Index.AtomicReaderContext;
using IBits = YAF.Lucene.Net.Util.IBits;
using IndexReader = YAF.Lucene.Net.Index.IndexReader;
using Term = YAF.Lucene.Net.Index.Term;
using TermContext = YAF.Lucene.Net.Index.TermContext;
/// <summary>
/// Wraps any <see cref="MultiTermQuery"/> as a <see cref="SpanQuery"/>,
/// so it can be nested within other <see cref="SpanQuery"/> classes.
/// <para/>
/// The query is rewritten by default to a <see cref="SpanOrQuery"/> containing
/// the expanded terms, but this can be customized.
/// <para/>
/// Example:
/// <code>
/// WildcardQuery wildcard = new WildcardQuery(new Term("field", "bro?n"));
/// SpanQuery spanWildcard = new SpanMultiTermQueryWrapper<WildcardQuery>(wildcard);
/// // do something with spanWildcard, such as use it in a SpanFirstQuery
/// </code>
/// </summary>
public class SpanMultiTermQueryWrapper<Q> : SpanQuery, ISpanMultiTermQueryWrapper where Q : MultiTermQuery
{
protected readonly Q m_query;
/// <summary>
/// Create a new <see cref="SpanMultiTermQueryWrapper{Q}"/>.
/// </summary>
/// <param name="query"> Query to wrap.
/// <para/>
/// NOTE: This will set <see cref="MultiTermQuery.MultiTermRewriteMethod"/>
/// on the wrapped <paramref name="query"/>, changing its rewrite method to a suitable one for spans.
/// Be sure to not change the rewrite method on the wrapped query afterwards! Doing so will
/// throw <see cref="NotSupportedException"/> on rewriting this query! </param>
public SpanMultiTermQueryWrapper(Q query)
{
this.m_query = query;
MultiTermQuery.RewriteMethod method = this.m_query.MultiTermRewriteMethod;
if (method is ITopTermsRewrite topTermsRewrite)
{
MultiTermRewriteMethod = new TopTermsSpanBooleanQueryRewrite(topTermsRewrite.Count);
}
else
{
MultiTermRewriteMethod = SCORING_SPAN_QUERY_REWRITE;
}
}
/// <summary>
/// Expert: Gets or Sets the rewrite method. This only makes sense
/// to be a span rewrite method.
/// </summary>
public SpanRewriteMethod MultiTermRewriteMethod
{
get
{
MultiTermQuery.RewriteMethod m = m_query.MultiTermRewriteMethod;
if (!(m is SpanRewriteMethod spanRewriteMethod))
{
throw UnsupportedOperationException.Create("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod.");
}
return spanRewriteMethod;
}
set => m_query.MultiTermRewriteMethod = value;
}
public override Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts)
{
throw UnsupportedOperationException.Create("Query should have been rewritten");
}
public override string Field => m_query.Field;
/// <summary>
/// Returns the wrapped query </summary>
public virtual Query WrappedQuery => m_query;
public override string ToString(string field)
{
StringBuilder builder = new StringBuilder();
builder.Append("SpanMultiTermQueryWrapper(");
builder.Append(m_query.ToString(field));
builder.Append(")");
if (Boost != 1F)
{
builder.Append('^');
builder.Append(Boost);
}
return builder.ToString();
}
public override Query Rewrite(IndexReader reader)
{
Query q = m_query.Rewrite(reader);
if (!(q is SpanQuery))
{
throw UnsupportedOperationException.Create("You can only use SpanMultiTermQueryWrapper with a suitable SpanRewriteMethod.");
}
q.Boost = q.Boost * Boost; // multiply boost
return q;
}
public override int GetHashCode()
{
const int prime = 31;
int result = base.GetHashCode();
result = prime * result + m_query.GetHashCode();
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (!base.Equals(obj))
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
var other = (SpanMultiTermQueryWrapper<Q>)obj;
if (!m_query.Equals(other.m_query))
{
return false;
}
return true;
}
// LUCENENET NOTE: Moved SpanRewriteMethod outside of this class
/// <summary>
/// A rewrite method that first translates each term into a <see cref="SpanTermQuery"/> in a
/// <see cref="Occur.SHOULD"/> clause in a <see cref="BooleanQuery"/>, and keeps the
/// scores as computed by the query.
/// </summary>
/// <seealso cref="MultiTermRewriteMethod"/>
public static readonly SpanRewriteMethod SCORING_SPAN_QUERY_REWRITE = new SpanRewriteMethodAnonymousClass();
private class SpanRewriteMethodAnonymousClass : SpanRewriteMethod
{
public SpanRewriteMethodAnonymousClass()
{
}
private readonly ScoringRewrite<SpanOrQuery> @delegate = new ScoringRewriteAnonymousClass();
private class ScoringRewriteAnonymousClass : ScoringRewrite<SpanOrQuery>
{
public ScoringRewriteAnonymousClass()
{
}
protected override SpanOrQuery GetTopLevelQuery()
{
return new SpanOrQuery();
}
protected override void CheckMaxClauseCount(int count)
{
// we accept all terms as SpanOrQuery has no limits
}
protected override void AddClause(SpanOrQuery topLevel, Term term, int docCount, float boost, TermContext states)
{
// TODO: would be nice to not lose term-state here.
// we could add a hack option to SpanOrQuery, but the hack would only work if this is the top-level Span
// (if you put this thing in another span query, it would extractTerms/double-seek anyway)
SpanTermQuery q = new SpanTermQuery(term);
q.Boost = boost;
topLevel.AddClause(q);
}
}
public override Query Rewrite(IndexReader reader, MultiTermQuery query)
{
return @delegate.Rewrite(reader, query);
}
}
/// <summary>
/// A rewrite method that first translates each term into a <see cref="SpanTermQuery"/> in a
/// <see cref="Occur.SHOULD"/> clause in a <see cref="BooleanQuery"/>, and keeps the
/// scores as computed by the query.
///
/// <para/>
/// This rewrite method only uses the top scoring terms so it will not overflow
/// the boolean max clause count.
/// </summary>
/// <seealso cref="MultiTermRewriteMethod"/>
public sealed class TopTermsSpanBooleanQueryRewrite : SpanRewriteMethod
{
private readonly TopTermsRewrite<SpanOrQuery> @delegate;
/// <summary>
/// Create a <see cref="TopTermsSpanBooleanQueryRewrite"/> for
/// at most <paramref name="size"/> terms.
/// </summary>
public TopTermsSpanBooleanQueryRewrite(int size)
{
@delegate = new TopTermsRewriteAnonymousClass(size);
}
private class TopTermsRewriteAnonymousClass : TopTermsRewrite<SpanOrQuery>
{
public TopTermsRewriteAnonymousClass(int size)
: base(size)
{
}
protected override int MaxSize => int.MaxValue;
protected override SpanOrQuery GetTopLevelQuery()
{
return new SpanOrQuery();
}
protected override void AddClause(SpanOrQuery topLevel, Term term, int docFreq, float boost, TermContext states)
{
SpanTermQuery q = new SpanTermQuery(term);
q.Boost = boost;
topLevel.AddClause(q);
}
}
/// <summary>
/// return the maximum priority queue size.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
public int Count => @delegate.Count;
public override Query Rewrite(IndexReader reader, MultiTermQuery query)
{
return @delegate.Rewrite(reader, query);
}
public override int GetHashCode()
{
return 31 * @delegate.GetHashCode();
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (obj is null)
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
TopTermsSpanBooleanQueryRewrite other = (TopTermsSpanBooleanQueryRewrite)obj;
return @delegate.Equals(other.@delegate);
}
}
}
/// <summary>
/// Abstract class that defines how the query is rewritten. </summary>
// LUCENENET specific - moved this class outside of SpanMultiTermQueryWrapper<Q>
public abstract class SpanRewriteMethod : MultiTermQuery.RewriteMethod
{
public override abstract Query Rewrite(IndexReader reader, MultiTermQuery query);
}
/// <summary>
/// LUCENENET specific interface for referring to/identifying a <see cref="Search.Spans.SpanMultiTermQueryWrapper{Q}"/> without
/// referring to its generic closing type.
/// </summary>
public interface ISpanMultiTermQueryWrapper
{
/// <summary>
/// Expert: Gets or Sets the rewrite method. This only makes sense
/// to be a span rewrite method.
/// </summary>
SpanRewriteMethod MultiTermRewriteMethod { get; }
Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts);
string Field { get; }
/// <summary>
/// Returns the wrapped query </summary>
Query WrappedQuery { get; }
Query Rewrite(IndexReader reader);
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using SQLRepositoryAsync.Data;
using SQLRepositoryAsync.Data.POCO;
using SQLRepositoryAsync.Data.Repository;
using Xunit;
using Newtonsoft.Json;
namespace Regression.Test
{
[Collection("Test Collection")]
public class QueryTests
{
private SetupFixture fixture;
private ILogger logger;
private AppSettingsConfiguration settings;
private DBContext dbc;
//Fixture instantiated at the beginning of all the tests in this class and passed to constructor
public QueryTests(SetupFixture f)
{
fixture = f;
logger = f.Logger;
settings = f.Settings;
}
[Fact]
public async Task ConnectionTest()
{
Assert.NotNull(dbc = new DBContext(settings.Database.ConnectionString, logger));
Assert.True(await dbc.Open());
Assert.True(dbc.Connection.State == ConnectionState.Open);
dbc.Close();
}
[Fact]
public async Task FindAllTest()
{
Assert.NotNull(dbc = new DBContext(settings.Database.ConnectionString, logger));
ContactRepository contactRepos = new ContactRepository(settings, logger, dbc);
CityRepository cityRepos = new CityRepository(settings, logger, dbc);
StateRepository stateRepos = new StateRepository(settings, logger, dbc);
ICollection<Contact> contacts = await contactRepos.FindAll();
Assert.NotEmpty(contacts);
ICollection<City> cities = await cityRepos.FindAll();
Assert.NotEmpty(cities);
ICollection<State> states = await stateRepos.FindAll();
Assert.NotEmpty(states);
dbc.Close();
}
[Fact]
public async Task FindAllPagedTest()
{
Assert.NotNull(dbc = new DBContext(settings.Database.ConnectionString, logger));
ContactRepository contactRepos = new ContactRepository(settings, logger, dbc);
CityRepository cityRepos = new CityRepository(settings, logger, dbc);
StateRepository stateRepos = new StateRepository(settings, logger, dbc);
IPager<Contact> contacts = await contactRepos.FindAll(new Pager<Contact>() { PageNbr = 2, PageSize = 5 });
Assert.NotNull(contacts);
Assert.True(contacts.RowCount > 0);
Assert.NotNull(contacts.Entities);
IPager<City> cities = await cityRepos.FindAll(new Pager<City>() { PageNbr = 2, PageSize = 5 });
Assert.NotNull(cities.Entities);
Assert.True(cities.RowCount > 0);
Assert.NotNull(cities.Entities);
IPager<State> states = await stateRepos.FindAll(new Pager<State>() { PageNbr = 2, PageSize = 5 });
Assert.NotNull(states.Entities);
Assert.True(states.RowCount > 0);
Assert.NotNull(states.Entities);
dbc.Close();
}
[Fact]
public async Task FindAllViewTest()
{
Assert.NotNull(dbc = new DBContext(settings.Database.ConnectionString, logger));
ContactRepository contactRepos = new ContactRepository(settings, logger, dbc);
CityRepository cityRepos = new CityRepository(settings, logger, dbc);
ICollection<Contact> contacts = await contactRepos.FindAllView();
Assert.NotEmpty(contacts);
Assert.NotNull(contacts.FirstOrDefault().City);
Assert.NotNull(contacts.FirstOrDefault().City.State);
ICollection<City> cities = await cityRepos.FindAllView();
Assert.NotEmpty(cities);
Assert.NotNull(cities.FirstOrDefault().State);
dbc.Close();
}
[Fact]
public async Task FindAllViewPagedTest()
{
Assert.NotNull(dbc = new DBContext(settings.Database.ConnectionString, logger));
ContactRepository contactRepos = new ContactRepository(settings, logger, dbc);
CityRepository cityRepos = new CityRepository(settings, logger, dbc);
IPager<Contact> contacts = await contactRepos.FindAllView(new Pager<Contact>() { PageNbr = 2, PageSize = 5 });
Assert.NotEmpty(contacts.Entities);
Assert.True(contacts.RowCount > 0);
Assert.NotNull(contacts.Entities);
Assert.NotNull(contacts.Entities.FirstOrDefault().City);
Assert.NotNull(contacts.Entities.FirstOrDefault().City.State);
IPager<City> cities = await cityRepos.FindAllView(new Pager<City>() { PageNbr = 2, PageSize = 5 });
Assert.NotEmpty(cities.Entities);
Assert.True(cities.RowCount > 0);
Assert.NotNull(cities.Entities);
Assert.NotNull(cities.Entities.FirstOrDefault().State);
dbc.Close();
}
[Fact]
public async Task FindByPKAlphaTest()
{
Assert.NotNull(dbc = new DBContext(settings.Database.ConnectionString, logger));
StateRepository repos = new StateRepository(settings, logger, dbc);
State state = await repos.FindByPK(new PrimaryKey() { Key = "FL" });
Assert.NotNull(state);
dbc.Close();
}
[Fact]
public async Task FindByPKNumericTest()
{
Assert.NotNull(dbc = new DBContext(settings.Database.ConnectionString, logger));
ContactRepository repos = new ContactRepository(settings, logger, dbc);
Contact contact = await repos.FindByPK(new PrimaryKey() { Key =1 });
Assert.NotNull(contact);
}
[Fact]
public async Task FindByCompositeKeyTest()
{
Assert.NotNull(dbc = new DBContext(settings.Database.ConnectionString, logger));
ProjectContactRepository repos = new ProjectContactRepository(settings, logger, dbc);
int projectId = 1;
int contactId = 2;
ProjectContact pc = await repos.FindByPK(new PrimaryKey() { CompositeKey = new object[] { projectId, contactId }, IsComposite = true });
Assert.NotNull(pc);
}
[Fact]
public async Task FindViewByPKTest()
{
Assert.NotNull(dbc = new DBContext(settings.Database.ConnectionString, logger));
ContactRepository repos = new ContactRepository(settings, logger, dbc);
Contact contact = await repos.FindViewByPK(new PrimaryKey() { Key = 1 });
Assert.NotNull(contact);
Assert.True(contact.Id == 1);
Assert.NotNull(contact.City);
Assert.NotNull(contact.City.State);
dbc.Close();
}
[Fact]
public async Task ExecNonQueryTest()
{
Assert.NotNull(dbc = new DBContext(settings.Database.ConnectionString, logger));
ContactRepository repos = new ContactRepository(settings, logger, dbc);
Assert.True(await repos.NonQuery() > 1);
dbc.Close();
}
[Fact]
public async Task ExecStoredProcTest()
{
Assert.NotNull(dbc = new DBContext(settings.Database.ConnectionString, logger));
ContactRepository contactRepos = new ContactRepository(settings, logger, dbc);
Assert.True(await contactRepos.StoredProc(1) == 1);
dbc.Close();
}
[Fact]
public async Task ExecJSONQueryTest()
{
Stats stats = null;
StatsView statsView = null;
Assert.NotNull(dbc = new DBContext(settings.Database.ConnectionString, logger));
StatsRepository statsRepos = new StatsRepository(settings, logger, dbc);
stats = await statsRepos.GetStats();
statsView = JsonConvert.DeserializeObject<StatsView>(stats.Result);
Assert.NotNull(statsView);
Assert.True(statsView.TotalContacts > 0);
dbc.Close();
}
}
}
| |
/*
* CookieCollection.cs
*
* This code is derived from System.Net.CookieCollection.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2004,2009 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* Authors:
* - Lawrence Pit <loz@cable.a2000.nl>
* - Gonzalo Paniagua Javier <gonzalo@ximian.com>
* - Sebastien Pouliot <sebastien@ximian.com>
*/
namespace WebSocketSharp.Net
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
/// <summary>
/// Provides a collection container for instances of the <see cref="Cookie"/> class.
/// </summary>
[Serializable]
public sealed class CookieCollection : ICollection<Cookie>
{
private readonly List<Cookie> _list;
private object _sync;
/// <summary>
/// Initializes a new instance of the <see cref="CookieCollection"/> class.
/// </summary>
public CookieCollection()
{
_list = new List<Cookie>();
}
internal IEnumerable<Cookie> Sorted
{
get
{
var list = new List<Cookie>(_list);
if (list.Count > 1)
{
list.Sort(CompareCookieWithinSorted);
}
return list;
}
}
public bool Remove(Cookie item)
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the number of cookies in the collection.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of cookies in the collection.
/// </value>
public int Count => _list.Count;
/// <summary>
/// Gets a value indicating whether the collection is read-only.
/// </summary>
/// <value>
/// <c>true</c> if the collection is read-only; otherwise, <c>false</c>.
/// The default value is <c>true</c>.
/// </value>
public bool IsReadOnly => true;
/// <summary>
/// Gets the <see cref="Cookie"/> at the specified <paramref name="index"/> from
/// the collection.
/// </summary>
/// <value>
/// A <see cref="Cookie"/> at the specified <paramref name="index"/> in the collection.
/// </value>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index of the <see cref="Cookie"/>
/// to find.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of allowable range of indexes for the collection.
/// </exception>
public Cookie this[int index]
{
get
{
if (index < 0 || index >= _list.Count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
return _list[index];
}
}
/// <summary>
/// Gets the <see cref="Cookie"/> with the specified <paramref name="name"/> from
/// the collection.
/// </summary>
/// <value>
/// A <see cref="Cookie"/> with the specified <paramref name="name"/> in the collection.
/// </value>
/// <param name="name">
/// A <see cref="string"/> that represents the name of the <see cref="Cookie"/> to find.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name"/> is <see langword="null"/>.
/// </exception>
public Cookie this[string name]
{
get
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return Sorted.FirstOrDefault(cookie => cookie.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
}
}
/// <summary>
/// Gets an object used to synchronize access to the collection.
/// </summary>
/// <value>
/// An <see cref="Object"/> used to synchronize access to the collection.
/// </value>
public object SyncRoot => _sync ?? (_sync = ((ICollection)_list).SyncRoot);
private static int CompareCookieWithinSorted(Cookie x, Cookie y)
{
int ret;
return (ret = x.Version - y.Version) != 0
? ret
: (ret = x.Name.CompareTo(y.Name)) != 0
? ret
: y.Path.Length - x.Path.Length;
}
private static CookieCollection ParseRequest(string value)
{
var cookies = new CookieCollection();
Cookie cookie = null;
var ver = 0;
var pairs = SplitCookieHeaderValue(value);
foreach (string pair in pairs.Select(t => t.Trim()))
{
if (pair.Length == 0)
{
continue;
}
if (pair.StartsWith("$version", StringComparison.InvariantCultureIgnoreCase))
{
ver = int.Parse(pair.GetValue('=', true));
}
else if (pair.StartsWith("$path", StringComparison.InvariantCultureIgnoreCase))
{
if (cookie != null)
{
cookie.Path = pair.GetValue('=');
}
}
else if (pair.StartsWith("$domain", StringComparison.InvariantCultureIgnoreCase))
{
if (cookie != null)
{
cookie.Domain = pair.GetValue('=');
}
}
else if (pair.StartsWith("$port", StringComparison.InvariantCultureIgnoreCase))
{
var port = pair.Equals("$port", StringComparison.InvariantCultureIgnoreCase)
? "\"\""
: pair.GetValue('=');
if (cookie != null)
{
cookie.Port = port;
}
}
else
{
if (cookie != null)
{
cookies.Add(cookie);
}
string name;
string val = string.Empty;
var pos = pair.IndexOf('=');
if (pos == -1)
{
name = pair;
}
else if (pos == pair.Length - 1)
{
name = pair.Substring(0, pos).TrimEnd(' ');
}
else
{
name = pair.Substring(0, pos).TrimEnd(' ');
val = pair.Substring(pos + 1).TrimStart(' ');
}
cookie = new Cookie(name, val);
if (ver != 0)
{
cookie.Version = ver;
}
}
}
if (cookie != null)
{
cookies.Add(cookie);
}
return cookies;
}
private static CookieCollection ParseResponse(string value)
{
var cookies = new CookieCollection();
Cookie cookie = null;
var pairs = SplitCookieHeaderValue(value);
for (var i = 0; i < pairs.Length; i++)
{
var pair = pairs[i].Trim();
if (pair.Length == 0)
continue;
if (pair.StartsWith("version", StringComparison.InvariantCultureIgnoreCase))
{
if (cookie != null)
cookie.Version = Int32.Parse(pair.GetValue('=', true));
}
else if (pair.StartsWith("expires", StringComparison.InvariantCultureIgnoreCase))
{
var buff = new StringBuilder(pair.GetValue('='), 32);
if (i < pairs.Length - 1)
buff.AppendFormat(", {0}", pairs[++i].Trim());
DateTime expires;
if (!DateTime.TryParseExact(
buff.ToString(),
new[] { "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'", "r" },
CultureInfo.CreateSpecificCulture("en-US"),
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal,
out expires))
expires = DateTime.Now;
if (cookie != null && cookie.Expires == DateTime.MinValue)
cookie.Expires = expires.ToLocalTime();
}
else if (pair.StartsWith("max-age", StringComparison.InvariantCultureIgnoreCase))
{
var max = Int32.Parse(pair.GetValue('=', true));
var expires = DateTime.Now.AddSeconds(max);
if (cookie != null)
cookie.Expires = expires;
}
else if (pair.StartsWith("path", StringComparison.InvariantCultureIgnoreCase))
{
if (cookie != null)
cookie.Path = pair.GetValue('=');
}
else if (pair.StartsWith("domain", StringComparison.InvariantCultureIgnoreCase))
{
if (cookie != null)
cookie.Domain = pair.GetValue('=');
}
else if (pair.StartsWith("port", StringComparison.InvariantCultureIgnoreCase))
{
var port = pair.Equals("port", StringComparison.InvariantCultureIgnoreCase)
? "\"\""
: pair.GetValue('=');
if (cookie != null)
cookie.Port = port;
}
else if (pair.StartsWith("comment", StringComparison.InvariantCultureIgnoreCase))
{
if (cookie != null)
cookie.Comment = pair.GetValue('=').UrlDecode();
}
else if (pair.StartsWith("commenturl", StringComparison.InvariantCultureIgnoreCase))
{
if (cookie != null)
cookie.CommentUri = pair.GetValue('=', true).ToUri();
}
else if (pair.StartsWith("discard", StringComparison.InvariantCultureIgnoreCase))
{
if (cookie != null)
cookie.Discard = true;
}
else if (pair.StartsWith("secure", StringComparison.InvariantCultureIgnoreCase))
{
if (cookie != null)
cookie.Secure = true;
}
else if (pair.StartsWith("httponly", StringComparison.InvariantCultureIgnoreCase))
{
if (cookie != null)
cookie.HttpOnly = true;
}
else
{
if (cookie != null)
cookies.Add(cookie);
string name;
string val = string.Empty;
var pos = pair.IndexOf('=');
if (pos == -1)
{
name = pair;
}
else if (pos == pair.Length - 1)
{
name = pair.Substring(0, pos).TrimEnd(' ');
}
else
{
name = pair.Substring(0, pos).TrimEnd(' ');
val = pair.Substring(pos + 1).TrimStart(' ');
}
cookie = new Cookie(name, val);
}
}
if (cookie != null)
cookies.Add(cookie);
return cookies;
}
private int SearchCookie(Cookie cookie)
{
var name = cookie.Name;
var path = cookie.Path;
var domain = cookie.Domain;
var ver = cookie.Version;
for (var i = _list.Count - 1; i >= 0; i--)
{
var c = _list[i];
if (c.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase) &&
c.Path.Equals(path, StringComparison.InvariantCulture) &&
c.Domain.Equals(domain, StringComparison.InvariantCultureIgnoreCase) &&
c.Version == ver)
return i;
}
return -1;
}
private static string[] SplitCookieHeaderValue(string value)
{
return new List<string>(value.SplitHeaderValue(',', ';')).ToArray();
}
internal static CookieCollection Parse(string value, bool response)
{
return response
? ParseResponse(value)
: ParseRequest(value);
}
internal void SetOrRemove(Cookie cookie)
{
var pos = SearchCookie(cookie);
if (pos == -1)
{
if (!cookie.Expired)
{
_list.Add(cookie);
}
return;
}
if (!cookie.Expired)
{
_list[pos] = cookie;
return;
}
_list.RemoveAt(pos);
}
internal void SetOrRemove(CookieCollection cookies)
{
foreach (Cookie cookie in cookies)
SetOrRemove(cookie);
}
/// <summary>
/// Adds the specified <paramref name="cookie"/> to the collection.
/// </summary>
/// <param name="cookie">
/// A <see cref="Cookie"/> to add.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="cookie"/> is <see langword="null"/>.
/// </exception>
public void Add(Cookie cookie)
{
if (cookie == null)
throw new ArgumentNullException("cookie");
var pos = SearchCookie(cookie);
if (pos == -1)
{
_list.Add(cookie);
return;
}
_list[pos] = cookie;
}
public void Clear()
{
_list.Clear();
}
public bool Contains(Cookie item)
{
return _list.Contains(item);
}
/// <summary>
/// Copies the elements of the collection to the specified array of <see cref="Cookie"/>,
/// starting at the specified <paramref name="index"/> in the <paramref name="array"/>.
/// </summary>
/// <param name="array">
/// An array of <see cref="Cookie"/> that represents the destination of the elements
/// copied from the collection.
/// </param>
/// <param name="index">
/// An <see cref="int"/> that represents the zero-based index in <paramref name="array"/>
/// at which copying begins.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="array"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than zero.
/// </exception>
/// <exception cref="ArgumentException">
/// The number of elements in the collection is greater than the available space from
/// <paramref name="index"/> to the end of the destination <paramref name="array"/>.
/// </exception>
public void CopyTo(Cookie[] array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
if (index < 0)
throw new ArgumentOutOfRangeException("index", "Less than zero.");
if (array.Length - index < _list.Count)
throw new ArgumentException(
"The number of elements in this collection is greater than the available space of the destination array.");
_list.CopyTo(array, index);
}
IEnumerator<Cookie> IEnumerable<Cookie>.GetEnumerator()
{
return _list.GetEnumerator();
}
/// <summary>
/// Gets the enumerator used to iterate through the collection.
/// </summary>
/// <returns>
/// An <see cref="IEnumerator"/> instance used to iterate through the collection.
/// </returns>
public IEnumerator GetEnumerator()
{
return _list.GetEnumerator();
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System.Collections.Generic;
using System.Runtime;
using System.Threading;
enum OpcodeID
{
NoOp,
SubExpr,
// Flow opcodes
Branch,
JumpIfNot,
Filter,
Function,
XsltFunction,
XsltInternalFunction,
Cast,
QueryTree,
BlockEnd,
SubRoutine,
// Set Opcodes
Ordinal,
LiteralOrdinal,
Empty,
Union,
Merge,
// Boolean opcodes
ApplyBoolean,
StartBoolean,
EndBoolean,
// Relational opcodes
Relation,
StringEquals,
NumberEquals,
StringEqualsBranch,
NumberEqualsBranch,
NumberRelation,
NumberInterval,
NumberIntervalBranch,
// Select/Node Operators
Select,
InitialSelect,
SelectRoot,
// Stack operators
PushXsltVariable,
PushBool,
PushString,
PushDouble,
PushContextNode,
PushNodeSequence,
PushPosition,
PopSequenceToValueStack,
PopSequenceToSequenceStack,
PopContextNodes,
PushContextCopy,
PopValueFrame,
// Math opcode
Plus,
Minus,
Multiply,
Divide,
Mod,
Negate,
// Specialized String operators
StringPrefix,
StringPrefixBranch,
// Results
MatchAlways,
MatchResult,
MatchFilterResult,
MatchMultipleResult,
MatchSingleFx,
QuerySingleFx,
QueryResult,
QueryMultipleResult
}
enum OpcodeFlags
{
None = 0x00000000,
Single = 0x00000001,
Multiple = 0x00000002,
Branch = 0x00000004,
Result = 0x00000008,
Jump = 0x00000010,
Literal = 0x00000020,
Select = 0x00000040,
Deleted = 0x00000080,
InConditional = 0x00000100,
NoContextCopy = 0x00000200,
InitialSelect = 0x00000400,
CompressableSelect = 0x00000800,
Fx = 0x00001000
}
abstract class Opcode
{
protected OpcodeFlags flags;
protected Opcode next;
OpcodeID opcodeID;
protected Opcode prev;
#if DEBUG
// debugging aid. Because C# references do not have displayble numeric values, hard to deduce the
// graph structure to see what opcode is connected to what
static long nextUniqueId = 0;
internal long uniqueID;
#endif
internal Opcode(OpcodeID id)
{
this.opcodeID = id;
this.flags = OpcodeFlags.Single;
#if DEBUG
this.uniqueID = Opcode.NextUniqueId();
#endif
}
internal OpcodeFlags Flags
{
get
{
return this.flags;
}
set
{
this.flags = value;
}
}
internal OpcodeID ID
{
get
{
return this.opcodeID;
}
}
internal Opcode Next
{
get
{
return this.next;
}
set
{
this.next = value;
}
}
internal Opcode Prev
{
get
{
return this.prev;
}
set
{
this.prev = value;
}
}
#if DEBUG
static long NextUniqueId()
{
return Interlocked.Increment(ref Opcode.nextUniqueId);
}
#endif
internal virtual void Add(Opcode op)
{
Fx.Assert(null != op, "");
Fx.Assert(null != this.prev, "");
// Create a branch that will include both this and the new opcode
this.prev.AddBranch(op);
}
internal virtual void AddBranch(Opcode opcode)
{
Fx.Assert(null != opcode, "");
// Replace what follows this opcode with a branch containing .next and the new opcode
// If this opcode is a conditional, then since the tree structure is about to change, conditional
// reachability for everything that follows is about to change.
// 1. Remove .next from the conditional's AlwaysBranch Table.
// 2. Create the new branch structure.
// 3. The branch, once in the tree, will fix up all conditional jumps
Opcode next = this.next;
if (this.TestFlag(OpcodeFlags.InConditional))
{
this.DelinkFromConditional(next);
}
BranchOpcode branch = new BranchOpcode();
this.next = null;
this.Attach(branch);
if (null != next)
{
Fx.Assert(OpcodeID.Branch != next.ID, "");
branch.Add(next);
}
branch.Add(opcode);
}
internal void Attach(Opcode op)
{
Fx.Assert(null == this.next, "");
this.next = op;
op.prev = this;
}
internal virtual void CollectXPathFilters(ICollection<MessageFilter> filters)
{
if (this.next != null)
{
this.next.CollectXPathFilters(filters);
}
}
internal virtual bool IsEquivalentForAdd(Opcode opcode)
{
return (this.ID == opcode.ID);
}
internal bool IsMultipleResult()
{
return ((this.flags & (OpcodeFlags.Result | OpcodeFlags.Multiple)) ==
(OpcodeFlags.Result | OpcodeFlags.Multiple));
}
internal virtual void DelinkFromConditional(Opcode child)
{
Fx.Assert(this.TestFlag(OpcodeFlags.InConditional), "");
if (this.TestFlag(OpcodeFlags.InConditional))
{
((QueryConditionalBranchOpcode)this.prev).RemoveAlwaysBranch(child);
}
}
internal Opcode DetachChild()
{
Opcode child = this.next;
if (child != null)
{
if (this.IsInConditional())
{
this.DelinkFromConditional(child);
}
}
this.next = null;
child.prev = null;
return child;
}
internal void DetachFromParent()
{
Opcode parent = this.prev;
if (parent != null)
{
parent.DetachChild();
}
}
internal virtual bool Equals(Opcode op)
{
return (op.ID == this.ID);
}
internal virtual Opcode Eval(ProcessingContext context)
{
return this.next;
}
internal virtual Opcode Eval(NodeSequence sequence, SeekableXPathNavigator node)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new QueryProcessingException(QueryProcessingError.Unexpected));
}
internal virtual Opcode EvalSpecial(ProcessingContext context)
{
return this.Eval(context);
}
internal virtual bool IsInConditional()
{
return this.TestFlag(OpcodeFlags.InConditional);
}
internal bool IsReachableFromConditional()
{
return (null != this.prev && this.prev.IsInConditional());
}
internal virtual Opcode Locate(Opcode opcode)
{
Fx.Assert(null != opcode, "");
if (null != this.next && this.next.Equals(opcode))
{
return this.next;
}
return null;
}
internal virtual void LinkToConditional(Opcode child)
{
Fx.Assert(this.TestFlag(OpcodeFlags.InConditional), "");
if (this.TestFlag(OpcodeFlags.InConditional))
{
((QueryConditionalBranchOpcode)this.prev).AddAlwaysBranch(this, child);
}
}
internal virtual void Remove()
{
if (null == this.next)
{
Opcode prevOpcode = this.prev;
if (null != prevOpcode)
{
prevOpcode.RemoveChild(this);
prevOpcode.Remove();
}
}
}
internal virtual void RemoveChild(Opcode opcode)
{
Fx.Assert(null != opcode, "");
Fx.Assert(this.next == opcode, "");
if (this.IsInConditional())
{
this.DelinkFromConditional(opcode);
}
opcode.prev = null;
this.next = null;
opcode.Flags |= OpcodeFlags.Deleted;
}
internal virtual void Replace(Opcode replace, Opcode with)
{
Fx.Assert(null != replace && null != with, "");
if (this.next == replace)
{
bool isConditional = this.IsInConditional();
if (isConditional)
{
this.DelinkFromConditional(this.next);
}
this.next.prev = null;
this.next = with;
with.prev = this;
if (isConditional)
{
this.LinkToConditional(with);
}
}
}
internal bool TestFlag(OpcodeFlags flag)
{
return (0 != (this.flags & flag));
}
#if DEBUG_FILTER
public override string ToString()
{
#if DEBUG
return string.Format("{0}(#{1})", this.opcodeID.ToString(), this.uniqueID);
#else
return this.opcodeID.ToString();
#endif
}
#endif
internal virtual void Trim()
{
if (this.next != null)
{
this.next.Trim();
}
}
}
struct OpcodeBlock
{
Opcode first;
Opcode last;
internal OpcodeBlock(Opcode first)
{
this.first = first;
this.first.Prev = null;
for (this.last = this.first; this.last.Next != null; this.last = this.last.Next);
}
#if FILTEROPTIMIZER
internal OpcodeBlock(Opcode first, Opcode last)
{
this.first = first;
this.first.Prev = null;
this.last = last;
this.Last.Next = null;
}
#endif
internal Opcode First
{
get
{
return this.first;
}
}
internal Opcode Last
{
get
{
return this.last;
}
}
internal void Append(Opcode opcode)
{
Fx.Assert(null != opcode, "");
if (null == this.last)
{
this.first = opcode;
this.last = opcode;
}
else
{
this.last.Attach(opcode);
opcode.Next = null;
this.last = opcode;
}
}
internal void Append(OpcodeBlock block)
{
if (null == this.last)
{
this.first = block.first;
this.last = block.last;
}
else
{
this.last.Attach(block.first);
this.last = block.last;
}
}
internal void DetachLast()
{
if (null == this.last)
{
return;
}
Opcode newLast = this.last.Prev;
this.last.Prev = null;
this.last = newLast;
if (null != this.last)
{
this.last.Next = null;
}
}
}
class OpcodeList
{
QueryBuffer<Opcode> opcodes;
public OpcodeList(int capacity)
{
this.opcodes = new QueryBuffer<Opcode>(capacity);
}
public int Count
{
get
{
return this.opcodes.count;
}
}
public Opcode this[int index]
{
get
{
return this.opcodes[index];
}
set
{
this.opcodes[index] = value;
}
}
public void Add(Opcode opcode)
{
this.opcodes.Add(opcode);
}
public int IndexOf(Opcode opcode)
{
return this.opcodes.IndexOf(opcode);
}
public void Remove(Opcode opcode)
{
this.opcodes.Remove(opcode);
}
public void Trim()
{
this.opcodes.TrimToCount();
}
}
}
| |
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using TestHelper;
using Signum.Analyzer;
namespace Signum.Analyzer.Test;
[TestClass]
public class LiteEqualityTest : CodeFixVerifier
{
protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer()
{
return new LiteEqualityAnalyzer();
}
protected override CodeFixProvider GetCSharpCodeFixProvider()
{
return new LiteEqualityCodeFixProvider();
}
[TestMethod]
public void CompareTwoLites()
{
TestDiagnostic("SF0031", "Avoid comparing two Lite<T> by reference, consider using 'Is' extension method", @"
Lite<OrangeEntity> o1 = null;
Lite<OrangeEntity> o2 = null;
var condition = o1 == o2;
");
}
[TestMethod]
public void CompareTwoEntities()
{
TestDiagnostic("SF0032", "Avoid comparing two Entities by reference, consider using 'Is' extension method", @"
OrangeEntity o1 = null;
OrangeEntity o2 = null;
var condition = o1 == o2;
");
}
[TestMethod]
public void CompareLiteAndEntity()
{
TestDiagnostic("SF0033", "Impossible to compare Lite<T> and T, consider using 'Is' extension method", @"
Lite<Entity> lite = null;
Entity entity = null;
var condition = lite == entity;
");
}
[TestMethod]
public void CompareIncompatibleTypes()
{
TestDiagnostic("SF0034","Impossible to compare Lite<AppleEntity> and Lite<OrangeEntity>", @"
Lite<AppleEntity> apple = null;
Lite<OrangeEntity> orange = null;
var condition = apple == orange;
");
}
[TestMethod]
public void CompareIncompatibleAbstractTypes()
{
TestDiagnostic("SF0034", "Impossible to compare Lite<AbstractBananaEntity> and Lite<OrangeEntity>", @"
Lite<AbstractBananaEntity> banana = null;
Lite<OrangeEntity> orange = null;
var condition = banana == orange;
");
}
[TestMethod]
public void CompareBaseType()
{
TestDiagnostic("SF0031", "Avoid comparing two Lite<T> by reference, consider using 'Is' extension method", @"
Lite<Entity> type = null;
Lite<OrangeEntity> query = null;
var condition = type == query;
");
}
[TestMethod]
public void CompareDifferentInterfaces()
{
TestDiagnostic("SF0031", "Avoid comparing two Lite<T> by reference, consider using 'Is' extension method", @"
Lite<ISpider> type = null;
Lite<IMan> baseLite = null;
var condition = type == baseLite; //Could be SpiderMan!
");
}
[TestMethod]
public void CompareDifferentInterfaceEntity()
{
TestDiagnostic("SF0031", "Avoid comparing two Lite<T> by reference, consider using 'Is' extension method", @"
Lite<ISpider> type = null;
Lite<OrangeEntity> baseLite = null;
var condition = type == baseLite; //Could be SpiderMan!
");
}
private void TestDiagnostic(string id, string expectedError, string code, bool withIncludes = false, bool assertErrors = true)
{
string test = Surround(code, withIncludes: withIncludes);
if (expectedError == null)
VerifyCSharpDiagnostic(test, assertErrors, new DiagnosticResult[0]);
else
VerifyCSharpDiagnostic(test, assertErrors, new DiagnosticResult
{
Id = id,
Message = expectedError,
Severity = id is "SF0031" or "SF0032" ? DiagnosticSeverity.Warning : DiagnosticSeverity.Error,
});
}
private static string Surround(string expression, bool withIncludes = false)
{
return @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using Signum.Entities;
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;" + (withIncludes ? @"
using System.Linq.Expressions;" : null) + @"
namespace ConsoleApplication1
{
public interface ISpider : IEntity {}
public interface IMan : IEntity {}
public class AppleEntity : Entity {}
public class OrangeEntity : Entity {}
public abstract class AbstractBananaEntity : Entity {}
class Bla
{
void Foo()
{"
+ expression +
@" }
}
}";
}
private void TestCodeFix(string initial, string final, bool allowNewCompilerDiagnostics = false)
{
VerifyCSharpFix(
Surround(initial),
Surround(final),
assertNoInitialErrors: false,
allowNewCompilerDiagnostics: allowNewCompilerDiagnostics);
}
[TestMethod]
public void FixLiteEquals()
{
TestCodeFix(
@"
Lite<AppleEntity> ap1 = null;
Lite<AppleEntity> ap2 = null;
var condition = ap1 == ap2;",
@"
Lite<AppleEntity> ap1 = null;
Lite<AppleEntity> ap2 = null;
var condition = ap1.Is(ap2);");
}
[TestMethod]
public void FixEntityEquals()
{
TestCodeFix(
@"
AppleEntity ap1 = null;
AppleEntity ap2 = null;
var condition = ap1 == ap2;",
@"
AppleEntity ap1 = null;
AppleEntity ap2 = null;
var condition = ap1.Is(ap2);");
}
[TestMethod]
public void FixLiteEntityEquals()
{
TestCodeFix(
@"
Lite<AppleEntity> ap1 = null;
AppleEntity ap2 = null;
var condition = ap1 == ap2;",
@"
Lite<AppleEntity> ap1 = null;
AppleEntity ap2 = null;
var condition = ap1.Is(ap2);");
}
[TestMethod]
public void FixLiteEqualsError()
{
TestCodeFix(
@"
Lite<OrangeEntity> or1 = null;
Lite<AppleEntity> ap2 = null;
var condition = or1 == ap2;",
@"
Lite<OrangeEntity> or1 = null;
Lite<AppleEntity> ap2 = null;
var condition = or1.Is(ap2);", allowNewCompilerDiagnostics: true);
}
[TestMethod]
public void FixEntityEqualsError()
{
TestCodeFix(
@"
OrangeEntity or1 = null;
AppleEntity ap2 = null;
var condition = or1 == ap2;",
@"
OrangeEntity or1 = null;
AppleEntity ap2 = null;
var condition = or1.Is(ap2);", allowNewCompilerDiagnostics: true);
}
[TestMethod]
public void FixLiteEntityEqualsError()
{
TestCodeFix(
@"
Lite<OrangeEntity> or1 = null;
AppleEntity ap2 = null;
var condition = or1 == ap2;",
@"
Lite<OrangeEntity> or1 = null;
AppleEntity ap2 = null;
var condition = or1.Is(ap2);", allowNewCompilerDiagnostics: true);
}
}
| |
using UnityEngine;
using System.Collections;
using System;
namespace UMA
{
/// <summary>
/// Texture processing coroutine using rendertextures for atlas building.
/// </summary>
[Serializable]
public class TextureProcessPROCoroutine : TextureProcessBaseCoroutine
{
UMAData umaData;
RenderTexture destinationTexture;
Texture[] resultingTextures;
UMAGeneratorBase umaGenerator;
Camera renderCamera;
/// <summary>
/// Setup data for atlas building.
/// </summary>
/// <param name="_umaData">UMA data.</param>
/// <param name="_umaGenerator">UMA generator.</param>
public override void Prepare(UMAData _umaData, UMAGeneratorBase _umaGenerator)
{
umaData = _umaData;
umaGenerator = _umaGenerator;
if (umaData.atlasResolutionScale <= 0) umaData.atlasResolutionScale = 1f;
}
protected override void Start()
{
}
protected override IEnumerator workerMethod()
{
var textureMerge = umaGenerator.textureMerge;
for (int atlasIndex = umaData.generatedMaterials.materials.Count-1; atlasIndex >= 0; atlasIndex--)
{
var atlas = umaData.generatedMaterials.materials[atlasIndex];
//Rendering Atlas
int moduleCount = 0;
//Process all necessary TextureModules
for (int i = 0; i < atlas.materialFragments.Count; i++)
{
if (!atlas.materialFragments[i].isRectShared)
{
moduleCount++;
moduleCount = moduleCount + atlas.materialFragments[i].overlays.Length;
}
}
textureMerge.EnsureCapacity(moduleCount);
var slotData = atlas.materialFragments[0].slotData;
resultingTextures = new Texture[slotData.asset.material.channels.Length];
for (int textureType = slotData.asset.material.channels.Length - 1; textureType >= 0; textureType--)
{
switch(slotData.asset.material.channels[textureType].channelType )
{
case UMAMaterial.ChannelType.Texture:
case UMAMaterial.ChannelType.DiffuseTexture:
case UMAMaterial.ChannelType.NormalMap:
{
textureMerge.Reset();
for (int i = 0; i < atlas.materialFragments.Count; i++)
{
textureMerge.SetupModule(atlas, i, textureType);
}
//last element for this textureType
moduleCount = 0;
umaGenerator.textureMerge.gameObject.SetActive(true);
int width = Mathf.FloorToInt(atlas.cropResolution.x);
int height = Mathf.FloorToInt(atlas.cropResolution.y);
destinationTexture = new RenderTexture(Mathf.FloorToInt(atlas.cropResolution.x * umaData.atlasResolutionScale), Mathf.FloorToInt(atlas.cropResolution.y * umaData.atlasResolutionScale), 0, slotData.asset.material.channels[textureType].textureFormat, RenderTextureReadWrite.Linear);
destinationTexture.filterMode = FilterMode.Point;
destinationTexture.useMipMap = umaGenerator.convertMipMaps && !umaGenerator.convertRenderTexture;
renderCamera = umaGenerator.textureMerge.myCamera;
renderCamera.targetTexture = destinationTexture;
renderCamera.orthographicSize = height >> 1;
var camTransform = renderCamera.GetComponent<Transform>();
camTransform.position = new Vector3(width >> 1, height >> 1, 3);
camTransform.rotation = Quaternion.Euler(0, 180, 180);
renderCamera.Render();
renderCamera.gameObject.SetActive(false);
renderCamera.targetTexture = null;
if (umaGenerator.convertRenderTexture)
{
#region Convert Render Textures
yield return 25;
Texture2D tempTexture;
tempTexture = new Texture2D(destinationTexture.width, destinationTexture.height, TextureFormat.ARGB32, umaGenerator.convertMipMaps);
int xblocks = destinationTexture.width / 512;
int yblocks = destinationTexture.height / 512;
if (xblocks == 0 || yblocks == 0)
{
RenderTexture.active = destinationTexture;
tempTexture.ReadPixels(new Rect(0, 0, destinationTexture.width, destinationTexture.height), 0, 0, umaGenerator.convertMipMaps);
RenderTexture.active = null;
}
else
{
// figures that ReadPixels works differently on OpenGL and DirectX, someday this code will break because Unity fixes this bug!
if (IsOpenGL())
{
for (int x = 0; x < xblocks; x++)
{
for (int y = 0; y < yblocks; y++)
{
RenderTexture.active = destinationTexture;
tempTexture.ReadPixels(new Rect(x * 512, y * 512, 512, 512), x * 512, y * 512, umaGenerator.convertMipMaps);
RenderTexture.active = null;
yield return 8;
}
}
}
else
{
for (int x = 0; x < xblocks; x++)
{
for (int y = 0; y < yblocks; y++)
{
RenderTexture.active = destinationTexture;
tempTexture.ReadPixels(new Rect(x * 512, destinationTexture.height - 512 - y * 512, 512, 512), x * 512, y * 512, umaGenerator.convertMipMaps);
RenderTexture.active = null;
yield return 8;
}
}
}
}
resultingTextures[textureType] = tempTexture as Texture;
renderCamera.targetTexture = null;
RenderTexture.active = null;
destinationTexture.Release();
UnityEngine.GameObject.DestroyImmediate(destinationTexture);
umaGenerator.textureMerge.gameObject.SetActive(false);
yield return 6;
tempTexture = resultingTextures[textureType] as Texture2D;
tempTexture.Apply();
tempTexture.wrapMode = TextureWrapMode.Repeat;
tempTexture.filterMode = FilterMode.Bilinear;
resultingTextures[textureType] = tempTexture;
atlas.material.SetTexture(slotData.asset.material.channels[textureType].materialPropertyName, tempTexture);
#endregion
}
else
{
destinationTexture.filterMode = FilterMode.Bilinear;
destinationTexture.wrapMode = TextureWrapMode.Repeat;
resultingTextures[textureType] = destinationTexture;
atlas.material.SetTexture(slotData.asset.material.channels[textureType].materialPropertyName, destinationTexture);
}
umaGenerator.textureMerge.gameObject.SetActive(false);
break;
}
case UMAMaterial.ChannelType.MaterialColor:
{
atlas.material.SetColor(slotData.asset.material.channels[textureType].materialPropertyName, atlas.materialFragments[0].baseColor);
break;
}
case UMAMaterial.ChannelType.TintedTexture:
{
for (int i = 0; i < atlas.materialFragments.Count; i++)
{
var fragment = atlas.materialFragments[i];
if (fragment.isRectShared) continue;
for (int j = 0; j < fragment.baseOverlay.textureList.Length; j++)
{
if (fragment.baseOverlay.textureList[j] != null)
{
atlas.material.SetTexture(slotData.asset.material.channels[j].materialPropertyName, fragment.baseOverlay.textureList[j]);
if (j == 0)
{
atlas.material.color = fragment.baseColor;
}
}
}
foreach (var overlay in fragment.overlays)
{
for (int j = 0; j < overlay.textureList.Length; j++)
{
if (overlay.textureList[j] != null)
{
atlas.material.SetTexture(slotData.asset.material.channels[j].materialPropertyName, overlay.textureList[j]);
}
}
}
}
break;
}
}
}
atlas.resultingAtlasList = resultingTextures;
}
}
private bool IsOpenGL()
{
var graphicsDeviceVersion = SystemInfo.graphicsDeviceVersion;
return graphicsDeviceVersion.StartsWith("OpenGL");
}
protected override void Stop()
{
}
}
}
| |
//-----------------------------------------------------------------------------
// <copyright file="Base64Stream.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
namespace System.Net
{
using System;
using System.IO;
using System.Net.Mime;
using System.Text;
using System.Diagnostics;
internal class Base64Stream : DelegatedStream, IEncodableStream
{
static byte[] base64DecodeMap = new byte[] {
//0 1 2 3 4 5 6 7 8 9 A B C D E F
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 0
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 1
255,255,255,255,255,255,255,255,255,255,255, 62,255,255,255, 63, // 2
52, 53, 54, 55, 56, 57, 58, 59, 60, 61,255,255,255,255,255,255, // 3
255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 4
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,255,255,255,255,255, // 5
255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 6
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,255,255,255,255,255, // 7
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 8
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 9
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // A
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // B
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // C
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // D
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // E
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // F
};
static byte[] base64EncodeMap = new byte[] {
65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99,100,101,102,
103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,
119,120,121,122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47,
61
};
int lineLength;
ReadStateInfo readState;
Base64WriteStateInfo writeState;
//the number of bytes needed to encode three bytes (see algorithm description in Encode method below)
const int sizeOfBase64EncodedChar = 4;
//bytes with this value in the decode map are invalid
const byte invalidBase64Value = 255;
internal Base64Stream(Stream stream, Base64WriteStateInfo writeStateInfo)
: base(stream)
{
this.writeState = new Base64WriteStateInfo();
this.lineLength = writeStateInfo.MaxLineLength;
}
internal Base64Stream(Stream stream, int lineLength)
: base(stream)
{
this.lineLength = lineLength;
this.writeState = new Base64WriteStateInfo();
}
internal Base64Stream(Base64WriteStateInfo writeStateInfo)
{
this.lineLength = writeStateInfo.MaxLineLength;
this.writeState = writeStateInfo;
}
public override bool CanWrite
{
get
{
return base.CanWrite;
}
}
ReadStateInfo ReadState
{
get
{
if (this.readState == null)
this.readState = new ReadStateInfo();
return this.readState;
}
}
internal Base64WriteStateInfo WriteState
{
get
{
Debug.Assert(writeState != null, "writeState was null");
return this.writeState;
}
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException("offset");
if (offset + count > buffer.Length)
throw new ArgumentOutOfRangeException("count");
ReadAsyncResult result = new ReadAsyncResult(this, buffer, offset, count, callback, state);
result.Read();
return result;
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException("offset");
if (offset + count > buffer.Length)
throw new ArgumentOutOfRangeException("count");
WriteAsyncResult result = new WriteAsyncResult(this, buffer, offset, count, callback, state);
result.Write();
return result;
}
public override void Close()
{
if (this.writeState != null && WriteState.Length > 0)
{
switch (WriteState.Padding)
{
case 2:
WriteState.Append(base64EncodeMap[WriteState.LastBits], base64EncodeMap[64],
base64EncodeMap[64]);
break;
case 1:
WriteState.Append(base64EncodeMap[WriteState.LastBits], base64EncodeMap[64]);
break;
}
WriteState.Padding = 0;
FlushInternal();
}
base.Close();
}
public int DecodeBytes(byte[] buffer, int offset, int count)
{
unsafe
{
fixed (byte* pBuffer = buffer)
{
byte* start = pBuffer + offset;
byte* source = start;
byte* dest = start;
byte* end = start + count;
while (source < end)
{
//space and tab are ok because folding must include a whitespace char.
if (*source == '\r' || *source == '\n' || *source == '=' || *source == ' ' || *source == '\t')
{
source++;
continue;
}
byte s = base64DecodeMap[*source];
if (s == invalidBase64Value)
throw new FormatException(SR.GetString(SR.MailBase64InvalidCharacter));
switch (ReadState.Pos)
{
case 0:
ReadState.Val = (byte)(s << 2);
ReadState.Pos++;
break;
case 1:
*dest++ = (byte)(ReadState.Val + (s >> 4));
ReadState.Val = (byte)(s << 4);
ReadState.Pos++;
break;
case 2:
*dest++ = (byte)(ReadState.Val + (s >> 2));
ReadState.Val = (byte)(s << 6);
ReadState.Pos++;
break;
case 3:
*dest++ = (byte)(ReadState.Val + s);
ReadState.Pos = 0;
break;
}
source++;
}
count = (int)(dest - start);
}
}
return count;
}
public int EncodeBytes(byte[] buffer, int offset, int count)
{
return this.EncodeBytes(buffer, offset, count, true, true);
}
internal int EncodeBytes(byte[] buffer, int offset, int count,
bool dontDeferFinalBytes, bool shouldAppendSpaceToCRLF)
{
int cur = offset;
Debug.Assert(buffer != null, "buffer was null");
Debug.Assert(this.writeState != null, "writestate was null");
Debug.Assert(this.writeState.Buffer != null, "writestate.buffer was null");
// Add Encoding header, if any. e.g. =?encoding?b?
WriteState.AppendHeader();
switch (WriteState.Padding)
{
case 2:
WriteState.Append(base64EncodeMap[WriteState.LastBits | ((buffer[cur]&0xf0)>>4)]);
if (count == 1)
{
WriteState.LastBits = (byte)((buffer[cur]&0x0f)<<2);
WriteState.Padding = 1;
return cur - offset;
}
WriteState.Append(base64EncodeMap[((buffer[cur]&0x0f)<<2) | ((buffer[cur+1]&0xc0)>>6)]);
WriteState.Append(base64EncodeMap[(buffer[cur+1]&0x3f)]);
cur+=2;
count-=2;
WriteState.Padding = 0;
break;
case 1:
WriteState.Append(base64EncodeMap[WriteState.LastBits | ((buffer[cur]&0xc0)>>6)]);
WriteState.Append(base64EncodeMap[(buffer[cur]&0x3f)]);
cur++;
count--;
WriteState.Padding = 0;
break;
}
int calcLength = cur + (count - (count%3));
// Convert three bytes at a time to base64 notation. This will output 4 chars.
for (; cur < calcLength; cur+=3)
{
if ((lineLength != -1)
&& (WriteState.CurrentLineLength + sizeOfBase64EncodedChar + writeState.FooterLength > lineLength))
{
WriteState.AppendCRLF(shouldAppendSpaceToCRLF);
}
//how we actually encode: get three bytes in the
//buffer to be encoded. Then, extract six bits at a time and encode each six bit chunk as a base-64 character.
//this means that three bytes of data will be encoded as four base64 characters. It also means that to encode
//a character, we must have three bytes to encode so if the number of bytes is not divisible by three, we
//must pad the buffer (this happens below)
WriteState.Append(base64EncodeMap[(buffer[cur]&0xfc)>>2]);
WriteState.Append(base64EncodeMap[((buffer[cur]&0x03)<<4) | ((buffer[cur+1]&0xf0)>>4)]);
WriteState.Append(base64EncodeMap[((buffer[cur+1]&0x0f)<<2) | ((buffer[cur+2]&0xc0)>>6)]);
WriteState.Append(base64EncodeMap[(buffer[cur+2]&0x3f)]);
}
cur = calcLength; //Where we left off before
// See if we need to fold before writing the last section (with possible padding)
if ((count % 3 != 0) && (lineLength != -1)
&& (WriteState.CurrentLineLength + sizeOfBase64EncodedChar + writeState.FooterLength >= lineLength))
{
WriteState.AppendCRLF(shouldAppendSpaceToCRLF);
}
//now pad this thing if we need to. Since it must be a number of bytes that is evenly divisble by 3,
//if there are extra bytes, pad with '=' until we have a number of bytes divisible by 3
switch(count%3)
{
case 2: //One character padding needed
WriteState.Append(base64EncodeMap[(buffer[cur]&0xFC)>>2]);
WriteState.Append(base64EncodeMap[((buffer[cur]&0x03)<<4)|((buffer[cur+1]&0xf0)>>4)]);
if (dontDeferFinalBytes) {
WriteState.Append(base64EncodeMap[((buffer[cur+1]&0x0f)<<2)]);
WriteState.Append(base64EncodeMap[64]);
WriteState.Padding = 0;
}
else{
WriteState.LastBits = (byte)((buffer[cur+1]&0x0F)<<2);
WriteState.Padding = 1;
}
cur += 2;
break;
case 1: // Two character padding needed
WriteState.Append(base64EncodeMap[(buffer[cur]&0xFC)>>2]);
if (dontDeferFinalBytes) {
WriteState.Append(base64EncodeMap[(byte)((buffer[cur]&0x03)<<4)]);
WriteState.Append(base64EncodeMap[64]);
WriteState.Append(base64EncodeMap[64]);
WriteState.Padding = 0;
}
else{
WriteState.LastBits = (byte)((buffer[cur]&0x03)<<4);
WriteState.Padding = 2;
}
cur++;
break;
}
// Write out the last footer, if any. e.g. ?=
WriteState.AppendFooter();
return cur - offset;
}
public Stream GetStream()
{
return this;
}
public string GetEncodedString()
{
return ASCIIEncoding.ASCII.GetString(this.WriteState.Buffer, 0, this.WriteState.Length);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
int read = ReadAsyncResult.End(asyncResult);
return read;
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
WriteAsyncResult.End(asyncResult);
}
public override void Flush()
{
if (this.writeState != null && WriteState.Length > 0)
{
FlushInternal();
}
base.Flush();
}
private void FlushInternal()
{
base.Write(WriteState.Buffer, 0, WriteState.Length);
WriteState.Reset();
}
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException("offset");
if (offset + count > buffer.Length)
throw new ArgumentOutOfRangeException("count");
for (;;)
{
// read data from the underlying stream
int read = base.Read(buffer, offset, count);
// if the underlying stream returns 0 then there
// is no more data - ust return 0.
if (read == 0)
return 0;
// while decoding, we may end up not having
// any bytes to return pending additional data
// from the underlying stream.
read = DecodeBytes(buffer, offset, read);
if (read > 0)
return read;
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException("offset");
if (offset + count > buffer.Length)
throw new ArgumentOutOfRangeException("count");
int written = 0;
// do not append a space when writing from a stream since this means
// it's writing the email body
for (;;)
{
written += EncodeBytes(buffer, offset + written, count - written, false, false);
if (written < count)
FlushInternal();
else
break;
}
}
class ReadAsyncResult : LazyAsyncResult
{
Base64Stream parent;
byte[] buffer;
int offset;
int count;
int read;
static AsyncCallback onRead = new AsyncCallback(OnRead);
internal ReadAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null,state,callback)
{
this.parent = parent;
this.buffer = buffer;
this.offset = offset;
this.count = count;
}
bool CompleteRead(IAsyncResult result)
{
this.read = this.parent.BaseStream.EndRead(result);
// if the underlying stream returns 0 then there
// is no more data - ust return 0.
if (read == 0)
{
InvokeCallback();
return true;
}
// while decoding, we may end up not having
// any bytes to return pending additional data
// from the underlying stream.
this.read = this.parent.DecodeBytes(this.buffer, this.offset, this.read);
if (this.read > 0)
{
InvokeCallback();
return true;
}
return false;
}
internal void Read()
{
for (;;)
{
IAsyncResult result = this.parent.BaseStream.BeginRead(this.buffer, this.offset, this.count, onRead, this);
if (!result.CompletedSynchronously || CompleteRead(result))
break;
}
}
static void OnRead(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
ReadAsyncResult thisPtr = (ReadAsyncResult)result.AsyncState;
try
{
if (!thisPtr.CompleteRead(result))
thisPtr.Read();
}
catch (Exception e)
{
if (thisPtr.IsCompleted)
throw;
thisPtr.InvokeCallback(e);
}
}
}
internal static int End(IAsyncResult result)
{
ReadAsyncResult thisPtr = (ReadAsyncResult)result;
thisPtr.InternalWaitForCompletion();
return thisPtr.read;
}
}
class WriteAsyncResult : LazyAsyncResult
{
Base64Stream parent;
byte[] buffer;
int offset;
int count;
static AsyncCallback onWrite = new AsyncCallback(OnWrite);
int written;
internal WriteAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback)
{
this.parent = parent;
this.buffer = buffer;
this.offset = offset;
this.count = count;
}
internal void Write()
{
for (;;)
{
// do not append a space when writing from a stream since this means
// it's writing the email body
this.written += this.parent.EncodeBytes(this.buffer, this.offset + this.written,
this.count - this.written, false, false);
if (this.written < this.count)
{
IAsyncResult result = this.parent.BaseStream.BeginWrite(this.parent.WriteState.Buffer, 0, this.parent.WriteState.Length, onWrite, this);
if (!result.CompletedSynchronously)
break;
CompleteWrite(result);
}
else
{
InvokeCallback();
break;
}
}
}
void CompleteWrite(IAsyncResult result)
{
this.parent.BaseStream.EndWrite(result);
this.parent.WriteState.Reset();
}
static void OnWrite(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState;
try
{
thisPtr.CompleteWrite(result);
thisPtr.Write();
}
catch (Exception e)
{
if (thisPtr.IsCompleted)
throw;
thisPtr.InvokeCallback(e);
}
}
}
internal static void End(IAsyncResult result)
{
WriteAsyncResult thisPtr = (WriteAsyncResult)result;
thisPtr.InternalWaitForCompletion();
Debug.Assert(thisPtr.written == thisPtr.count);
}
}
class ReadStateInfo
{
byte val;
byte pos;
internal byte Val
{
get { return this.val; }
set { this.val = value; }
}
internal byte Pos
{
get { return this.pos; }
set { this.pos = value; }
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Data;
using Nop.Core.Domain.Blogs;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Stores;
using Nop.Services.Events;
namespace Nop.Services.Blogs
{
/// <summary>
/// Blog service
/// </summary>
public partial class BlogService : IBlogService
{
#region Fields
private readonly IRepository<BlogPost> _blogPostRepository;
private readonly IRepository<BlogComment> _blogCommentRepository;
private readonly IRepository<StoreMapping> _storeMappingRepository;
private readonly CatalogSettings _catalogSettings;
private readonly IEventPublisher _eventPublisher;
#endregion
#region Ctor
public BlogService(IRepository<BlogPost> blogPostRepository,
IRepository<BlogComment> blogCommentRepository,
IRepository<StoreMapping> storeMappingRepository,
CatalogSettings catalogSettings,
IEventPublisher eventPublisher)
{
this._blogPostRepository = blogPostRepository;
this._blogCommentRepository = blogCommentRepository;
this._storeMappingRepository = storeMappingRepository;
this._catalogSettings = catalogSettings;
this._eventPublisher = eventPublisher;
}
#endregion
#region Methods
/// <summary>
/// Deletes a blog post
/// </summary>
/// <param name="blogPost">Blog post</param>
public virtual void DeleteBlogPost(BlogPost blogPost)
{
if (blogPost == null)
throw new ArgumentNullException("blogPost");
_blogPostRepository.Delete(blogPost);
//event notification
_eventPublisher.EntityDeleted(blogPost);
}
/// <summary>
/// Gets a blog post
/// </summary>
/// <param name="blogPostId">Blog post identifier</param>
/// <returns>Blog post</returns>
public virtual BlogPost GetBlogPostById(int blogPostId)
{
if (blogPostId == 0)
return null;
return _blogPostRepository.GetById(blogPostId);
}
/// <summary>
/// Gets all blog posts
/// </summary>
/// <param name="storeId">The store identifier; pass 0 to load all records</param>
/// <param name="languageId">Language identifier; 0 if you want to get all records</param>
/// <param name="dateFrom">Filter by created date; null if you want to get all records</param>
/// <param name="dateTo">Filter by created date; null if you want to get all records</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Blog posts</returns>
public virtual IPagedList<BlogPost> GetAllBlogPosts(int storeId = 0, int languageId = 0,
DateTime? dateFrom = null, DateTime? dateTo = null,
int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
{
var query = _blogPostRepository.Table;
if (dateFrom.HasValue)
query = query.Where(b => dateFrom.Value <= b.CreatedOnUtc);
if (dateTo.HasValue)
query = query.Where(b => dateTo.Value >= b.CreatedOnUtc);
if (languageId > 0)
query = query.Where(b => languageId == b.LanguageId);
if (!showHidden)
{
var utcNow = DateTime.UtcNow;
query = query.Where(b => !b.StartDateUtc.HasValue || b.StartDateUtc <= utcNow);
query = query.Where(b => !b.EndDateUtc.HasValue || b.EndDateUtc >= utcNow);
}
if (storeId > 0 && !_catalogSettings.IgnoreStoreLimitations)
{
//Store mapping
query = from bp in query
join sm in _storeMappingRepository.Table
on new { c1 = bp.Id, c2 = "BlogPost" } equals new { c1 = sm.EntityId, c2 = sm.EntityName } into bp_sm
from sm in bp_sm.DefaultIfEmpty()
where !bp.LimitedToStores || storeId == sm.StoreId
select bp;
//only distinct blog posts (group by ID)
query = from bp in query
group bp by bp.Id
into bpGroup
orderby bpGroup.Key
select bpGroup.FirstOrDefault();
}
query = query.OrderByDescending(b => b.CreatedOnUtc);
var blogPosts = new PagedList<BlogPost>(query, pageIndex, pageSize);
return blogPosts;
}
/// <summary>
/// Gets all blog posts
/// </summary>
/// <param name="storeId">The store identifier; pass 0 to load all records</param>
/// <param name="languageId">Language identifier. 0 if you want to get all news</param>
/// <param name="tag">Tag</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Blog posts</returns>
public virtual IPagedList<BlogPost> GetAllBlogPostsByTag(int storeId = 0,
int languageId = 0, string tag = "",
int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false)
{
tag = tag.Trim();
//we load all records and only then filter them by tag
var blogPostsAll = GetAllBlogPosts(storeId: storeId, languageId: languageId, showHidden: showHidden);
var taggedBlogPosts = new List<BlogPost>();
foreach (var blogPost in blogPostsAll)
{
var tags = blogPost.ParseTags();
if (!String.IsNullOrEmpty(tags.FirstOrDefault(t => t.Equals(tag, StringComparison.InvariantCultureIgnoreCase))))
taggedBlogPosts.Add(blogPost);
}
//server-side paging
var result = new PagedList<BlogPost>(taggedBlogPosts, pageIndex, pageSize);
return result;
}
/// <summary>
/// Gets all blog post tags
/// </summary>
/// <param name="storeId">The store identifier; pass 0 to load all records</param>
/// <param name="languageId">Language identifier. 0 if you want to get all news</param>
/// <param name="showHidden">A value indicating whether to show hidden records</param>
/// <returns>Blog post tags</returns>
public virtual IList<BlogPostTag> GetAllBlogPostTags(int storeId, int languageId, bool showHidden = false)
{
var blogPostTags = new List<BlogPostTag>();
var blogPosts = GetAllBlogPosts(storeId: storeId, languageId: languageId, showHidden: showHidden);
foreach (var blogPost in blogPosts)
{
var tags = blogPost.ParseTags();
foreach (string tag in tags)
{
var foundBlogPostTag = blogPostTags.Find(bpt => bpt.Name.Equals(tag, StringComparison.InvariantCultureIgnoreCase));
if (foundBlogPostTag == null)
{
foundBlogPostTag = new BlogPostTag
{
Name = tag,
BlogPostCount = 1
};
blogPostTags.Add(foundBlogPostTag);
}
else
foundBlogPostTag.BlogPostCount++;
}
}
return blogPostTags;
}
/// <summary>
/// Inserts an blog post
/// </summary>
/// <param name="blogPost">Blog post</param>
public virtual void InsertBlogPost(BlogPost blogPost)
{
if (blogPost == null)
throw new ArgumentNullException("blogPost");
_blogPostRepository.Insert(blogPost);
//event notification
_eventPublisher.EntityInserted(blogPost);
}
/// <summary>
/// Updates the blog post
/// </summary>
/// <param name="blogPost">Blog post</param>
public virtual void UpdateBlogPost(BlogPost blogPost)
{
if (blogPost == null)
throw new ArgumentNullException("blogPost");
_blogPostRepository.Update(blogPost);
//event notification
_eventPublisher.EntityUpdated(blogPost);
}
/// <summary>
/// Gets all comments
/// </summary>
/// <param name="customerId">Customer identifier; 0 to load all records</param>
/// <returns>Comments</returns>
public virtual IList<BlogComment> GetAllComments(int customerId)
{
var query = from c in _blogCommentRepository.Table
orderby c.CreatedOnUtc
where (customerId == 0 || c.CustomerId == customerId)
select c;
var content = query.ToList();
return content;
}
/// <summary>
/// Gets a blog comment
/// </summary>
/// <param name="blogCommentId">Blog comment identifier</param>
/// <returns>Blog comment</returns>
public virtual BlogComment GetBlogCommentById(int blogCommentId)
{
if (blogCommentId == 0)
return null;
return _blogCommentRepository.GetById(blogCommentId);
}
/// <summary>
/// Get blog comments by identifiers
/// </summary>
/// <param name="commentIds">Blog comment identifiers</param>
/// <returns>Blog comments</returns>
public virtual IList<BlogComment> GetBlogCommentsByIds(int[] commentIds)
{
if (commentIds == null || commentIds.Length == 0)
return new List<BlogComment>();
var query = from bc in _blogCommentRepository.Table
where commentIds.Contains(bc.Id)
select bc;
var comments = query.ToList();
//sort by passed identifiers
var sortedComments = new List<BlogComment>();
foreach (int id in commentIds)
{
var comment = comments.Find(x => x.Id == id);
if (comment != null)
sortedComments.Add(comment);
}
return sortedComments;
}
/// <summary>
/// Deletes a blog comment
/// </summary>
/// <param name="blogComment">Blog comment</param>
public virtual void DeleteBlogComment(BlogComment blogComment)
{
if (blogComment == null)
throw new ArgumentNullException("blogComment");
_blogCommentRepository.Delete(blogComment);
}
#endregion
}
}
| |
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using FixedBitSet = Lucene.Net.Util.FixedBitSet;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using Term = Lucene.Net.Index.Term;
internal sealed class SloppyPhraseScorer : Scorer
{
private PhrasePositions min, max;
private float sloppyFreq; //phrase frequency in current doc as computed by phraseFreq().
private readonly Similarity.SimScorer docScorer;
private readonly int slop;
private readonly int numPostings;
private readonly PhraseQueue pq; // for advancing min position
private int end; // current largest phrase position
private bool hasRpts; // flag indicating that there are repetitions (as checked in first candidate doc)
private bool checkedRpts; // flag to only check for repetitions in first candidate doc
private bool hasMultiTermRpts;
private PhrasePositions[][] rptGroups; // in each group are PPs that repeats each other (i.e. same term), sorted by (query) offset
private PhrasePositions[] rptStack; // temporary stack for switching colliding repeating pps
private int numMatches;
private readonly long cost;
internal SloppyPhraseScorer(Weight weight, PhraseQuery.PostingsAndFreq[] postings, int slop, Similarity.SimScorer docScorer)
: base(weight)
{
this.docScorer = docScorer;
this.slop = slop;
this.numPostings = postings == null ? 0 : postings.Length;
pq = new PhraseQueue(postings.Length);
// min(cost)
cost = postings[0].postings.GetCost();
// convert tps to a list of phrase positions.
// note: phrase-position differs from term-position in that its position
// reflects the phrase offset: pp.pos = tp.pos - offset.
// this allows to easily identify a matching (exact) phrase
// when all PhrasePositions have exactly the same position.
if (postings.Length > 0)
{
min = new PhrasePositions(postings[0].postings, postings[0].position, 0, postings[0].terms);
max = min;
max.doc = -1;
for (int i = 1; i < postings.Length; i++)
{
PhrasePositions pp = new PhrasePositions(postings[i].postings, postings[i].position, i, postings[i].terms);
max.next = pp;
max = pp;
max.doc = -1;
}
max.next = min; // make it cyclic for easier manipulation
}
}
/// <summary>
/// Score a candidate doc for all slop-valid position-combinations (matches)
/// encountered while traversing/hopping the PhrasePositions.
/// <para/> The score contribution of a match depends on the distance:
/// <para/> - highest score for distance=0 (exact match).
/// <para/> - score gets lower as distance gets higher.
/// <para/>Example: for query "a b"~2, a document "x a b a y" can be scored twice:
/// once for "a b" (distance=0), and once for "b a" (distance=2).
/// <para/>Possibly not all valid combinations are encountered, because for efficiency
/// we always propagate the least PhrasePosition. This allows to base on
/// <see cref="Util.PriorityQueue{T}"/> and move forward faster.
/// As result, for example, document "a b c b a"
/// would score differently for queries "a b c"~4 and "c b a"~4, although
/// they really are equivalent.
/// Similarly, for doc "a b c b a f g", query "c b"~2
/// would get same score as "g f"~2, although "c b"~2 could be matched twice.
/// We may want to fix this in the future (currently not, for performance reasons).
/// </summary>
private float PhraseFreq()
{
if (!InitPhrasePositions())
{
return 0.0f;
}
float freq = 0.0f;
numMatches = 0;
PhrasePositions pp = pq.Pop();
int matchLength = end - pp.position;
int next = pq.Top.position;
while (AdvancePP(pp))
{
if (hasRpts && !AdvanceRpts(pp))
{
break; // pps exhausted
}
if (pp.position > next) // done minimizing current match-length
{
if (matchLength <= slop)
{
freq += docScorer.ComputeSlopFactor(matchLength); // score match
numMatches++;
}
pq.Add(pp);
pp = pq.Pop();
next = pq.Top.position;
matchLength = end - pp.position;
}
else
{
int matchLength2 = end - pp.position;
if (matchLength2 < matchLength)
{
matchLength = matchLength2;
}
}
}
if (matchLength <= slop)
{
freq += docScorer.ComputeSlopFactor(matchLength); // score match
numMatches++;
}
return freq;
}
/// <summary>
/// Advance a PhrasePosition and update 'end', return false if exhausted </summary>
private bool AdvancePP(PhrasePositions pp)
{
if (!pp.NextPosition())
{
return false;
}
if (pp.position > end)
{
end = pp.position;
}
return true;
}
/// <summary>
/// pp was just advanced. If that caused a repeater collision, resolve by advancing the lesser
/// of the two colliding pps. Note that there can only be one collision, as by the initialization
/// there were no collisions before pp was advanced.
/// </summary>
private bool AdvanceRpts(PhrasePositions pp)
{
if (pp.rptGroup < 0)
{
return true; // not a repeater
}
PhrasePositions[] rg = rptGroups[pp.rptGroup];
FixedBitSet bits = new FixedBitSet(rg.Length); // for re-queuing after collisions are resolved
int k0 = pp.rptInd;
int k;
while ((k = Collide(pp)) >= 0)
{
pp = Lesser(pp, rg[k]); // always advance the lesser of the (only) two colliding pps
if (!AdvancePP(pp))
{
return false; // exhausted
}
if (k != k0) // careful: mark only those currently in the queue
{
bits = FixedBitSet.EnsureCapacity(bits, k);
bits.Set(k); // mark that pp2 need to be re-queued
}
}
// collisions resolved, now re-queue
// empty (partially) the queue until seeing all pps advanced for resolving collisions
int n = 0;
// TODO would be good if we can avoid calling cardinality() in each iteration!
int numBits = bits.Length; // larges bit we set
while (bits.Cardinality() > 0)
{
PhrasePositions pp2 = pq.Pop();
rptStack[n++] = pp2;
if (pp2.rptGroup >= 0 && pp2.rptInd < numBits && bits.Get(pp2.rptInd)) // this bit may not have been set
{
bits.Clear(pp2.rptInd);
}
}
// add back to queue
for (int i = n - 1; i >= 0; i--)
{
pq.Add(rptStack[i]);
}
return true;
}
/// <summary>
/// Compare two pps, but only by position and offset </summary>
private PhrasePositions Lesser(PhrasePositions pp, PhrasePositions pp2)
{
if (pp.position < pp2.position || (pp.position == pp2.position && pp.offset < pp2.offset))
{
return pp;
}
return pp2;
}
/// <summary>
/// Index of a pp2 colliding with pp, or -1 if none </summary>
private int Collide(PhrasePositions pp)
{
int tpPos = TpPos(pp);
PhrasePositions[] rg = rptGroups[pp.rptGroup];
for (int i = 0; i < rg.Length; i++)
{
PhrasePositions pp2 = rg[i];
if (pp2 != pp && TpPos(pp2) == tpPos)
{
return pp2.rptInd;
}
}
return -1;
}
/// <summary>
/// Initialize <see cref="PhrasePositions"/> in place.
/// A one time initialization for this scorer (on first doc matching all terms):
/// <list type="bullet">
/// <item><description>Check if there are repetitions</description></item>
/// <item><description>If there are, find groups of repetitions.</description></item>
/// </list>
/// Examples:
/// <list type="number">
/// <item><description>no repetitions: <b>"ho my"~2</b></description></item>
/// <item><description>>repetitions: <b>"ho my my"~2</b></description></item>
/// <item><description>repetitions: <b>"my ho my"~2</b></description></item>
/// </list>
/// </summary>
/// <returns> <c>false</c> if PPs are exhausted (and so current doc will not be a match) </returns>
private bool InitPhrasePositions()
{
end = int.MinValue;
if (!checkedRpts)
{
return InitFirstTime();
}
if (!hasRpts)
{
InitSimple();
return true; // PPs available
}
return InitComplex();
}
/// <summary>
/// No repeats: simplest case, and most common. It is important to keep this piece of the code simple and efficient </summary>
private void InitSimple()
{
//System.err.println("initSimple: doc: "+min.doc);
pq.Clear();
// position pps and build queue from list
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
pp.FirstPosition();
if (pp.position > end)
{
end = pp.position;
}
pq.Add(pp);
}
}
/// <summary>
/// With repeats: not so simple. </summary>
private bool InitComplex()
{
//System.err.println("initComplex: doc: "+min.doc);
PlaceFirstPositions();
if (!AdvanceRepeatGroups())
{
return false; // PPs exhausted
}
FillQueue();
return true; // PPs available
}
/// <summary>
/// Move all PPs to their first position </summary>
private void PlaceFirstPositions()
{
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
pp.FirstPosition();
}
}
/// <summary>
/// Fill the queue (all pps are already placed) </summary>
private void FillQueue()
{
pq.Clear();
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
if (pp.position > end)
{
end = pp.position;
}
pq.Add(pp);
}
}
/// <summary>
/// At initialization (each doc), each repetition group is sorted by (query) offset.
/// this provides the start condition: no collisions.
/// <para/>Case 1: no multi-term repeats
/// <para/>
/// It is sufficient to advance each pp in the group by one less than its group index.
/// So lesser pp is not advanced, 2nd one advance once, 3rd one advanced twice, etc.
/// <para/>Case 2: multi-term repeats
/// </summary>
/// <returns> <c>false</c> if PPs are exhausted. </returns>
private bool AdvanceRepeatGroups()
{
foreach (PhrasePositions[] rg in rptGroups)
{
if (hasMultiTermRpts)
{
// more involved, some may not collide
int incr;
for (int i = 0; i < rg.Length; i += incr)
{
incr = 1;
PhrasePositions pp = rg[i];
int k;
while ((k = Collide(pp)) >= 0)
{
PhrasePositions pp2 = Lesser(pp, rg[k]);
if (!AdvancePP(pp2)) // at initialization always advance pp with higher offset
{
return false; // exhausted
}
if (pp2.rptInd < i) // should not happen?
{
incr = 0;
break;
}
}
}
}
else
{
// simpler, we know exactly how much to advance
for (int j = 1; j < rg.Length; j++)
{
for (int k = 0; k < j; k++)
{
if (!rg[j].NextPosition())
{
return false; // PPs exhausted
}
}
}
}
}
return true; // PPs available
}
/// <summary>
/// Initialize with checking for repeats. Heavy work, but done only for the first candidate doc.
/// <para/>
/// If there are repetitions, check if multi-term postings (MTP) are involved.
/// <para/>
/// Without MTP, once PPs are placed in the first candidate doc, repeats (and groups) are visible.
/// <para/>
/// With MTP, a more complex check is needed, up-front, as there may be "hidden collisions".
/// <para/>
/// For example P1 has {A,B}, P1 has {B,C}, and the first doc is: "A C B". At start, P1 would point
/// to "A", p2 to "C", and it will not be identified that P1 and P2 are repetitions of each other.
/// <para/>
/// The more complex initialization has two parts:
/// <para/>
/// (1) identification of repetition groups.
/// <para/>
/// (2) advancing repeat groups at the start of the doc.
/// <para/>
/// For (1), a possible solution is to just create a single repetition group,
/// made of all repeating pps. But this would slow down the check for collisions,
/// as all pps would need to be checked. Instead, we compute "connected regions"
/// on the bipartite graph of postings and terms.
/// </summary>
private bool InitFirstTime()
{
//System.err.println("initFirstTime: doc: "+min.doc);
checkedRpts = true;
PlaceFirstPositions();
var rptTerms = RepeatingTerms();
hasRpts = rptTerms.Count > 0;
if (hasRpts)
{
rptStack = new PhrasePositions[numPostings]; // needed with repetitions
IList<IList<PhrasePositions>> rgs = GatherRptGroups(rptTerms);
SortRptGroups(rgs);
if (!AdvanceRepeatGroups())
{
return false; // PPs exhausted
}
}
FillQueue();
return true; // PPs available
}
/// <summary>
/// Sort each repetition group by (query) offset.
/// Done only once (at first doc) and allows to initialize faster for each doc.
/// </summary>
private void SortRptGroups(IList<IList<PhrasePositions>> rgs)
{
rptGroups = new PhrasePositions[rgs.Count][];
IComparer<PhrasePositions> cmprtr = new ComparerAnonymousInnerClassHelper(this);
for (int i = 0; i < rptGroups.Length; i++)
{
PhrasePositions[] rg = rgs[i].ToArray();
Array.Sort(rg, cmprtr);
rptGroups[i] = rg;
for (int j = 0; j < rg.Length; j++)
{
rg[j].rptInd = j; // we use this index for efficient re-queuing
}
}
}
private class ComparerAnonymousInnerClassHelper : IComparer<PhrasePositions>
{
private readonly SloppyPhraseScorer outerInstance;
public ComparerAnonymousInnerClassHelper(SloppyPhraseScorer outerInstance)
{
this.outerInstance = outerInstance;
}
public virtual int Compare(PhrasePositions pp1, PhrasePositions pp2)
{
return pp1.offset - pp2.offset;
}
}
/// <summary>
/// Detect repetition groups. Done once - for first doc. </summary>
private IList<IList<PhrasePositions>> GatherRptGroups(LinkedHashMap<Term, int?> rptTerms)
{
PhrasePositions[] rpp = RepeatingPPs(rptTerms);
IList<IList<PhrasePositions>> res = new List<IList<PhrasePositions>>();
if (!hasMultiTermRpts)
{
// simpler - no multi-terms - can base on positions in first doc
for (int i = 0; i < rpp.Length; i++)
{
PhrasePositions pp = rpp[i];
if (pp.rptGroup >= 0) // already marked as a repetition
{
continue;
}
int tpPos = TpPos(pp);
for (int j = i + 1; j < rpp.Length; j++)
{
PhrasePositions pp2 = rpp[j];
if (pp2.rptGroup >= 0 || pp2.offset == pp.offset || TpPos(pp2) != tpPos) // not a repetition - not a repetition: two PPs are originally in same offset in the query! - already marked as a repetition
{
continue;
}
// a repetition
int g = pp.rptGroup;
if (g < 0)
{
g = res.Count;
pp.rptGroup = g;
List<PhrasePositions> rl = new List<PhrasePositions>(2);
rl.Add(pp);
res.Add(rl);
}
pp2.rptGroup = g;
res[g].Add(pp2);
}
}
}
else
{
// more involved - has multi-terms
List<HashSet<PhrasePositions>> tmp = new List<HashSet<PhrasePositions>>();
IList<FixedBitSet> bb = PpTermsBitSets(rpp, rptTerms);
UnionTermGroups(bb);
IDictionary<Term, int> tg = TermGroups(rptTerms, bb);
HashSet<int> distinctGroupIDs = new HashSet<int>(tg.Values);
for (int i = 0; i < distinctGroupIDs.Count; i++)
{
tmp.Add(new HashSet<PhrasePositions>());
}
foreach (PhrasePositions pp in rpp)
{
foreach (Term t in pp.terms)
{
if (rptTerms.ContainsKey(t))
{
int g = tg[t];
tmp[g].Add(pp);
Debug.Assert(pp.rptGroup == -1 || pp.rptGroup == g);
pp.rptGroup = g;
}
}
}
foreach (HashSet<PhrasePositions> hs in tmp)
{
res.Add(new List<PhrasePositions>(hs));
}
}
return res;
}
/// <summary>
/// Actual position in doc of a PhrasePosition, relies on that position = tpPos - offset) </summary>
private int TpPos(PhrasePositions pp)
{
return pp.position + pp.offset;
}
/// <summary>
/// Find repeating terms and assign them ordinal values </summary>
private LinkedHashMap<Term, int?> RepeatingTerms()
{
LinkedHashMap<Term, int?> tord = new LinkedHashMap<Term, int?>();
Dictionary<Term, int?> tcnt = new Dictionary<Term, int?>();
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
foreach (Term t in pp.terms)
{
int? cnt0;
tcnt.TryGetValue(t, out cnt0);
int? cnt = cnt0 == null ? new int?(1) : new int?(1 + (int)cnt0);
tcnt[t] = cnt;
if (cnt == 2)
{
tord[t] = tord.Count;
}
}
}
return tord;
}
/// <summary>
/// Find repeating pps, and for each, if has multi-terms, update this.hasMultiTermRpts </summary>
private PhrasePositions[] RepeatingPPs(HashMap<Term, int?> rptTerms)
{
List<PhrasePositions> rp = new List<PhrasePositions>();
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
foreach (Term t in pp.terms)
{
if (rptTerms.ContainsKey(t))
{
rp.Add(pp);
hasMultiTermRpts |= (pp.terms.Length > 1);
break;
}
}
}
return rp.ToArray();
}
/// <summary>
/// bit-sets - for each repeating pp, for each of its repeating terms, the term ordinal values is set </summary>
private IList<FixedBitSet> PpTermsBitSets(PhrasePositions[] rpp, HashMap<Term, int?> tord)
{
List<FixedBitSet> bb = new List<FixedBitSet>(rpp.Length);
foreach (PhrasePositions pp in rpp)
{
FixedBitSet b = new FixedBitSet(tord.Count);
var ord = new int?();
foreach (var t in pp.terms.Where(t => (ord = tord[t]) != null))
{
b.Set((int)ord);
}
bb.Add(b);
}
return bb;
}
/// <summary>
/// Union (term group) bit-sets until they are disjoint (O(n^^2)), and each group have different terms </summary>
private void UnionTermGroups(IList<FixedBitSet> bb)
{
int incr;
for (int i = 0; i < bb.Count - 1; i += incr)
{
incr = 1;
int j = i + 1;
while (j < bb.Count)
{
if (bb[i].Intersects(bb[j]))
{
bb[i].Or(bb[j]);
bb.RemoveAt(j);
incr = 0;
}
else
{
++j;
}
}
}
}
/// <summary>
/// Map each term to the single group that contains it </summary>
private IDictionary<Term, int> TermGroups(LinkedHashMap<Term, int?> tord, IList<FixedBitSet> bb)
{
Dictionary<Term, int> tg = new Dictionary<Term, int>();
Term[] t = tord.Keys.ToArray(/*new Term[0]*/);
for (int i = 0; i < bb.Count; i++) // i is the group no.
{
DocIdSetIterator bits = bb[i].GetIterator();
int ord;
while ((ord = bits.NextDoc()) != NO_MORE_DOCS)
{
tg[t[ord]] = i;
}
}
return tg;
}
public override int Freq
{
get { return numMatches; }
}
internal float SloppyFreq
{
get { return sloppyFreq; }
}
// private void printQueue(PrintStream ps, PhrasePositions ext, String title) {
// //if (min.doc != ?) return;
// ps.println();
// ps.println("---- "+title);
// ps.println("EXT: "+ext);
// PhrasePositions[] t = new PhrasePositions[pq.size()];
// if (pq.size()>0) {
// t[0] = pq.pop();
// ps.println(" " + 0 + " " + t[0]);
// for (int i=1; i<t.length; i++) {
// t[i] = pq.pop();
// assert t[i-1].position <= t[i].position;
// ps.println(" " + i + " " + t[i]);
// }
// // add them back
// for (int i=t.length-1; i>=0; i--) {
// pq.add(t[i]);
// }
// }
// }
private bool AdvanceMin(int target)
{
if (!min.SkipTo(target))
{
max.doc = NO_MORE_DOCS; // for further calls to docID()
return false;
}
min = min.next; // cyclic
max = max.next; // cyclic
return true;
}
public override int DocID
{
get { return max.doc; }
}
public override int NextDoc()
{
return Advance(max.doc + 1); // advance to the next doc after #docID()
}
public override float GetScore()
{
return docScorer.Score(max.doc, sloppyFreq);
}
public override int Advance(int target)
{
Debug.Assert(target > DocID);
do
{
if (!AdvanceMin(target))
{
return NO_MORE_DOCS;
}
while (min.doc < max.doc)
{
if (!AdvanceMin(max.doc))
{
return NO_MORE_DOCS;
}
}
// found a doc with all of the terms
sloppyFreq = PhraseFreq(); // check for phrase
target = min.doc + 1; // next target in case sloppyFreq is still 0
} while (sloppyFreq == 0f);
// found a match
return max.doc;
}
public override long GetCost()
{
return cost;
}
public override string ToString()
{
return "scorer(" + m_weight + ")";
}
}
}
| |
// SF API version v50.0
// Custom fields included: False
// Relationship objects included: True
using System;
using NetCoreForce.Client.Models;
using NetCoreForce.Client.Attributes;
using Newtonsoft.Json;
namespace NetCoreForce.Models
{
///<summary>
/// Flow Definition
///<para>SObject Name: FlowDefinitionView</para>
///<para>Custom Object: False</para>
///</summary>
public class SfFlowDefinitionView : SObject
{
[JsonIgnore]
public static string SObjectTypeName
{
get { return "FlowDefinitionView"; }
}
///<summary>
/// Flow Definition View ID
/// <para>Name: Id</para>
/// <para>SF Type: id</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "id")]
[Updateable(false), Createable(false)]
public string Id { get; set; }
///<summary>
/// Durable ID
/// <para>Name: DurableId</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "durableId")]
[Updateable(false), Createable(false)]
public string DurableId { get; set; }
///<summary>
/// Flow API Name
/// <para>Name: ApiName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "apiName")]
[Updateable(false), Createable(false)]
public string ApiName { get; set; }
///<summary>
/// Flow Label
/// <para>Name: Label</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "label")]
[Updateable(false), Createable(false)]
public string Label { get; set; }
///<summary>
/// Flow Description
/// <para>Name: Description</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "description")]
[Updateable(false), Createable(false)]
public string Description { get; set; }
///<summary>
/// Process Type
/// <para>Name: ProcessType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "processType")]
[Updateable(false), Createable(false)]
public string ProcessType { get; set; }
///<summary>
/// Trigger
/// <para>Name: TriggerType</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "triggerType")]
[Updateable(false), Createable(false)]
public string TriggerType { get; set; }
///<summary>
/// Flow Namespace
/// <para>Name: NamespacePrefix</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "namespacePrefix")]
[Updateable(false), Createable(false)]
public string NamespacePrefix { get; set; }
///<summary>
/// Active Flow Version API Name or ID
/// <para>Name: ActiveVersionId</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "activeVersionId")]
[Updateable(false), Createable(false)]
public string ActiveVersionId { get; set; }
///<summary>
/// Latest Flow Version API Name or ID
/// <para>Name: LatestVersionId</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "latestVersionId")]
[Updateable(false), Createable(false)]
public string LatestVersionId { get; set; }
///<summary>
/// Last Modified By
/// <para>Name: LastModifiedBy</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedBy")]
[Updateable(false), Createable(false)]
public string LastModifiedBy { get; set; }
///<summary>
/// Active
/// <para>Name: IsActive</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isActive")]
[Updateable(false), Createable(false)]
public bool? IsActive { get; set; }
///<summary>
/// Is Using an Older Version
/// <para>Name: IsOutOfDate</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isOutOfDate")]
[Updateable(false), Createable(false)]
public bool? IsOutOfDate { get; set; }
///<summary>
/// Last Modified Date
/// <para>Name: LastModifiedDate</para>
/// <para>SF Type: datetime</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "lastModifiedDate")]
[Updateable(false), Createable(false)]
public DateTimeOffset? LastModifiedDate { get; set; }
///<summary>
/// Template
/// <para>Name: IsTemplate</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isTemplate")]
[Updateable(false), Createable(false)]
public bool? IsTemplate { get; set; }
///<summary>
/// Is Swing Flow
/// <para>Name: IsSwingFlow</para>
/// <para>SF Type: boolean</para>
/// <para>Nillable: False</para>
///</summary>
[JsonProperty(PropertyName = "isSwingFlow")]
[Updateable(false), Createable(false)]
public bool? IsSwingFlow { get; set; }
///<summary>
/// Built with
/// <para>Name: Builder</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "builder")]
[Updateable(false), Createable(false)]
public string Builder { get; set; }
///<summary>
/// Package State
/// <para>Name: ManageableState</para>
/// <para>SF Type: picklist</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "manageableState")]
[Updateable(false), Createable(false)]
public string ManageableState { get; set; }
///<summary>
/// Package Name
/// <para>Name: InstalledPackageName</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "installedPackageName")]
[Updateable(false), Createable(false)]
public string InstalledPackageName { get; set; }
///<summary>
/// Preview Label
/// <para>Name: GuestMasterLabel</para>
/// <para>SF Type: string</para>
/// <para>Nillable: True</para>
///</summary>
[JsonProperty(PropertyName = "guestMasterLabel")]
[Updateable(false), Createable(false)]
public string GuestMasterLabel { get; set; }
}
}
| |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* 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 Poly2Tri 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.
*/
/// Changes from the Java version
/// attributification
/// Future possibilities
/// Flattening out the number of indirections
/// Replacing arrays of 3 with fixed-length arrays?
/// Replacing bool[3] with a bit array of some sort?
/// Bundling everything into an AoS mess?
/// Hardcode them all as ABC ?
using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace Poly2Tri
{
public class DelaunayTriangle
{
public FixedArray3<TriangulationPoint> Points;
public FixedArray3<DelaunayTriangle> Neighbors;
private FixedBitArray3 mEdgeIsConstrained;
public FixedBitArray3 EdgeIsConstrained { get { return mEdgeIsConstrained; } }
public FixedBitArray3 EdgeIsDelaunay;
public bool IsInterior { get; set; }
public DelaunayTriangle(TriangulationPoint p1, TriangulationPoint p2, TriangulationPoint p3)
{
Points[0] = p1;
Points[1] = p2;
Points[2] = p3;
}
public int IndexOf(TriangulationPoint p)
{
int i = Points.IndexOf(p);
if (i == -1)
{
throw new Exception("Calling index with a point that doesn't exist in triangle");
}
return i;
}
public int IndexCWFrom(TriangulationPoint p)
{
return (IndexOf(p) + 2) % 3;
}
public int IndexCCWFrom(TriangulationPoint p)
{
return (IndexOf(p) + 1) % 3;
}
public bool Contains(TriangulationPoint p)
{
return Points.Contains(p);
}
/// <summary>
/// Update neighbor pointers
/// </summary>
/// <param name="p1">Point 1 of the shared edge</param>
/// <param name="p2">Point 2 of the shared edge</param>
/// <param name="t">This triangle's new neighbor</param>
private void MarkNeighbor(TriangulationPoint p1, TriangulationPoint p2, DelaunayTriangle t)
{
int i = EdgeIndex(p1, p2);
if (i == -1)
{
throw new Exception("Error marking neighbors -- t doesn't contain edge p1-p2!");
}
Neighbors[i] = t;
}
/// <summary>
/// Exhaustive search to update neighbor pointers
/// </summary>
public void MarkNeighbor(DelaunayTriangle t)
{
// Points of this triangle also belonging to t
bool a = t.Contains(Points[0]);
bool b = t.Contains(Points[1]);
bool c = t.Contains(Points[2]);
if (b && c)
{
Neighbors[0] = t;
t.MarkNeighbor(Points[1], Points[2], this);
}
else if (a && c)
{
Neighbors[1] = t;
t.MarkNeighbor(Points[0], Points[2], this);
}
else if (a && b)
{
Neighbors[2] = t;
t.MarkNeighbor(Points[0], Points[1], this);
}
// else
// {
// throw new Exception("Failed to mark neighbor, doesn't share an edge!");
// }
}
public bool SharedEdge(TriangulationPoint p1, TriangulationPoint p2)
{
bool shared = false;
foreach (DelaunayTriangle t in Neighbors)
{
if (t != null)
{
if (t.Contains(p1) && t.Contains(p2))
{
shared = true;
}
else
{
}
}
else
{
}
}
return shared;
}
public void ClearNeighbors()
{
Neighbors[0] = Neighbors[1] = Neighbors[2] = null;
}
public void ClearNeighbor(DelaunayTriangle triangle)
{
if (Neighbors[0] == triangle)
{
Neighbors[0] = null;
}
else if (Neighbors[1] == triangle)
{
Neighbors[1] = null;
}
else if (Neighbors[2] == triangle)
{
Neighbors[2] = null;
}
}
/// <summary>
/// Clears all references to all other triangles and points
/// </summary>
public void Clear()
{
DelaunayTriangle t;
for (int i = 0; i < 3; i++)
{
t = Neighbors[i];
if (t != null)
{
t.ClearNeighbor(this);
}
}
ClearNeighbors();
Points[0] = Points[1] = Points[2] = null;
}
/// <param name="t">Opposite triangle</param>
/// <param name="p">The point in t that isn't shared between the triangles</param>
public TriangulationPoint OppositePoint(DelaunayTriangle t, TriangulationPoint p)
{
Debug.Assert(t != this, "self-pointer error");
return PointCWFrom(t.PointCWFrom(p));
}
public DelaunayTriangle NeighborCWFrom(TriangulationPoint point)
{
return Neighbors[(Points.IndexOf(point) + 1) % 3];
}
public DelaunayTriangle NeighborCCWFrom(TriangulationPoint point)
{
return Neighbors[(Points.IndexOf(point) + 2) % 3];
}
public DelaunayTriangle NeighborAcrossFrom(TriangulationPoint point)
{
return Neighbors[Points.IndexOf(point)];
}
public TriangulationPoint PointCCWFrom(TriangulationPoint point)
{
return Points[(IndexOf(point) + 1) % 3];
}
public TriangulationPoint PointCWFrom(TriangulationPoint point)
{
return Points[(IndexOf(point) + 2) % 3];
}
private void RotateCW()
{
var t = Points[2];
Points[2] = Points[1];
Points[1] = Points[0];
Points[0] = t;
}
/// <summary>
/// Legalize triangle by rotating clockwise around oPoint
/// </summary>
/// <param name="oPoint">The origin point to rotate around</param>
/// <param name="nPoint">???</param>
public void Legalize(TriangulationPoint oPoint, TriangulationPoint nPoint)
{
RotateCW();
Points[IndexCCWFrom(oPoint)] = nPoint;
}
public override string ToString()
{
return Points[0] + "," + Points[1] + "," + Points[2];
}
/// <summary>
/// Finalize edge marking
/// </summary>
public void MarkNeighborEdges()
{
for (int i = 0; i < 3; i++)
{
if (EdgeIsConstrained[i] && Neighbors[i] != null)
{
Neighbors[i].MarkConstrainedEdge(Points[(i + 1) % 3], Points[(i + 2) % 3]);
}
}
}
public void MarkEdge(DelaunayTriangle triangle)
{
for (int i = 0; i < 3; i++)
if (EdgeIsConstrained[i])
{
triangle.MarkConstrainedEdge(Points[(i + 1) % 3], Points[(i + 2) % 3]);
}
}
public void MarkEdge(List<DelaunayTriangle> tList)
{
foreach (DelaunayTriangle t in tList)
{
for (int i = 0; i < 3; i++)
{
if (t.EdgeIsConstrained[i])
{
MarkConstrainedEdge(t.Points[(i + 1) % 3], t.Points[(i + 2) % 3]);
}
}
}
}
public void MarkConstrainedEdge(int index)
{
mEdgeIsConstrained[index] = true;
}
public void MarkConstrainedEdge(DTSweepConstraint edge)
{
MarkConstrainedEdge(edge.P, edge.Q);
}
/// <summary>
/// Mark edge as constrained
/// </summary>
public void MarkConstrainedEdge(TriangulationPoint p, TriangulationPoint q)
{
int i = EdgeIndex(p, q);
if (i != -1)
{
mEdgeIsConstrained[i] = true;
}
}
public double Area()
{
double b = Points[0].X - Points[1].X;
double h = Points[2].Y - Points[1].Y;
return Math.Abs((b * h * 0.5f));
}
public TriangulationPoint Centroid()
{
double cx = (Points[0].X + Points[1].X + Points[2].X) / 3f;
double cy = (Points[0].Y + Points[1].Y + Points[2].Y) / 3f;
return new TriangulationPoint(cx, cy);
}
/// <summary>
/// Get the index of the neighbor that shares this edge (or -1 if it isn't shared)
/// </summary>
/// <returns>index of the shared edge or -1 if edge isn't shared</returns>
public int EdgeIndex(TriangulationPoint p1, TriangulationPoint p2)
{
int i1 = Points.IndexOf(p1);
int i2 = Points.IndexOf(p2);
// Points of this triangle in the edge p1-p2
bool a = (i1 == 0 || i2 == 0);
bool b = (i1 == 1 || i2 == 1);
bool c = (i1 == 2 || i2 == 2);
if (b && c)
{
return 0;
}
if (a && c)
{
return 1;
}
if (a && b)
{
return 2;
}
return -1;
}
public bool GetConstrainedEdgeCCW(TriangulationPoint p)
{
return EdgeIsConstrained[(IndexOf(p) + 2) % 3];
}
public bool GetConstrainedEdgeCW(TriangulationPoint p)
{
return EdgeIsConstrained[(IndexOf(p) + 1) % 3];
}
public bool GetConstrainedEdgeAcross(TriangulationPoint p)
{
return EdgeIsConstrained[IndexOf(p)];
}
protected void SetConstrainedEdge(int idx, bool ce)
{
//if (ce == false && EdgeIsConstrained[idx])
//{
// DTSweepConstraint edge = null;
// if (GetEdge(idx, out edge))
// {
// Console.WriteLine("Removing pre-defined constraint from edge " + edge.ToString());
// }
//}
mEdgeIsConstrained[idx] = ce;
}
public void SetConstrainedEdgeCCW(TriangulationPoint p, bool ce)
{
int idx = (IndexOf(p) + 2) % 3;
SetConstrainedEdge(idx, ce);
}
public void SetConstrainedEdgeCW(TriangulationPoint p, bool ce)
{
int idx = (IndexOf(p) + 1) % 3;
SetConstrainedEdge(idx, ce);
}
public void SetConstrainedEdgeAcross(TriangulationPoint p, bool ce)
{
int idx = IndexOf(p);
SetConstrainedEdge(idx, ce);
}
public bool GetDelaunayEdgeCCW(TriangulationPoint p)
{
return EdgeIsDelaunay[(IndexOf(p) + 2) % 3];
}
public bool GetDelaunayEdgeCW(TriangulationPoint p)
{
return EdgeIsDelaunay[(IndexOf(p) + 1) % 3];
}
public bool GetDelaunayEdgeAcross(TriangulationPoint p)
{
return EdgeIsDelaunay[IndexOf(p)];
}
public void SetDelaunayEdgeCCW(TriangulationPoint p, bool ce)
{
EdgeIsDelaunay[(IndexOf(p) + 2) % 3] = ce;
}
public void SetDelaunayEdgeCW(TriangulationPoint p, bool ce)
{
EdgeIsDelaunay[(IndexOf(p) + 1) % 3] = ce;
}
public void SetDelaunayEdgeAcross(TriangulationPoint p, bool ce)
{
EdgeIsDelaunay[IndexOf(p)] = ce;
}
public bool GetEdge(int idx, out DTSweepConstraint edge)
{
edge = null;
if (idx < 0 || idx > 2)
{
return false;
}
TriangulationPoint p1 = Points[(idx + 1) % 3];
TriangulationPoint p2 = Points[(idx + 2) % 3];
if (p1.GetEdge(p2, out edge))
{
return true;
}
else if (p2.GetEdge(p1, out edge))
{
return true;
}
return false;
}
public bool GetEdgeCCW(TriangulationPoint p, out DTSweepConstraint edge)
{
int pointIndex = IndexOf(p);
int edgeIdx = (pointIndex + 2) % 3;
return GetEdge(edgeIdx, out edge);
}
public bool GetEdgeCW(TriangulationPoint p, out DTSweepConstraint edge)
{
int pointIndex = IndexOf(p);
int edgeIdx = (pointIndex + 1) % 3;
return GetEdge(edgeIdx, out edge);
}
public bool GetEdgeAcross(TriangulationPoint p, out DTSweepConstraint edge)
{
int pointIndex = IndexOf(p);
int edgeIdx = pointIndex;
return GetEdge(edgeIdx, out edge);
}
}
}
| |
/*
THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.
This is sample code and is freely distributable.
*/
using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
namespace DigitalPlatform.Drawing
{
/// <summary>
/// Quantize using an Octree
/// </summary>
public unsafe class OctreeQuantizer : Quantizer
{
public Color TransparentColor = Color.Black;
/// <summary>
/// Construct the octree quantizer
/// </summary>
/// <remarks>
/// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree,
/// the second pass quantizes a color based on the nodes in the tree
/// </remarks>
/// <param name="maxColors">The maximum number of colors to return</param>
/// <param name="maxColorBits">The number of significant bits</param>
public OctreeQuantizer(int maxColors, int maxColorBits)
: base(false)
{
if (maxColors > 255)
throw new ArgumentOutOfRangeException("maxColors", maxColors, "The number of colors should be less than 256");
if ((maxColorBits < 1) | (maxColorBits > 8))
throw new ArgumentOutOfRangeException("maxColorBits", maxColorBits, "This should be between 1 and 8");
// Construct the octree
_octree = new Octree(maxColorBits);
_maxColors = maxColors;
}
/// <summary>
/// Process the pixel in the first pass of the algorithm
/// </summary>
/// <param name="pixel">The pixel to quantize</param>
/// <remarks>
/// This function need only be overridden if your quantize algorithm needs two passes,
/// such as an Octree quantizer.
/// </remarks>
protected override void InitialQuantizePixel(Color32* pixel)
{
// Add the color to the octree
_octree.AddColor(pixel);
}
/// <summary>
/// Override this to process the pixel in the second pass of the algorithm
/// </summary>
/// <param name="pixel">The pixel to quantize</param>
/// <returns>The quantized value</returns>
protected override byte QuantizePixel(Color32* pixel)
{
byte paletteIndex = (byte)_maxColors; // The color at [_maxColors] is set to transparent
// Get the palette index if this non-transparent
if (pixel->Alpha > 0)
paletteIndex = (byte)_octree.GetPaletteIndex(pixel);
return paletteIndex;
}
// private Hashtable _colorMap;
//
// protected override byte QuantizePixel(Color32* pixel)
// {
// byte colorIndex = 0 ;
// int colorHash = pixel->GetHashCode();
// Color [] colors = this._currentPalette.Entries;
//
// // Check if the color is in the lookup table
// if ( _colorMap.ContainsKey ( colorHash ) )
// colorIndex = (byte)_colorMap[colorHash] ;
// else
// {
// // Not found - loop through the palette and find the nearest match.
// // Firstly check the alpha value - if 0,
// // lookup the transparent color
// if (pixel->Alpha > 0)
// {
// // Not transparent...
// int leastDistance = int.MaxValue ;
// int red = pixel->Red ;
// int green = pixel->Green;
// int blue = pixel->Blue;
//
// // Loop through the entire palette, looking for the closest color match
// for( int index = 0 ; index < colors.Length ; index++ )
// {
// Color paletteColor = colors[index];
//
// int redDistance = paletteColor.R - red ;
// int greenDistance = paletteColor.G - green ;
// int blueDistance = paletteColor.B - blue ;
//
// int distance =
// ( redDistance * redDistance ) +
// ( greenDistance * greenDistance ) +
// ( blueDistance * blueDistance ) ;
//
// if( distance < leastDistance )
// {
// colorIndex = (byte)index ;
// leastDistance = distance ;
//
// // And if it's an exact match,
// // exit the loop
// if( 0 == distance )
// break ;
// }
// }
// }
//
// // Now I have the color, pop it into the
// // hashtable for next time
// _colorMap.Add ( colorHash , colorIndex ) ;
// }
//
// return colorIndex ;
// }
/// <summary>
/// Retrieve the palette for the quantized image
/// </summary>
/// <param name="original">Any old palette, this is overrwritten</param>
/// <returns>The new color palette</returns>
protected override ColorPalette GetPalette(ColorPalette original)
{
// First off convert the octree to _maxColors colors
ArrayList palette = _octree.Palletize(_maxColors - 1);
// Then convert the palette based on those colors
for (int index = 0; index < palette.Count; index++)
original.Entries[index] = (Color)palette[index];
// Add the transparent color
// original.Entries[_maxColors] = Color.FromArgb(0, 0, 0, 0);
original.Entries[_maxColors] = Color.FromArgb(0, this.TransparentColor);
return original;
}
/// <summary>
/// Stores the tree
/// </summary>
private Octree _octree;
/// <summary>
/// Maximum allowed color depth
/// </summary>
private int _maxColors;
/// <summary>
/// Class which does the actual quantization
/// </summary>
private class Octree
{
/// <summary>
/// Construct the octree
/// </summary>
/// <param name="maxColorBits">The maximum number of significant bits in the image</param>
public Octree(int maxColorBits)
{
_maxColorBits = maxColorBits;
_leafCount = 0;
_reducibleNodes = new OctreeNode[9];
_root = new OctreeNode(0, _maxColorBits, this);
_previousColor = 0;
_previousNode = null;
}
/// <summary>
/// Add a given color value to the octree
/// </summary>
/// <param name="pixel"></param>
public void AddColor(Color32* pixel)
{
// Check if this request is for the same color as the last
if (_previousColor == pixel->ARGB)
{
// If so, check if I have a previous node setup. This will only ocurr if the first color in the image
// happens to be black, with an alpha component of zero.
if (null == _previousNode)
{
_previousColor = pixel->ARGB;
_root.AddColor(pixel, _maxColorBits, 0, this);
}
else
// Just update the previous node
_previousNode.Increment(pixel);
}
else
{
_previousColor = pixel->ARGB;
_root.AddColor(pixel, _maxColorBits, 0, this);
}
}
/// <summary>
/// Reduce the depth of the tree
/// </summary>
public void Reduce()
{
int index;
// Find the deepest level containing at least one reducible node
for (index = _maxColorBits - 1; (index > 0) && (null == _reducibleNodes[index]); index--) ;
// Reduce the node most recently added to the list at level 'index'
OctreeNode node = _reducibleNodes[index];
_reducibleNodes[index] = node.NextReducible;
// Decrement the leaf count after reducing the node
_leafCount -= node.Reduce();
// And just in case I've reduced the last color to be added, and the next color to
// be added is the same, invalidate the previousNode...
_previousNode = null;
}
/// <summary>
/// Get/Set the number of leaves in the tree
/// </summary>
public int Leaves
{
get { return _leafCount; }
set { _leafCount = value; }
}
/// <summary>
/// Return the array of reducible nodes
/// </summary>
protected OctreeNode[] ReducibleNodes
{
get { return _reducibleNodes; }
}
/// <summary>
/// Keep track of the previous node that was quantized
/// </summary>
/// <param name="node">The node last quantized</param>
protected void TrackPrevious(OctreeNode node)
{
_previousNode = node;
}
/// <summary>
/// Convert the nodes in the octree to a palette with a maximum of colorCount colors
/// </summary>
/// <param name="colorCount">The maximum number of colors</param>
/// <returns>An arraylist with the palettized colors</returns>
public ArrayList Palletize(int colorCount)
{
while (Leaves > colorCount)
Reduce();
// Now palettize the nodes
ArrayList palette = new ArrayList(Leaves);
int paletteIndex = 0;
_root.ConstructPalette(palette, ref paletteIndex);
// And return the palette
return palette;
}
/// <summary>
/// Get the palette index for the passed color
/// </summary>
/// <param name="pixel"></param>
/// <returns>index</returns>
public int GetPaletteIndex(Color32* pixel)
{
return _root.GetPaletteIndex(pixel, 0);
}
/// <summary>
/// Mask used when getting the appropriate pixels for a given node
/// </summary>
private static int[] mask = new int[8] { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
/// <summary>
/// The root of the octree
/// </summary>
private OctreeNode _root;
/// <summary>
/// Number of leaves in the tree
/// </summary>
private int _leafCount;
/// <summary>
/// Array of reducible nodes
/// </summary>
private OctreeNode[] _reducibleNodes;
/// <summary>
/// Maximum number of significant bits in the image
/// </summary>
private int _maxColorBits;
/// <summary>
/// Store the last node quantized
/// </summary>
private OctreeNode _previousNode;
/// <summary>
/// Cache the previous color quantized
/// </summary>
private int _previousColor;
/// <summary>
/// Class which encapsulates each node in the tree
/// </summary>
protected class OctreeNode
{
/// <summary>
/// Construct the node
/// </summary>
/// <param name="level">The level in the tree = 0 - 7</param>
/// <param name="colorBits">The number of significant color bits in the image</param>
/// <param name="octree">The tree to which this node belongs</param>
public OctreeNode(int level, int colorBits, Octree octree)
{
// Construct the new node
_leaf = (level == colorBits);
_red = _green = _blue = 0;
_pixelCount = 0;
// If a leaf, increment the leaf count
if (_leaf)
{
octree.Leaves++;
_nextReducible = null;
_children = null;
}
else
{
// Otherwise add this to the reducible nodes
_nextReducible = octree.ReducibleNodes[level];
octree.ReducibleNodes[level] = this;
_children = new OctreeNode[8];
}
}
/// <summary>
/// Add a color into the tree
/// </summary>
/// <param name="pixel">The color</param>
/// <param name="colorBits">The number of significant color bits</param>
/// <param name="level">The level in the tree</param>
/// <param name="octree">The tree to which this node belongs</param>
public void AddColor(Color32* pixel, int colorBits, int level, Octree octree)
{
// Update the color information if this is a leaf
if (_leaf)
{
Increment(pixel);
// Setup the previous node
octree.TrackPrevious(this);
}
else
{
// Go to the next level down in the tree
int shift = 7 - level;
int index = ((pixel->Red & mask[level]) >> (shift - 2)) |
((pixel->Green & mask[level]) >> (shift - 1)) |
((pixel->Blue & mask[level]) >> (shift));
OctreeNode child = _children[index];
if (null == child)
{
// Create a new child node & store in the array
child = new OctreeNode(level + 1, colorBits, octree);
_children[index] = child;
}
// Add the color to the child node
child.AddColor(pixel, colorBits, level + 1, octree);
}
}
/// <summary>
/// Get/Set the next reducible node
/// </summary>
public OctreeNode NextReducible
{
get { return _nextReducible; }
set { _nextReducible = value; }
}
/// <summary>
/// Return the child nodes
/// </summary>
public OctreeNode[] Children
{
get { return _children; }
}
/// <summary>
/// Reduce this node by removing all of its children
/// </summary>
/// <returns>The number of leaves removed</returns>
public int Reduce()
{
_red = _green = _blue = 0;
int children = 0;
// Loop through all children and add their information to this node
for (int index = 0; index < 8; index++)
{
if (null != _children[index])
{
_red += _children[index]._red;
_green += _children[index]._green;
_blue += _children[index]._blue;
_pixelCount += _children[index]._pixelCount;
++children;
_children[index] = null;
}
}
// Now change this to a leaf node
_leaf = true;
// Return the number of nodes to decrement the leaf count by
return (children - 1);
}
/// <summary>
/// Traverse the tree, building up the color palette
/// </summary>
/// <param name="palette">The palette</param>
/// <param name="paletteIndex">The current palette index</param>
public void ConstructPalette(ArrayList palette, ref int paletteIndex)
{
if (_leaf)
{
// Consume the next palette index
_paletteIndex = paletteIndex++;
// And set the color of the palette entry
palette.Add(Color.FromArgb(_red / _pixelCount, _green / _pixelCount, _blue / _pixelCount));
}
else
{
// Loop through children looking for leaves
for (int index = 0; index < 8; index++)
{
if (null != _children[index])
_children[index].ConstructPalette(palette, ref paletteIndex);
}
}
}
/// <summary>
/// Return the palette index for the passed color
/// </summary>
public int GetPaletteIndex(Color32* pixel, int level)
{
int paletteIndex = _paletteIndex;
if (!_leaf)
{
int shift = 7 - level;
int index = ((pixel->Red & mask[level]) >> (shift - 2)) |
((pixel->Green & mask[level]) >> (shift - 1)) |
((pixel->Blue & mask[level]) >> (shift));
if (null != _children[index])
paletteIndex = _children[index].GetPaletteIndex(pixel, level + 1);
else
throw new Exception("Didn't expect this!");
}
return paletteIndex;
}
/// <summary>
/// Increment the pixel count and add to the color information
/// </summary>
public void Increment(Color32* pixel)
{
_pixelCount++;
_red += pixel->Red;
_green += pixel->Green;
_blue += pixel->Blue;
}
/// <summary>
/// Flag indicating that this is a leaf node
/// </summary>
private bool _leaf;
/// <summary>
/// Number of pixels in this node
/// </summary>
private int _pixelCount;
/// <summary>
/// Red component
/// </summary>
private int _red;
/// <summary>
/// Green Component
/// </summary>
private int _green;
/// <summary>
/// Blue component
/// </summary>
private int _blue;
/// <summary>
/// Pointers to any child nodes
/// </summary>
private OctreeNode[] _children;
/// <summary>
/// Pointer to next reducible node
/// </summary>
private OctreeNode _nextReducible;
/// <summary>
/// The index of this node in the palette
/// </summary>
private int _paletteIndex;
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using ASC.Api.Attributes;
using ASC.Api.Collections;
using ASC.Api.CRM.Wrappers;
using ASC.Api.Exceptions;
using ASC.CRM.Core;
using ASC.CRM.Core.Entities;
using ASC.ElasticSearch;
using ASC.MessagingSystem;
using ASC.Web.CRM.Core.Search;
namespace ASC.Api.CRM
{
public partial class CRMApi
{
/// <summary>
/// Returns the list of descriptions for all existing user fields
/// </summary>
/// <param name="entityType" remark="Allowed values: contact,person,company,opportunity,case">Type</param>
/// <short>Get user field list</short>
/// <category>User fields</category>
///<returns>
/// User field list
/// </returns>
///<exception cref="ArgumentException"></exception>
[Read(@"{entityType:(contact|person|company|opportunity|case)}/customfield/definitions")]
public IEnumerable<CustomFieldWrapper> GetCustomFieldDefinitions(string entityType)
{
return DaoFactory.CustomFieldDao.GetFieldsDescription(ToEntityType(entityType)).ConvertAll(ToCustomFieldWrapper).ToSmartList();
}
/// <summary>
/// Returns the list of all user field values using the entity type and entity ID specified in the request
/// </summary>
/// <param name="entityType" remark="Allowed values: contact,person,company,opportunity,case">Type</param>
/// <param name="entityid">ID</param>
/// <short>Get user field values</short>
/// <category>User fields</category>
/// <returns></returns>
[Read(@"{entityType:(contact|person|company|opportunity|case)}/{entityid:[0-9]+}/customfield")]
public IEnumerable<CustomFieldBaseWrapper> GetCustomFieldForSubject(string entityType, int entityid)
{
return DaoFactory.CustomFieldDao.GetEntityFields(ToEntityType(entityType), entityid, false).ConvertAll(ToCustomFieldBaseWrapper).ToItemList();
}
/// <summary>
/// Sets the new user field value using the entity type, ID, field ID and value specified in the request
/// </summary>
/// <param name="entityType" remark="Allowed values: contact,person,company,opportunity,case">Type</param>
/// <param name="entityid">ID</param>
/// <param name="fieldid">Field ID</param>
/// <param name="fieldValue">Field Value</param>
/// <short>Set user field value</short>
/// <category>User fields</category>
/// <returns>
/// User field
/// </returns>
[Create(@"{entityType:(contact|person|company|opportunity|case)}/{entityid:[0-9]+}/customfield/{fieldid:[0-9]+}")]
public CustomFieldBaseWrapper SetEntityCustomFieldValue(string entityType, int entityid, int fieldid, string fieldValue)
{
var customField = DaoFactory.CustomFieldDao.GetFieldDescription(fieldid);
var entityTypeStr = ToEntityType(entityType);
customField.EntityID = entityid;
customField.Value = fieldValue;
DaoFactory.CustomFieldDao.SetFieldValue(entityTypeStr, entityid, fieldid, fieldValue);
return ToCustomFieldBaseWrapper(customField);
}
/// <summary>
/// Creates a new user field with the parameters (entity type, field title, type, etc.) specified in the request
/// </summary>
/// <param optional="false" name="entityType" remark="Allowed values: contact,person,company,opportunity,case">Entity type</param>
/// <param optional="false" name="label">Field title</param>
/// <param name="fieldType"
/// remark="Allowed values: TextField, TextArea, SelectBox, CheckBox, Heading or Date">
/// User field value
/// </param>
/// <param optional="true" name="position">Field position</param>
/// <param optional="true" name="mask" remark="Sent in json format only" >Mask</param>
/// <short>Create user field</short>
/// <category>User fields</category>
/// <returns>
/// User field
/// </returns>
///<example>
/// <![CDATA[
///
/// Data transfer in application/json format:
///
/// 1) Creation of a user field of TextField type
///
/// data: {
/// entityType: "contact",
/// label: "Sample TextField",
/// fieldType: 0,
/// position: 0,
/// mask: {"size":"40"} - this is the text field size. All other values are ignored.
/// }
///
///
/// 2) Creation of a user field of TextArea type
///
/// data: {
/// entityType: "contact",
/// label: "Sample TextArea",
/// fieldType: 1,
/// position: 1,
/// mask: '{"rows":"2","cols":"30"}' - this is the TextArea size. All other values are ignored.
/// }
///
///
/// 3) Creation of a user field of SelectBox type
///
/// data: {
/// entityType: "contact",
/// label: "Sample SelectBox",
/// fieldType: 2,
/// position: 0,
/// mask: ["1","2","3"] - SelectBox values.
/// }
///
///
///
/// 4) Creation of a user field of CheckBox type
///
/// data: {
/// entityType: "contact",
/// label: "Sample CheckBox",
/// fieldType: 3,
/// position: 0,
/// mask: ""
/// }
///
///
///
/// 5) Creation of a user field of Heading type
///
/// data: {
/// entityType: "contact",
/// label: "Sample Heading",
/// fieldType: 4,
/// position: 0,
/// mask: ""
/// }
///
///
///
/// 6) Creation of a user field of Date type
///
/// data: {
/// entityType: "contact",
/// label: "Sample Date",
/// fieldType: 5,
/// position: 0,
/// mask: ""
/// }
///
///
/// ]]>
/// </example>
[Create(@"{entityType:(contact|person|company|opportunity|case)}/customfield")]
public CustomFieldWrapper CreateCustomFieldValue(string entityType, string label, int fieldType, int position, string mask)
{
if (!(CRMSecurity.IsAdmin)) throw CRMSecurity.CreateSecurityException();
var entityTypeObj = ToEntityType(entityType);
var fieldID = DaoFactory.CustomFieldDao.CreateField(entityTypeObj, label, (CustomFieldType)fieldType, mask);
var wrapper = DaoFactory.CustomFieldDao.GetFieldDescription(fieldID);
var messageAction = GetCustomFieldCreatedAction(entityTypeObj);
MessageService.Send(Request, messageAction, MessageTarget.Create(wrapper.ID), wrapper.Label);
return ToCustomFieldWrapper(DaoFactory.CustomFieldDao.GetFieldDescription(fieldID));
}
/// <summary>
/// Updates the selected user field with the parameters (entity type, field title, type, etc.) specified in the request
/// </summary>
/// <param name="id">User field id</param>
/// <param name="entityType" remark="Allowed values: contact,person,company,opportunity,case">Entity type</param>
/// <param optional="false" name="label">Field title</param>
/// <param name="fieldType"
/// remark="Allowed values: 0 (TextField),1 (TextArea),2 (SelectBox),3 (CheckBox),4 (Heading) or 5 (Date)">
/// User field value
/// </param>
/// <param optional="true" name="position">Field position</param>
/// <param optional="true" name="mask" remark="Sent in json format only" >Mask</param>
/// <short> Updates the selected user field</short>
/// <category>User fields</category>
/// <returns>
/// User field
/// </returns>
///<remarks>
/// <![CDATA[
/// You can update field if there is no related elements. If such elements exist there will be updated only label and mask, other parameters will be ignored.
/// ]]>
/// </remarks>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
[Update(@"{entityType:(contact|person|company|opportunity|case)}/customfield/{id:[0-9]+}")]
public CustomFieldWrapper UpdateCustomFieldValue(int id, string entityType, string label, int fieldType, int position, string mask)
{
if (id <= 0) throw new ArgumentException();
if (!DaoFactory.CustomFieldDao.IsExist(id)) throw new ItemNotFoundException();
var entityTypeObj = ToEntityType(entityType);
var customField = new CustomField
{
EntityType = entityTypeObj,
FieldType = (CustomFieldType)fieldType,
ID = id,
Mask = mask,
Label = label,
Position = position
};
DaoFactory.CustomFieldDao.EditItem(customField);
customField = DaoFactory.CustomFieldDao.GetFieldDescription(id);
var messageAction = GetCustomFieldUpdatedAction(entityTypeObj);
MessageService.Send(Request, messageAction, MessageTarget.Create(customField.ID), customField.Label);
return ToCustomFieldWrapper(customField);
}
/// <summary>
/// Deletes the user field with the ID specified in the request
/// </summary>
/// <param name="entityType" remark="Allowed values: contact,person,company,opportunity,case">Type</param>
/// <param name="fieldid">Field ID</param>
/// <short>Delete user field</short>
/// <category>User fields</category>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
/// <returns>
/// User field
/// </returns>
[Delete(@"{entityType:(contact|person|company|opportunity|case)}/customfield/{fieldid:[0-9]+}")]
public CustomFieldWrapper DeleteCustomField(string entityType, int fieldid)
{
if (!(CRMSecurity.IsAdmin)) throw CRMSecurity.CreateSecurityException();
if (fieldid <= 0) throw new ArgumentException();
var customField = DaoFactory.CustomFieldDao.GetFieldDescription(fieldid);
if (customField == null) throw new ItemNotFoundException();
var result = ToCustomFieldWrapper(customField);
DaoFactory.CustomFieldDao.DeleteField(fieldid);
FactoryIndexer<FieldsWrapper>.DeleteAsync(customField);
var messageAction = GetCustomFieldDeletedAction(ToEntityType(entityType));
MessageService.Send(Request, messageAction, MessageTarget.Create(customField.ID), result.Label);
return result;
}
/// <summary>
/// Updates user fields order
/// </summary>
/// <param name="fieldids">User field ID list</param>
/// <param name="entityType" remark="Allowed values: contact,person,company,opportunity,case">Entity type</param>
/// <category>User fields</category>
/// <returns>
/// User fields
/// </returns>
/// <exception cref="SecurityException"></exception>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ItemNotFoundException"></exception>
[Update(@"{entityType:(contact|person|company|opportunity|case)}/customfield/reorder")]
public IEnumerable<CustomFieldBaseWrapper> UpdateCustomFieldsOrder(IEnumerable<int> fieldids, string entityType)
{
if (fieldids == null) throw new ArgumentException();
if (!(CRMSecurity.IsAdmin)) throw CRMSecurity.CreateSecurityException();
var customFields = new List<CustomField>();
foreach (var id in fieldids)
{
if (!DaoFactory.CustomFieldDao.IsExist(id)) throw new ItemNotFoundException();
customFields.Add(DaoFactory.CustomFieldDao.GetFieldDescription(id));
}
DaoFactory.CustomFieldDao.ReorderFields(fieldids.ToArray());
var messageAction = GetCustomFieldsUpdatedOrderAction(ToEntityType(entityType));
MessageService.Send(Request, messageAction, MessageTarget.Create(fieldids), customFields.Select(x => x.Label));
return customFields.Select(ToCustomFieldBaseWrapper);
}
private static CustomFieldBaseWrapper ToCustomFieldBaseWrapper(CustomField customField)
{
return new CustomFieldBaseWrapper(customField);
}
private CustomFieldWrapper ToCustomFieldWrapper(CustomField customField)
{
var result = new CustomFieldWrapper(customField)
{
RelativeItemsCount = DaoFactory.CustomFieldDao.GetContactLinkCount(customField.EntityType, customField.ID)
};
return result;
}
private static MessageAction GetCustomFieldCreatedAction(EntityType entityType)
{
switch (entityType)
{
case EntityType.Contact:
return MessageAction.ContactUserFieldCreated;
case EntityType.Person:
return MessageAction.PersonUserFieldCreated;
case EntityType.Company:
return MessageAction.CompanyUserFieldCreated;
case EntityType.Opportunity:
return MessageAction.OpportunityUserFieldCreated;
case EntityType.Case:
return MessageAction.CaseUserFieldCreated;
default:
throw new ArgumentException("Invalid entityType: " + entityType);
}
}
private static MessageAction GetCustomFieldUpdatedAction(EntityType entityType)
{
switch (entityType)
{
case EntityType.Contact:
return MessageAction.ContactUserFieldUpdated;
case EntityType.Person:
return MessageAction.PersonUserFieldUpdated;
case EntityType.Company:
return MessageAction.CompanyUserFieldUpdated;
case EntityType.Opportunity:
return MessageAction.OpportunityUserFieldUpdated;
case EntityType.Case:
return MessageAction.CaseUserFieldUpdated;
default:
throw new ArgumentException("Invalid entityType: " + entityType);
}
}
private static MessageAction GetCustomFieldDeletedAction(EntityType entityType)
{
switch (entityType)
{
case EntityType.Contact:
return MessageAction.ContactUserFieldDeleted;
case EntityType.Person:
return MessageAction.PersonUserFieldDeleted;
case EntityType.Company:
return MessageAction.CompanyUserFieldDeleted;
case EntityType.Opportunity:
return MessageAction.OpportunityUserFieldDeleted;
case EntityType.Case:
return MessageAction.CaseUserFieldDeleted;
default:
throw new ArgumentException("Invalid entityType: " + entityType);
}
}
private static MessageAction GetCustomFieldsUpdatedOrderAction(EntityType entityType)
{
switch (entityType)
{
case EntityType.Contact:
return MessageAction.ContactUserFieldsUpdatedOrder;
case EntityType.Person:
return MessageAction.PersonUserFieldsUpdatedOrder;
case EntityType.Company:
return MessageAction.CompanyUserFieldsUpdatedOrder;
case EntityType.Opportunity:
return MessageAction.OpportunityUserFieldsUpdatedOrder;
case EntityType.Case:
return MessageAction.CaseUserFieldsUpdatedOrder;
default:
throw new ArgumentException("Invalid entityType: " + entityType);
}
}
}
}
| |
// <copyright file="By.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text.RegularExpressions;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium
{
/// <summary>
/// Provides a mechanism by which to find elements within a document.
/// </summary>
/// <remarks>It is possible to create your own locating mechanisms for finding documents.
/// In order to do this,subclass this class and override the protected methods. However,
/// it is expected that that all subclasses rely on the basic finding mechanisms provided
/// through static methods of this class. An example of this can be found in OpenQA.Support.ByIdOrName
/// </remarks>
[Serializable]
public class By
{
private static readonly string CssSelectorMechanism = "css selector";
private static readonly string XPathSelectorMechanism = "xpath";
private static readonly string TagNameMechanism = "tag name";
private static readonly string LinkTextMechanism = "link text";
private static readonly string PartialLinkTextMechanism = "partial link text";
private string description = "OpenQA.Selenium.By";
private string mechanism = string.Empty;
private string criteria = string.Empty;
private Func<ISearchContext, IWebElement> findElementMethod;
private Func<ISearchContext, ReadOnlyCollection<IWebElement>> findElementsMethod;
/// <summary>
/// Initializes a new instance of the <see cref="By"/> class.
/// </summary>
protected By()
{
}
/// <summary>
/// Intializes a new instance of the <see cref="By"/> class using the specified mechanism and critieria for finding elements.
/// </summary>
/// <param name="mechanism">The mechanism to use in finding elements.</param>
/// <param name="criteria">The criteria to use in finding elements.</param>
/// <remarks>
/// Customizing nothing else, instances using this constructor will attempt to find elemsnts
/// using the <see cref="IFindsElement.FindElement(string, string)"/> method, taking string arguments.
/// </remarks>
protected By(string mechanism, string criteria)
{
this.mechanism = mechanism;
this.criteria = criteria;
this.findElementMethod = (ISearchContext context) => ((IFindsElement)context).FindElement(this.mechanism, this.criteria);
this.findElementsMethod = (ISearchContext context) => ((IFindsElement)context).FindElements(this.mechanism, this.criteria);
}
/// <summary>
/// Initializes a new instance of the <see cref="By"/> class using the given functions to find elements.
/// </summary>
/// <param name="findElementMethod">A function that takes an object implementing <see cref="ISearchContext"/>
/// and returns the found <see cref="IWebElement"/>.</param>
/// <param name="findElementsMethod">A function that takes an object implementing <see cref="ISearchContext"/>
/// and returns a <see cref="ReadOnlyCollection{T}"/> of the found<see cref="IWebElement">IWebElements</see>.
/// <see cref="IWebElement">IWebElements</see>/>.</param>
protected By(Func<ISearchContext, IWebElement> findElementMethod, Func<ISearchContext, ReadOnlyCollection<IWebElement>> findElementsMethod)
{
this.findElementMethod = findElementMethod;
this.findElementsMethod = findElementsMethod;
}
/// <summary>
/// Gets the value of the mechanism for this <see cref="By"/> class instance.
/// </summary>
public string Mechanism
{
get { return this.mechanism; }
}
/// <summary>
/// Gets the value of the criteria for this <see cref="By"/> class instance.
/// </summary>
public string Criteria
{
get { return this.criteria; }
}
/// <summary>
/// Gets or sets the value of the description for this <see cref="By"/> class instance.
/// </summary>
protected string Description
{
get { return this.description; }
set { this.description = value; }
}
/// <summary>
/// Gets or sets the method used to find a single element matching specified criteria.
/// </summary>
protected Func<ISearchContext, IWebElement> FindElementMethod
{
get { return this.findElementMethod; }
set { this.findElementMethod = value; }
}
/// <summary>
/// Gets or sets the method used to find all elements matching specified criteria.
/// </summary>
protected Func<ISearchContext, ReadOnlyCollection<IWebElement>> FindElementsMethod
{
get { return this.findElementsMethod; }
set { this.findElementsMethod = value; }
}
/// <summary>
/// Determines if two <see cref="By"/> instances are equal.
/// </summary>
/// <param name="one">One instance to compare.</param>
/// <param name="two">The other instance to compare.</param>
/// <returns><see langword="true"/> if the two instances are equal; otherwise, <see langword="false"/>.</returns>
public static bool operator ==(By one, By two)
{
// If both are null, or both are same instance, return true.
if (object.ReferenceEquals(one, two))
{
return true;
}
// If one is null, but not both, return false.
if (((object)one == null) || ((object)two == null))
{
return false;
}
return one.Equals(two);
}
/// <summary>
/// Determines if two <see cref="By"/> instances are unequal.
/// </summary>s
/// <param name="one">One instance to compare.</param>
/// <param name="two">The other instance to compare.</param>
/// <returns><see langword="true"/> if the two instances are not equal; otherwise, <see langword="false"/>.</returns>
public static bool operator !=(By one, By two)
{
return !(one == two);
}
/// <summary>
/// Gets a mechanism to find elements by their ID.
/// </summary>
/// <param name="idToFind">The ID to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By Id(string idToFind)
{
if (idToFind == null)
{
throw new ArgumentNullException("idToFind", "Cannot find elements with a null id attribute.");
}
string selector = By.EscapeCssSelector(idToFind);
By by = new By(CssSelectorMechanism, "#" + selector);
by.description = "By.Id: " + idToFind;
if (string.IsNullOrEmpty(selector))
{
// Finding multiple elements with an empty ID will return
// an empty list. However, finding by a CSS selector of '#'
// throws an exception, even in the multiple elements case,
// which means we need to short-circuit that behavior.
by.findElementsMethod = (ISearchContext context) => new List<IWebElement>().AsReadOnly();
}
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their link text.
/// </summary>
/// <param name="linkTextToFind">The link text to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By LinkText(string linkTextToFind)
{
if (linkTextToFind == null)
{
throw new ArgumentNullException("linkTextToFind", "Cannot find elements when link text is null.");
}
By by = new By(LinkTextMechanism, linkTextToFind);
by.description = "By.LinkText: " + linkTextToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their name.
/// </summary>
/// <param name="nameToFind">The name to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By Name(string nameToFind)
{
if (nameToFind == null)
{
throw new ArgumentNullException("nameToFind", "Cannot find elements when name text is null.");
}
string selector = "*[name =\"" + By.EscapeCssSelector(nameToFind) + "\"]";
By by = new By(CssSelectorMechanism, selector);
by.description = "By.Name: " + nameToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by an XPath query.
/// When searching within a WebElement using xpath be aware that WebDriver follows standard conventions:
/// a search prefixed with "//" will search the entire document, not just the children of this current node.
/// Use ".//" to limit your search to the children of this WebElement.
/// </summary>
/// <param name="xpathToFind">The XPath query to use.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By XPath(string xpathToFind)
{
if (xpathToFind == null)
{
throw new ArgumentNullException("xpathToFind", "Cannot find elements when the XPath expression is null.");
}
By by = new By(XPathSelectorMechanism, xpathToFind);
by.description = "By.XPath: " + xpathToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their CSS class.
/// </summary>
/// <param name="classNameToFind">The CSS class to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
/// <remarks>If an element has many classes then this will match against each of them.
/// For example if the value is "one two onone", then the following values for the
/// className parameter will match: "one" and "two".</remarks>
public static By ClassName(string classNameToFind)
{
if (classNameToFind == null)
{
throw new ArgumentNullException("classNameToFind", "Cannot find elements when the class name expression is null.");
}
string selector = "." + By.EscapeCssSelector(classNameToFind);
if (selector.Contains(" "))
{
// Finding elements by class name with whitespace is not allowed.
// However, converting the single class name to a valid CSS selector
// by prepending a '.' may result in a still-valid, but incorrect
// selector. Thus, we short-ciruit that behavior here.
throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead.");
}
By by = new By(CssSelectorMechanism, selector);
by.description = "By.ClassName[Contains]: " + classNameToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by a partial match on their link text.
/// </summary>
/// <param name="partialLinkTextToFind">The partial link text to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By PartialLinkText(string partialLinkTextToFind)
{
if (partialLinkTextToFind == null)
{
throw new ArgumentNullException("partialLinkTextToFind", "Cannot find elements when partial link text is null.");
}
By by = new By(PartialLinkTextMechanism, partialLinkTextToFind);
by.description = "By.PartialLinkText: " + partialLinkTextToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their tag name.
/// </summary>
/// <param name="tagNameToFind">The tag name to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By TagName(string tagNameToFind)
{
if (tagNameToFind == null)
{
throw new ArgumentNullException("tagNameToFind", "Cannot find elements when name tag name is null.");
}
By by = new By(TagNameMechanism, tagNameToFind);
by.description = "By.TagName: " + tagNameToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their cascading style sheet (CSS) selector.
/// </summary>
/// <param name="cssSelectorToFind">The CSS selector to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By CssSelector(string cssSelectorToFind)
{
if (cssSelectorToFind == null)
{
throw new ArgumentNullException("cssSelectorToFind", "Cannot find elements when name CSS selector is null.");
}
By by = new By(CssSelectorMechanism, cssSelectorToFind);
by.description = "By.CssSelector: " + cssSelectorToFind;
return by;
}
/// <summary>
/// Finds the first element matching the criteria.
/// </summary>
/// <param name="context">An <see cref="ISearchContext"/> object to use to search for the elements.</param>
/// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns>
public virtual IWebElement FindElement(ISearchContext context)
{
return this.findElementMethod(context);
}
/// <summary>
/// Finds all elements matching the criteria.
/// </summary>
/// <param name="context">An <see cref="ISearchContext"/> object to use to search for the elements.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see>
/// matching the current criteria, or an empty list if nothing matches.</returns>
public virtual ReadOnlyCollection<IWebElement> FindElements(ISearchContext context)
{
return this.findElementsMethod(context);
}
/// <summary>
/// Gets a string representation of the finder.
/// </summary>
/// <returns>The string displaying the finder content.</returns>
public override string ToString()
{
return this.description;
}
/// <summary>
/// Determines whether the specified <see cref="object">Object</see> is equal
/// to the current <see cref="object">Object</see>.
/// </summary>
/// <param name="obj">The <see cref="object">Object</see> to compare with the
/// current <see cref="object">Object</see>.</param>
/// <returns><see langword="true"/> if the specified <see cref="object">Object</see>
/// is equal to the current <see cref="object">Object</see>; otherwise,
/// <see langword="false"/>.</returns>
public override bool Equals(object obj)
{
var other = obj as By;
// TODO(dawagner): This isn't ideal
return other != null && this.description.Equals(other.description);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>A hash code for the current <see cref="object">Object</see>.</returns>
public override int GetHashCode()
{
return this.description.GetHashCode();
}
/// <summary>
/// Escapes invalid characters in a CSS selector.
/// </summary>
/// <param name="selector">The selector to escape.</param>
/// <returns>The selector with invalid characters escaped.</returns>
internal static string EscapeCssSelector(string selector)
{
string escaped = Regex.Replace(selector, @"([ '""\\#.:;,!?+<>=~*^$|%&@`{}\-/\[\]\(\)])", @"\$1");
if (selector.Length > 0 && char.IsDigit(selector[0]))
{
escaped = @"\" + (30 + int.Parse(selector.Substring(0, 1), CultureInfo.InvariantCulture)).ToString(CultureInfo.InvariantCulture) + " " + selector.Substring(1);
}
return escaped;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text.RegularExpressions;
using System.Web;
using Umbraco.Core.Auditing;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Events;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Services
{
/// <summary>
/// Represents the File Service, which is an easy access to operations involving <see cref="IFile"/> objects like Scripts, Stylesheets and Templates
/// </summary>
public class FileService : IFileService
{
private readonly RepositoryFactory _repositoryFactory;
private readonly IUnitOfWorkProvider _fileUowProvider;
private readonly IDatabaseUnitOfWorkProvider _dataUowProvider;
private const string PartialViewHeader = "@inherits Umbraco.Web.Mvc.UmbracoTemplatePage";
private const string PartialViewMacroHeader = "@inherits Umbraco.Web.Macros.PartialViewMacroPage";
[Obsolete("Use the constructors that specify all dependencies instead")]
public FileService()
: this(new RepositoryFactory())
{ }
[Obsolete("Use the constructors that specify all dependencies instead")]
public FileService(RepositoryFactory repositoryFactory)
: this(new FileUnitOfWorkProvider(), new PetaPocoUnitOfWorkProvider(), repositoryFactory)
{
}
public FileService(IUnitOfWorkProvider fileProvider, IDatabaseUnitOfWorkProvider dataProvider, RepositoryFactory repositoryFactory)
{
if (fileProvider == null) throw new ArgumentNullException("fileProvider");
if (dataProvider == null) throw new ArgumentNullException("dataProvider");
if (repositoryFactory == null) throw new ArgumentNullException("repositoryFactory");
_repositoryFactory = repositoryFactory;
_fileUowProvider = fileProvider;
_dataUowProvider = dataProvider;
}
#region Stylesheets
/// <summary>
/// Gets a list of all <see cref="Stylesheet"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="Stylesheet"/> objects</returns>
public IEnumerable<Stylesheet> GetStylesheets(params string[] names)
{
using (var repository = _repositoryFactory.CreateStylesheetRepository(_fileUowProvider.GetUnitOfWork(), _dataUowProvider.GetUnitOfWork()))
{
return repository.GetAll(names);
}
}
/// <summary>
/// Gets a <see cref="Stylesheet"/> object by its name
/// </summary>
/// <param name="name">Name of the stylesheet incl. extension</param>
/// <returns>A <see cref="Stylesheet"/> object</returns>
public Stylesheet GetStylesheetByName(string name)
{
using (var repository = _repositoryFactory.CreateStylesheetRepository(_fileUowProvider.GetUnitOfWork(), _dataUowProvider.GetUnitOfWork()))
{
return repository.Get(name);
}
}
/// <summary>
/// Saves a <see cref="Stylesheet"/>
/// </summary>
/// <param name="stylesheet"><see cref="Stylesheet"/> to save</param>
/// <param name="userId"></param>
public void SaveStylesheet(Stylesheet stylesheet, int userId = 0)
{
if (SavingStylesheet.IsRaisedEventCancelled(new SaveEventArgs<Stylesheet>(stylesheet), this))
return;
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateStylesheetRepository(uow, _dataUowProvider.GetUnitOfWork()))
{
repository.AddOrUpdate(stylesheet);
uow.Commit();
SavedStylesheet.RaiseEvent(new SaveEventArgs<Stylesheet>(stylesheet, false), this);
}
Audit(AuditType.Save, string.Format("Save Stylesheet performed by user"), userId, -1);
}
/// <summary>
/// Deletes a stylesheet by its name
/// </summary>
/// <param name="path">Name incl. extension of the Stylesheet to delete</param>
/// <param name="userId"></param>
public void DeleteStylesheet(string path, int userId = 0)
{
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateStylesheetRepository(uow, _dataUowProvider.GetUnitOfWork()))
{
var stylesheet = repository.Get(path);
if (stylesheet == null) return;
if (DeletingStylesheet.IsRaisedEventCancelled(new DeleteEventArgs<Stylesheet>(stylesheet), this))
return;
repository.Delete(stylesheet);
uow.Commit();
DeletedStylesheet.RaiseEvent(new DeleteEventArgs<Stylesheet>(stylesheet, false), this);
Audit(AuditType.Delete, string.Format("Delete Stylesheet performed by user"), userId, -1);
}
}
/// <summary>
/// Validates a <see cref="Stylesheet"/>
/// </summary>
/// <param name="stylesheet"><see cref="Stylesheet"/> to validate</param>
/// <returns>True if Stylesheet is valid, otherwise false</returns>
public bool ValidateStylesheet(Stylesheet stylesheet)
{
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateStylesheetRepository(uow, _dataUowProvider.GetUnitOfWork()))
{
return repository.ValidateStylesheet(stylesheet);
}
}
#endregion
#region Scripts
/// <summary>
/// Gets a list of all <see cref="Script"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="Script"/> objects</returns>
public IEnumerable<Script> GetScripts(params string[] names)
{
using (var repository = _repositoryFactory.CreateScriptRepository(_fileUowProvider.GetUnitOfWork()))
{
return repository.GetAll(names);
}
}
/// <summary>
/// Gets a <see cref="Script"/> object by its name
/// </summary>
/// <param name="name">Name of the script incl. extension</param>
/// <returns>A <see cref="Script"/> object</returns>
public Script GetScriptByName(string name)
{
using (var repository = _repositoryFactory.CreateScriptRepository(_fileUowProvider.GetUnitOfWork()))
{
return repository.Get(name);
}
}
/// <summary>
/// Saves a <see cref="Script"/>
/// </summary>
/// <param name="script"><see cref="Script"/> to save</param>
/// <param name="userId"></param>
public void SaveScript(Script script, int userId = 0)
{
if (SavingScript.IsRaisedEventCancelled(new SaveEventArgs<Script>(script), this))
return;
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateScriptRepository(uow))
{
repository.AddOrUpdate(script);
uow.Commit();
SavedScript.RaiseEvent(new SaveEventArgs<Script>(script, false), this);
}
Audit(AuditType.Save, string.Format("Save Script performed by user"), userId, -1);
}
/// <summary>
/// Deletes a script by its name
/// </summary>
/// <param name="path">Name incl. extension of the Script to delete</param>
/// <param name="userId"></param>
public void DeleteScript(string path, int userId = 0)
{
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateScriptRepository(uow))
{
var script = repository.Get(path);
if (script == null) return;
if (DeletingScript.IsRaisedEventCancelled(new DeleteEventArgs<Script>(script), this))
return; ;
repository.Delete(script);
uow.Commit();
DeletedScript.RaiseEvent(new DeleteEventArgs<Script>(script, false), this);
Audit(AuditType.Delete, string.Format("Delete Script performed by user"), userId, -1);
}
}
/// <summary>
/// Validates a <see cref="Script"/>
/// </summary>
/// <param name="script"><see cref="Script"/> to validate</param>
/// <returns>True if Script is valid, otherwise false</returns>
public bool ValidateScript(Script script)
{
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateScriptRepository(uow))
{
return repository.ValidateScript(script);
}
}
public void CreateScriptFolder(string folderPath)
{
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateScriptRepository(uow))
{
((ScriptRepository)repository).AddFolder(folderPath);
uow.Commit();
}
}
public void DeleteScriptFolder(string folderPath)
{
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateScriptRepository(uow))
{
((ScriptRepository)repository).DeleteFolder(folderPath);
uow.Commit();
}
}
#endregion
#region Templates
public ITemplate CreateTemplateWithIdentity(string name, string content, ITemplate masterTemplate = null, int userId = 0)
{
var template = new Template(name, name)
{
Content = content
};
if (masterTemplate != null)
{
template.SetMasterTemplate(masterTemplate);
}
SaveTemplate(template, userId);
return template;
}
/// <summary>
/// Gets a list of all <see cref="ITemplate"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns>
public IEnumerable<ITemplate> GetTemplates(params string[] aliases)
{
using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork()))
{
return repository.GetAll(aliases).OrderBy(x => x.Name);
}
}
/// <summary>
/// Gets a list of all <see cref="ITemplate"/> objects
/// </summary>
/// <returns>An enumerable list of <see cref="ITemplate"/> objects</returns>
public IEnumerable<ITemplate> GetTemplates(int masterTemplateId)
{
using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork()))
{
return repository.GetChildren(masterTemplateId).OrderBy(x => x.Name);
}
}
/// <summary>
/// Gets a <see cref="ITemplate"/> object by its alias
/// </summary>
/// <param name="alias">Alias of the template</param>
/// <returns>A <see cref="Template"/> object</returns>
public ITemplate GetTemplate(string alias)
{
using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork()))
{
return repository.Get(alias);
}
}
/// <summary>
/// Gets a <see cref="ITemplate"/> object by its alias
/// </summary>
/// <param name="id">Id of the template</param>
/// <returns>A <see cref="ITemplate"/> object</returns>
public ITemplate GetTemplate(int id)
{
using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork()))
{
return repository.Get(id);
}
}
/// <summary>
/// Returns a template as a template node which can be traversed (parent, children)
/// </summary>
/// <param name="alias"></param>
/// <returns></returns>
public TemplateNode GetTemplateNode(string alias)
{
using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork()))
{
return repository.GetTemplateNode(alias);
}
}
/// <summary>
/// Given a template node in a tree, this will find the template node with the given alias if it is found in the hierarchy, otherwise null
/// </summary>
/// <param name="anyNode"></param>
/// <param name="alias"></param>
/// <returns></returns>
public TemplateNode FindTemplateInTree(TemplateNode anyNode, string alias)
{
using (var repository = _repositoryFactory.CreateTemplateRepository(_dataUowProvider.GetUnitOfWork()))
{
return repository.FindTemplateInTree(anyNode, alias);
}
}
/// <summary>
/// Saves a <see cref="Template"/>
/// </summary>
/// <param name="template"><see cref="Template"/> to save</param>
/// <param name="userId"></param>
public void SaveTemplate(ITemplate template, int userId = 0)
{
if (SavingTemplate.IsRaisedEventCancelled(new SaveEventArgs<ITemplate>(template), this))
return;
var uow = _dataUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateTemplateRepository(uow))
{
repository.AddOrUpdate(template);
uow.Commit();
SavedTemplate.RaiseEvent(new SaveEventArgs<ITemplate>(template, false), this);
}
Audit(AuditType.Save, string.Format("Save Template performed by user"), userId, template.Id);
}
/// <summary>
/// Saves a collection of <see cref="Template"/> objects
/// </summary>
/// <param name="templates">List of <see cref="Template"/> to save</param>
/// <param name="userId">Optional id of the user</param>
public void SaveTemplate(IEnumerable<ITemplate> templates, int userId = 0)
{
if (SavingTemplate.IsRaisedEventCancelled(new SaveEventArgs<ITemplate>(templates), this))
return;
var uow = _dataUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateTemplateRepository(uow))
{
foreach (var template in templates)
{
repository.AddOrUpdate(template);
}
uow.Commit();
SavedTemplate.RaiseEvent(new SaveEventArgs<ITemplate>(templates, false), this);
}
Audit(AuditType.Save, string.Format("Save Template performed by user"), userId, -1);
}
/// <summary>
/// This checks what the default rendering engine is set in config but then also ensures that there isn't already
/// a template that exists in the opposite rendering engine's template folder, then returns the appropriate
/// rendering engine to use.
/// </summary>
/// <returns></returns>
/// <remarks>
/// The reason this is required is because for example, if you have a master page file already existing under ~/masterpages/Blah.aspx
/// and then you go to create a template in the tree called Blah and the default rendering engine is MVC, it will create a Blah.cshtml
/// empty template in ~/Views. This means every page that is using Blah will go to MVC and render an empty page.
/// This is mostly related to installing packages since packages install file templates to the file system and then create the
/// templates in business logic. Without this, it could cause the wrong rendering engine to be used for a package.
/// </remarks>
public RenderingEngine DetermineTemplateRenderingEngine(ITemplate template)
{
var uow = _dataUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateTemplateRepository(uow))
{
return repository.DetermineTemplateRenderingEngine(template);
}
}
/// <summary>
/// Deletes a template by its alias
/// </summary>
/// <param name="alias">Alias of the <see cref="ITemplate"/> to delete</param>
/// <param name="userId"></param>
public void DeleteTemplate(string alias, int userId = 0)
{
var uow = _dataUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateTemplateRepository(uow))
{
var template = repository.Get(alias);
if (template == null) return;
if (DeletingTemplate.IsRaisedEventCancelled(new DeleteEventArgs<ITemplate>(template), this))
return;
repository.Delete(template);
uow.Commit();
DeletedTemplate.RaiseEvent(new DeleteEventArgs<ITemplate>(template, false), this);
Audit(AuditType.Delete, string.Format("Delete Template performed by user"), userId, template.Id);
}
}
/// <summary>
/// Validates a <see cref="ITemplate"/>
/// </summary>
/// <param name="template"><see cref="ITemplate"/> to validate</param>
/// <returns>True if Script is valid, otherwise false</returns>
public bool ValidateTemplate(ITemplate template)
{
var uow = _dataUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateTemplateRepository(uow))
{
return repository.ValidateTemplate(template);
}
}
#endregion
#region Partial Views
public IEnumerable<string> GetPartialViewSnippetNames(params string[] filterNames)
{
var snippetPath = IOHelper.MapPath(string.Format("{0}/PartialViewMacros/Templates/", SystemDirectories.Umbraco));
var files = Directory.GetFiles(snippetPath, "*.cshtml")
.Select(Path.GetFileNameWithoutExtension)
.Except(filterNames, StringComparer.InvariantCultureIgnoreCase)
.ToArray();
//Ensure the ones that are called 'Empty' are at the top
var empty = files.Where(x => Path.GetFileName(x).InvariantStartsWith("Empty"))
.OrderBy(x => x.Length)
.ToArray();
return empty.Union(files.Except(empty));
}
public void DeletePartialViewFolder(string folderPath)
{
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreatePartialViewRepository(uow))
{
((PartialViewRepository)repository).DeleteFolder(folderPath);
uow.Commit();
}
}
public void DeletePartialViewMacroFolder(string folderPath)
{
var uow = _fileUowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreatePartialViewMacroRepository(uow))
{
((PartialViewMacroRepository)repository).DeleteFolder(folderPath);
uow.Commit();
}
}
public IPartialView GetPartialView(string path)
{
using (var repository = _repositoryFactory.CreatePartialViewRepository(_fileUowProvider.GetUnitOfWork()))
{
return repository.Get(path);
}
}
public IPartialView GetPartialViewMacro(string path)
{
using (var repository = _repositoryFactory.CreatePartialViewMacroRepository(_fileUowProvider.GetUnitOfWork()))
{
return repository.Get(path);
}
}
public Attempt<IPartialView> CreatePartialView(IPartialView partialView, string snippetName = null, int userId = 0)
{
return CreatePartialViewMacro(partialView, PartialViewType.PartialView, snippetName, userId);
}
public Attempt<IPartialView> CreatePartialViewMacro(IPartialView partialView, string snippetName = null, int userId = 0)
{
return CreatePartialViewMacro(partialView, PartialViewType.PartialViewMacro, snippetName, userId);
}
private Attempt<IPartialView> CreatePartialViewMacro(IPartialView partialView, PartialViewType partialViewType, string snippetName = null, int userId = 0)
{
if (CreatingPartialView.IsRaisedEventCancelled(new NewEventArgs<IPartialView>(partialView, true, partialView.Alias, -1), this))
return Attempt<IPartialView>.Fail();
var uow = _fileUowProvider.GetUnitOfWork();
string partialViewHeader = null;
IPartialViewRepository repository;
switch (partialViewType)
{
case PartialViewType.PartialView:
repository = _repositoryFactory.CreatePartialViewRepository(uow);
partialViewHeader = PartialViewHeader;
break;
case PartialViewType.PartialViewMacro:
default:
repository = _repositoryFactory.CreatePartialViewMacroRepository(uow);
partialViewHeader = PartialViewMacroHeader;
break;
}
if (snippetName.IsNullOrWhiteSpace() == false)
{
//create the file
var snippetPathAttempt = TryGetSnippetPath(snippetName);
if (snippetPathAttempt.Success == false)
{
throw new InvalidOperationException("Could not load snippet with name " + snippetName);
}
using (var snippetFile = new StreamReader(System.IO.File.OpenRead(snippetPathAttempt.Result)))
{
var snippetContent = snippetFile.ReadToEnd().Trim();
//strip the @inherits if it's there
snippetContent = StripPartialViewHeader(snippetContent);
var content = string.Format("{0}{1}{2}",
partialViewHeader,
Environment.NewLine, snippetContent);
partialView.Content = content;
}
}
using (repository)
{
repository.AddOrUpdate(partialView);
uow.Commit();
CreatedPartialView.RaiseEvent(new NewEventArgs<IPartialView>(partialView, false, partialView.Alias, -1), this);
}
Audit(AuditType.Save, string.Format("Save {0} performed by user", partialViewType), userId, -1);
return Attempt<IPartialView>.Succeed(partialView);
}
public bool DeletePartialView(string path, int userId = 0)
{
return DeletePartialViewMacro(path, PartialViewType.PartialView, userId);
}
public bool DeletePartialViewMacro(string path, int userId = 0)
{
return DeletePartialViewMacro(path, PartialViewType.PartialViewMacro, userId);
}
private bool DeletePartialViewMacro(string path, PartialViewType partialViewType, int userId = 0)
{
var uow = _fileUowProvider.GetUnitOfWork();
IPartialViewRepository repository;
switch (partialViewType)
{
case PartialViewType.PartialView:
repository = _repositoryFactory.CreatePartialViewRepository(uow);
break;
case PartialViewType.PartialViewMacro:
default:
repository = _repositoryFactory.CreatePartialViewMacroRepository(uow);
break;
}
using (repository)
{
var partialView = repository.Get(path);
if (partialView == null)
return true;
if (DeletingPartialView.IsRaisedEventCancelled(new DeleteEventArgs<IPartialView>(partialView), this))
return false;
repository.Delete(partialView);
uow.Commit();
DeletedPartialView.RaiseEvent(new DeleteEventArgs<IPartialView>(partialView, false), this);
Audit(AuditType.Delete, string.Format("Delete {0} performed by user", partialViewType), userId, -1);
}
return true;
}
public Attempt<IPartialView> SavePartialView(IPartialView partialView, int userId = 0)
{
return SavePartialView(partialView, PartialViewType.PartialView, userId);
}
public Attempt<IPartialView> SavePartialViewMacro(IPartialView partialView, int userId = 0)
{
return SavePartialView(partialView, PartialViewType.PartialViewMacro, userId);
}
private Attempt<IPartialView> SavePartialView(IPartialView partialView, PartialViewType partialViewType, int userId = 0)
{
if (SavingPartialView.IsRaisedEventCancelled(new SaveEventArgs<IPartialView>(partialView), this))
return Attempt<IPartialView>.Fail();
var uow = _fileUowProvider.GetUnitOfWork();
IPartialViewRepository repository;
switch (partialViewType)
{
case PartialViewType.PartialView:
repository = _repositoryFactory.CreatePartialViewRepository(uow);
break;
case PartialViewType.PartialViewMacro:
default:
repository = _repositoryFactory.CreatePartialViewMacroRepository(uow);
break;
}
using (repository)
{
repository.AddOrUpdate(partialView);
uow.Commit();
SavedPartialView.RaiseEvent(new SaveEventArgs<IPartialView>(partialView, false), this);
}
Audit(AuditType.Save, string.Format("Save {0} performed by user", partialViewType), userId, -1);
SavedPartialView.RaiseEvent(new SaveEventArgs<IPartialView>(partialView), this);
return Attempt.Succeed(partialView);
}
public bool ValidatePartialView(PartialView partialView)
{
var validatePath = IOHelper.ValidateEditPath(partialView.Path, new[] { SystemDirectories.MvcViews + "/Partials/", SystemDirectories.MvcViews + "/MacroPartials/" });
var verifyFileExtension = IOHelper.VerifyFileExtension(partialView.Path, new List<string> { "cshtml" });
return validatePath && verifyFileExtension;
}
internal string StripPartialViewHeader(string contents)
{
var headerMatch = new Regex("^@inherits\\s+?.*$", RegexOptions.Multiline);
return headerMatch.Replace(contents, string.Empty);
}
internal Attempt<string> TryGetSnippetPath(string fileName)
{
if (fileName.EndsWith(".cshtml") == false)
{
fileName += ".cshtml";
}
var snippetPath = IOHelper.MapPath(string.Format("{0}/PartialViewMacros/Templates/{1}", SystemDirectories.Umbraco, fileName));
return System.IO.File.Exists(snippetPath)
? Attempt<string>.Succeed(snippetPath)
: Attempt<string>.Fail();
}
private enum PartialViewType
{
PartialView,
PartialViewMacro
}
private void Audit(AuditType type, string message, int userId, int objectId)
{
var uow = _dataUowProvider.GetUnitOfWork();
using (var auditRepo = _repositoryFactory.CreateAuditRepository(uow))
{
auditRepo.AddOrUpdate(new AuditItem(objectId, message, type, userId));
uow.Commit();
}
}
#endregion
//TODO Method to change name and/or alias of view/masterpage template
#region Event Handlers
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<ITemplate>> DeletingTemplate;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<ITemplate>> DeletedTemplate;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<Script>> DeletingScript;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<Script>> DeletedScript;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<Stylesheet>> DeletingStylesheet;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<Stylesheet>> DeletedStylesheet;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<ITemplate>> SavingTemplate;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<ITemplate>> SavedTemplate;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<Script>> SavingScript;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<Script>> SavedScript;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<Stylesheet>> SavingStylesheet;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<Stylesheet>> SavedStylesheet;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<IPartialView>> SavingPartialView;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IFileService, SaveEventArgs<IPartialView>> SavedPartialView;
/// <summary>
/// Occurs before Create
/// </summary>
public static event TypedEventHandler<IFileService, NewEventArgs<IPartialView>> CreatingPartialView;
/// <summary>
/// Occurs after Create
/// </summary>
public static event TypedEventHandler<IFileService, NewEventArgs<IPartialView>> CreatedPartialView;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<IPartialView>> DeletingPartialView;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IFileService, DeleteEventArgs<IPartialView>> DeletedPartialView;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using AlephNote.Common.Util;
using AlephNote.PluginInterface;
using AlephNote.PluginInterface.Exceptions;
using MSHC.Network;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AlephNote.Common.Network
{
public class SimpleJsonRest : ISimpleJsonRest
{
private const int LOG_FMT_DEPTH = 4;
private readonly HttpClient _client;
private readonly Uri _host;
private JsonConverter[] _converter = new JsonConverter[0];
private StringEscapeHandling _seHandling = StringEscapeHandling.Default;
private Tuple<string, string> _urlAuthentication = null;
private Dictionary<string, string> _headers = new Dictionary<string, string>();
private HttpResponseMessage _lastResponse = null;
public SimpleJsonRest(IWebProxy proxy, string host)
{
if (proxy != null)
{
_client = new HttpClient(new HttpClientHandler
{
Proxy = proxy,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
});
}
else
{
_client = new HttpClient(new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
});
}
_headers["User-Agent"] = "AlephNote/Common";
_headers["ContentType"] = "application/json";
_host = new Uri(host);
}
public void Dispose()
{
_client?.Dispose();
}
public void AddDTOConverter(Func<string, DateTimeOffset> c1, Func<DateTimeOffset, string> c2)
{
var c = new GenericDTOConverter(c1, c2);
_converter = _converter.Concat(new[] {c}).ToArray();
}
public void SetEscapeAllNonASCIICharacters(bool escape)
{
_seHandling = escape ? StringEscapeHandling.EscapeNonAscii : StringEscapeHandling.Default;
}
public void SetURLAuthentication(string username, string password)
{
_urlAuthentication = Tuple.Create(username, password);
}
private Uri CreateUri(string path, params string[] parameter)
{
var uri = new Uri(_host, path);
var result = uri.ToString();
if (_urlAuthentication != null)
{
result = string.Format("{0}://{1}:{2}@{3}:{4}{5}",
uri.Scheme,
Uri.EscapeDataString(_urlAuthentication.Item1),
Uri.EscapeDataString(_urlAuthentication.Item2),
uri.Host,
uri.Port,
uri.AbsolutePath);
}
bool first = true;
foreach (var param in parameter)
{
if (first)
result += "?" + param;
else
result += "&" + param;
first = false;
}
return new Uri(result);
}
public void AddHeader(string name, string value)
{
_headers[name] = value;
}
public string GetResponseHeader(string name)
{
return string.Join("\n", _lastResponse.Headers.GetValues(name));
}
private JsonSerializerSettings GetSerializerSettings()
{
return new JsonSerializerSettings
{
Converters = _converter,
StringEscapeHandling = _seHandling,
};
}
public TResult ParseJson<TResult>(string content)
{
return JsonConvert.DeserializeObject<TResult>(content, _converter);
}
public TResult ParseJsonWithoutConverter<TResult>(string content)
{
return JsonConvert.DeserializeObject<TResult>(content);
}
public TResult ParseJsonOrNull<TResult>(string content)
{
try
{
return JsonConvert.DeserializeObject<TResult>(content, new JsonSerializerSettings()
{
Converters = _converter,
DateParseHandling = DateParseHandling.None
});
}
catch (Exception)
{
return default;
}
}
public string ParseJsonAndGetSubJson(string content, string key, string defValue)
{
try
{
JsonReader reader = new JsonTextReader(new StringReader(content)) { DateParseHandling = DateParseHandling.None };
var obj = JObject.Load(reader);
if (!obj.ContainsKey(key)) return defValue;
return obj[key].ToString(Formatting.None);
}
catch (Exception)
{
return defValue;
}
}
public string SerializeJson<TResult>(TResult obj)
{
return JsonConvert.SerializeObject(obj);
}
#region POST
public TResult PostTwoWay<TResult>(object body, string path, params string[] parameter)
{
return GenericTwoWay<TResult>(body, path, HttpMethod.Post, new int[0], parameter);
}
public TResult PostTwoWay<TResult>(object body, string path, int[] allowedStatusCodes, params string[] parameter)
{
return GenericTwoWay<TResult>(body, path, HttpMethod.Post, allowedStatusCodes, parameter);
}
public void PostUpload(object body, string path, params string[] parameter)
{
GenericUpload(body, path, HttpMethod.Post, new int[0], parameter);
}
public void PostUpload(object body, string path, int[] allowedStatusCodes, params string[] parameter)
{
GenericUpload(body, path, HttpMethod.Post, allowedStatusCodes, parameter);
}
public TResult PostDownload<TResult>(string path, params string[] parameter)
{
return GenericDownload<TResult>(path, HttpMethod.Post, new int[0], parameter);
}
public TResult PostDownload<TResult>(string path, int[] allowedStatusCodes, params string[] parameter)
{
return GenericDownload<TResult>(path, HttpMethod.Post, allowedStatusCodes, parameter);
}
public void PostEmpty(string path, params string[] parameter)
{
GenericEmpty(path, HttpMethod.Post, new int[0], parameter);
}
public void PostEmpty(string path, int[] allowedStatusCodes, params string[] parameter)
{
GenericEmpty(path, HttpMethod.Post, allowedStatusCodes, parameter);
}
#endregion
#region PUT
public TResult PutTwoWay<TResult>(object body, string path, params string[] parameter)
{
return GenericTwoWay<TResult>(body, path, HttpMethod.Put, new int[0], parameter);
}
public TResult PutTwoWay<TResult>(object body, string path, int[] allowedStatusCodes, params string[] parameter)
{
return GenericTwoWay<TResult>(body, path, HttpMethod.Put, allowedStatusCodes, parameter);
}
public void PutUpload(object body, string path, params string[] parameter)
{
GenericUpload(body, path, HttpMethod.Put, new int[0], parameter);
}
public void PutUpload(object body, string path, int[] allowedStatusCodes, params string[] parameter)
{
GenericUpload(body, path, HttpMethod.Put, allowedStatusCodes, parameter);
}
public TResult PutDownload<TResult>(string path, params string[] parameter)
{
return GenericDownload<TResult>(path, HttpMethod.Put, new int[0], parameter);
}
public TResult PutDownload<TResult>(string path, int[] allowedStatusCodes, params string[] parameter)
{
return GenericDownload<TResult>(path, HttpMethod.Put, allowedStatusCodes, parameter);
}
public void PutEmpty(string path, params string[] parameter)
{
GenericEmpty(path, HttpMethod.Put, new int[0], parameter);
}
public void PutEmpty(string path, int[] allowedStatusCodes, params string[] parameter)
{
GenericEmpty(path, HttpMethod.Put, allowedStatusCodes, parameter);
}
#endregion
#region DELETE
public TResult DeleteTwoWay<TResult>(object body, string path, params string[] parameter)
{
return GenericTwoWay<TResult>(body, path, HttpMethod.Delete, new int[0], parameter);
}
public TResult DeleteTwoWay<TResult>(object body, string path, int[] allowedStatusCodes, params string[] parameter)
{
return GenericTwoWay<TResult>(body, path, HttpMethod.Delete, allowedStatusCodes, parameter);
}
public void DeleteUpload(object body, string path, params string[] parameter)
{
GenericUpload(body, path, HttpMethod.Delete, new int[0], parameter);
}
public void DeleteUpload(object body, string path, int[] allowedStatusCodes, params string[] parameter)
{
GenericUpload(body, path, HttpMethod.Delete, allowedStatusCodes, parameter);
}
public TResult DeleteDownload<TResult>(string path, params string[] parameter)
{
return GenericDownload<TResult>(path, HttpMethod.Delete, new int[0], parameter);
}
public TResult DeleteDownload<TResult>(string path, int[] allowedStatusCodes, params string[] parameter)
{
return GenericDownload<TResult>(path, HttpMethod.Delete, allowedStatusCodes, parameter);
}
public void DeleteEmpty(string path, params string[] parameter)
{
GenericEmpty(path, HttpMethod.Delete, new int[0], parameter);
}
public void DeleteEmpty(string path, int[] allowedStatusCodes, params string[] parameter)
{
GenericEmpty(path, HttpMethod.Delete, allowedStatusCodes, parameter);
}
#endregion
#region GET
public TResult Get<TResult>(string path, params string[] parameter)
{
return Get<TResult>(path, new int[0], parameter);
}
public TResult Get<TResult>(string path, int[] allowedStatusCodes, params string[] parameter)
{
return GenericDownload<TResult>(path, HttpMethod.Get, allowedStatusCodes, parameter);
}
#endregion
#region GENERIC
private TResult GenericTwoWay<TResult>(object body, string path, HttpMethod method, int[] allowedStatusCodes, params string[] parameter)
{
var uri = CreateUri(path, parameter);
var ident = $"[[{Guid.NewGuid().ToString("N").ToUpper().Substring(0,6)}]]";
string upload = JsonConvert.SerializeObject(body, GetSerializerSettings());
string download;
HttpResponseMessage resp;
try
{
var request = new HttpRequestMessage
{
Content = new StringContent(upload, Encoding.UTF8, "application/json"),
RequestUri = uri,
Method = method,
};
_headers.ToList().ForEach(h => request.Headers.Add(h.Key, h.Value));
LoggerSingleton.Inst.Debug("REST",
$"{ident} SendRequest<GenericTwoWay> [START] ({uri} :: {method})",
$"RequestUri := {uri}\nMethod := {method}\nBody := {body?.GetType()?.FullName ?? "NULL"}\n{((upload == null) ? "" : CompactJsonFormatter.FormatJSON(upload, LOG_FMT_DEPTH))}\n\nHeaders :=\n[\n{string.Join("\n", _headers.Select(h => $" {h.Key} => '{h.Value}'"))}\n]");
resp = _client.SendAsync(request).Result;
if (!resp.IsSuccessStatusCode)
{
if (allowedStatusCodes.Any(sc => sc == (int)resp.StatusCode))
{
LoggerSingleton.Inst.Warn("REST",
$"{ident} SendRequest<GenericTwoWay> [FAILED] ({uri} :: {method})",
$"REST call to '{uri}' [{method}] returned (allowed) statuscode {(int) resp.StatusCode} ({resp.StatusCode})");
_lastResponse = resp;
return default(TResult);
}
string content = string.Empty;
try
{
content = resp.Content.ReadAsStringAsync().Result;
}
catch (Exception)
{
// ignore
}
LoggerSingleton.Inst.Warn("REST",
$"{ident} SendRequest<GenericTwoWay> [ERRORED] ({uri} :: {method})",
$"REST call to '{uri}' [{method}] returned (not-allowed) statuscode {(int)resp.StatusCode} ({resp.StatusCode})\n\n" +
$"Send:\n{CompactJsonFormatter.FormatJSON(upload, LOG_FMT_DEPTH)}\n\n" +
"---------------------\n\n" +
$"Recieved:\n{content}");
if (resp.StatusCode == HttpStatusCode.GatewayTimeout) throw new RestStatuscodeException(uri.Host, (int)resp.StatusCode, resp.ReasonPhrase, content, true);
throw new RestStatuscodeException(uri.Host, (int)resp.StatusCode, resp.ReasonPhrase, content);
}
download = resp.Content.ReadAsStringAsync().Result;
}
catch (AggregateException e)
{
if (e.InnerExceptions.Count == 1)
{
var e0 = e.InnerExceptions.First();
throw new RestException("Could not communicate with server " + uri.Host, e0 is HttpRequestException);
}
else
{
var e0 = e.InnerExceptions.First();
throw new RestException("Could not communicate with server " + uri.Host, e, e0 is HttpRequestException);
}
}
catch (RestException)
{
throw;
}
catch (Exception e)
{
throw new RestException("Could not communicate with server " + uri.Host, e, e is HttpRequestException);
}
TResult downloadObject;
try
{
downloadObject = JsonConvert.DeserializeObject<TResult>(download, _converter);
}
catch (Exception e)
{
throw new RestException("Rest call to " + uri.Host + " returned unexpected data :\r\n" + download, e, false);
}
LoggerSingleton.Inst.Debug("REST",
$"{ident} SendRequest<GenericTwoWay> [FINISH] ({uri} :: {method})",
$"Send:\r\n{CompactJsonFormatter.FormatJSON(upload, LOG_FMT_DEPTH)}\n\n"+
"---------------------\n\n"+
$"Recieved:\n{CompactJsonFormatter.FormatJSON(download, LOG_FMT_DEPTH)}");
_lastResponse = resp;
return downloadObject;
}
private void GenericUpload(object body, string path, HttpMethod method, int[] allowedStatusCodes, params string[] parameter)
{
var uri = CreateUri(path, parameter);
var ident = $"[[{Guid.NewGuid().ToString("N").ToUpper().Substring(0,6)}]]";
string upload = JsonConvert.SerializeObject(body, GetSerializerSettings());
HttpResponseMessage resp;
try
{
var request = new HttpRequestMessage
{
Content = new StringContent(upload, Encoding.UTF8, "application/json"),
RequestUri = uri,
Method = method,
};
_headers.ToList().ForEach(h => request.Headers.Add(h.Key, h.Value));
LoggerSingleton.Inst.Debug("REST",
$"{ident} SendRequest<GenericUpload> [START] ({uri} :: {method})",
$"RequestUri := {uri}\nMethod := {method}\nBody := {body?.GetType()?.FullName ?? "NULL"}\n{((upload == null) ? "" : CompactJsonFormatter.FormatJSON(upload, LOG_FMT_DEPTH))}\n\nHeaders :=\n[\n{string.Join("\n", _headers.Select(h => $" {h.Key} => '{h.Value}'"))}\n]");
resp = _client.SendAsync(request).Result;
if (!resp.IsSuccessStatusCode)
{
if (allowedStatusCodes.Any(sc => sc == (int)resp.StatusCode))
{
LoggerSingleton.Inst.Warn("REST",
$"{ident} SendRequest<GenericUpload> [FAILED] ({uri} :: {method})",
$"REST call to '{uri}' [{method}] returned (allowed) statuscode {(int) resp.StatusCode} ({resp.StatusCode})");
_lastResponse = resp;
return;
}
LoggerSingleton.Inst.Warn("REST",
$"{ident} SendRequest<GenericTwoWay> [ERRORED] ({uri} :: {method})",
$"REST call to '{uri}' [{method}] returned (not-allowed) statuscode {(int)resp.StatusCode} ({resp.StatusCode})\n\n" +
$"Send:\r\n{CompactJsonFormatter.FormatJSON(upload, LOG_FMT_DEPTH)}");
if (resp.StatusCode == HttpStatusCode.GatewayTimeout) throw new RestStatuscodeException(uri.Host, (int)resp.StatusCode, resp.ReasonPhrase, string.Empty, true);
throw new RestStatuscodeException(uri.Host, (int)resp.StatusCode, resp.ReasonPhrase, string.Empty);
}
}
catch (AggregateException e)
{
if (e.InnerExceptions.Count == 1)
{
var e0 = e.InnerExceptions.First();
throw new RestException("Could not communicate with server " + uri.Host, e0 is HttpRequestException);
}
else
{
var e0 = e.InnerExceptions.First();
throw new RestException("Could not communicate with server " + uri.Host, e, e0 is HttpRequestException);
}
}
catch (RestException)
{
throw;
}
catch (Exception e)
{
throw new RestException("Could not communicate with server " + uri.Host, e, e is HttpRequestException);
}
LoggerSingleton.Inst.Debug("REST",
$"{ident} SendRequest<GenericUpload> [FINISH] ({uri} :: {method})",
$"Send:\r\n{CompactJsonFormatter.FormatJSON(upload, LOG_FMT_DEPTH)}\r\n\r\nRecieved: Nothing");
_lastResponse = resp;
}
private TResult GenericDownload<TResult>(string path, HttpMethod method, int[] allowedStatusCodes, params string[] parameter)
{
var uri = CreateUri(path, parameter);
var ident = $"[[{Guid.NewGuid().ToString("N").ToUpper().Substring(0,6)}]]";
string download;
HttpResponseMessage resp;
try
{
var request = new HttpRequestMessage
{
RequestUri = uri,
Method = method,
};
_headers.ToList().ForEach(h => request.Headers.Add(h.Key, h.Value));
LoggerSingleton.Inst.Debug("REST",
$"{ident} SendRequest<GenericDownload> [START] ({uri} :: {method})",
$"RequestUri := {uri}\nMethod := {method}\nHeaders :=\n[\n{string.Join("\n", _headers.Select(h => $" {h.Key} => '{h.Value}'"))}\n]");
resp = _client.SendAsync(request).Result;
if (!resp.IsSuccessStatusCode)
{
if (allowedStatusCodes.Any(sc => sc == (int)resp.StatusCode))
{
LoggerSingleton.Inst.Warn("REST",
$"{ident} SendRequest<GenericDownload> [FAILED] ({uri} :: {method})",
$"REST call to '{uri}' [{method}] returned (allowed) statuscode {(int) resp.StatusCode} ({resp.StatusCode})");
_lastResponse = resp;
return default(TResult);
}
string content = string.Empty;
try
{
content = resp.Content.ReadAsStringAsync().Result;
}
catch (Exception)
{
// ignore
}
LoggerSingleton.Inst.Warn("REST",
$"{ident} SendRequest<GenericTwoWay> [ERRORED] ({uri} :: {method})",
$"REST call to '{uri}' [{method}] returned (not-allowed) statuscode {(int)resp.StatusCode} ({resp.StatusCode})\n\n" +
$"Recieved:\n{content}");
if (resp.StatusCode == HttpStatusCode.GatewayTimeout) throw new RestStatuscodeException(uri.Host, (int)resp.StatusCode, resp.ReasonPhrase, content, true);
throw new RestStatuscodeException(uri.Host, (int)resp.StatusCode, resp.ReasonPhrase, content);
}
download = resp.Content.ReadAsStringAsync().Result;
}
catch (AggregateException e)
{
if (e.InnerExceptions.Count == 1)
{
var e0 = e.InnerExceptions.First();
throw new RestException("Could not communicate with server " + uri.Host, e0 is HttpRequestException);
}
else
{
var e0 = e.InnerExceptions.First();
throw new RestException("Could not communicate with server " + uri.Host, e, e0 is HttpRequestException);
}
}
catch (RestException)
{
throw;
}
catch (Exception e)
{
throw new RestException("Could not communicate with server " + uri.Host, e, e is HttpRequestException);
}
TResult downloadObject;
try
{
downloadObject = JsonConvert.DeserializeObject<TResult>(download, _converter);
}
catch (Exception e)
{
throw new RestException("Rest call to " + uri.Host + " returned unexpected data", "Rest call to " + uri.Host + " returned unexpected data :\r\n" + download, e, false);
}
LoggerSingleton.Inst.Debug("REST",
$"{ident} SendRequest<GenericDownload> [FINISH] ({uri} :: {method})",
$"Send: Nothing\r\nRecieved:\r\n{CompactJsonFormatter.FormatJSON(download, LOG_FMT_DEPTH)}");
_lastResponse = resp;
return downloadObject;
}
private void GenericEmpty(string path, HttpMethod method, int[] allowedStatusCodes, params string[] parameter)
{
var uri = CreateUri(path, parameter);
HttpResponseMessage resp;
try
{
var request = new HttpRequestMessage
{
RequestUri = uri,
Method = method,
};
_headers.ToList().ForEach(h => request.Headers.Add(h.Key, h.Value));
LoggerSingleton.Inst.Debug("REST", "SendRequest<GenericEmpty>", $"RequestUri := {uri}\nMethod := {method}\nHeaders :=\n[\n{string.Join("\n", _headers.Select(h => $" {h.Key} => '{h.Value}'"))}\n]");
resp = _client.SendAsync(request).Result;
if (!resp.IsSuccessStatusCode)
{
if (allowedStatusCodes.Any(sc => sc == (int)resp.StatusCode))
{
LoggerSingleton.Inst.Debug("REST", string.Format("REST call to '{0}' [{3}] returned (allowed) statuscode {1} ({2})", uri, (int)resp.StatusCode, resp.StatusCode, method));
_lastResponse = resp;
return;
}
if (resp.StatusCode == HttpStatusCode.GatewayTimeout) throw new RestStatuscodeException(uri.Host, (int)resp.StatusCode, resp.ReasonPhrase, string.Empty, true);
throw new RestStatuscodeException(uri.Host, (int)resp.StatusCode, resp.ReasonPhrase, string.Empty);
}
}
catch (AggregateException e)
{
if (e.InnerExceptions.Count == 1)
{
var e0 = e.InnerExceptions.First();
throw new RestException("Could not communicate with server " + uri.Host, e0 is HttpRequestException);
}
else
{
var e0 = e.InnerExceptions.First();
throw new RestException("Could not communicate with server " + uri.Host, e, e0 is HttpRequestException);
}
}
catch (RestException)
{
throw;
}
catch (Exception e)
{
throw new RestException("Could not communicate with server " + uri.Host, e, e is HttpRequestException);
}
LoggerSingleton.Inst.Debug("REST", string.Format("Calling REST API '{0}' [{1}]", uri, method), "Send: Nothing\r\n\r\nRecieved: Nothing");
_lastResponse = resp;
}
#endregion
}
}
| |
/*! Achordeon - MIT License
Copyright (c) 2017 tiamatix / Wolf Robben
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 System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Input;
using System.Windows.Threading;
using Achordeon.Common.Helpers;
using Achordeon.Lib.DataModel;
using Achordeon.Lib.Parser;
using Achordeon.Rendering.Ascii;
using Achordeon.Rendering.Pdf;
using Achordeon.Shell.Wpf.Helpers.Converters;
using Achordeon.Shell.Wpf.Properties;
using Common.Logging;
using DryIoc;
using DryIoc.Experimental;
using Microsoft.Win32;
namespace Achordeon.Shell.Wpf.Contents.ChordProFile
{
public class ChordProFileViewModel : ViewModelBase, IDocViewModel
{
private Dispatcher m_Dispatcher;
private CoreViewModel m_Core;
private string m_FileName;
private bool m_HasUnsavedChanges;
private string m_Content;
private Encoding m_Encoding;
private ChordProFileView m_ChordProFileView;
private LinkedSongOptionsViewModel m_SongOptionViewModel;
private ZoomViewModel m_ZoomViewModel;
private ICommand m_SavePdfCommand;
private ICommand m_RunPdfCommand;
private ICommand m_SaveCommand;
private ICommand m_SaveAsCommand;
private ICommand m_CloseCommand;
private ICommand m_PrintCommand;
private ICommand m_ImportPlainTextCommand;
private ICommand m_CommentUncommentSelectionCommand;
private ICommand m_ChorusUnchorusSelectionCommand;
private ICommand m_TabUnTabSelectionCommand;
private ICommand m_EditSongOptionsCommand;
private readonly Regex m_ConvertPlainToCommentRegex = new Regex(@"^\s*(?<text>[^\r\n]+)\s*$");
private readonly Regex m_ConvertCommentToPlainRegex = new Regex(@"^\s*{\s*[c](omment)?(_)?(i)?(talic)?(b)?(ox)?:(?<text>[^\r\n]+)\s*}\s*$", RegexOptions.IgnoreCase);
private ILog Log => Core.IoC.Get<Log>().Using(this);
public ChordProFileViewModel(CoreViewModel ACore,
string AContent,
Encoding AEncoding)
{
Core = ACore;
Dispatcher = Dispatcher.CurrentDispatcher;
Content = AContent ?? Resources.EmptyFileTemplate;
Encoding = AEncoding ?? Encoding.Default;
ZoomViewModel = new ZoomViewModel(Core);
ZoomViewModel.Dispatcher = Dispatcher;
SaveCommand = new SimpleCommand(Save, CanSave);
SaveAsCommand = new SimpleCommand(SaveAs, CanSaveAs);
SavePdfCommand = new SimpleCommand(SavePdf);
RunPdfCommand = new SimpleCommand(RunPdf);
CloseCommand = new SimpleCommand(Close);
PrintCommand = new SimpleCommand(Dummy);
EditSongOptionsCommand = new SimpleCommand(Dummy);
ImportPlainTextCommand = new SimpleCommand(ImportPlainText, CanImportPlainText);
CommentUncommentSelectionCommand = new SimpleCommand(CommentUncommentSelection, CanCommentUncommentSelection);
ChorusUnchorusSelectionCommand = new SimpleCommand(ChorusUnchorusSelection, CanChorusUnchorusSelection);
TabUnTabSelectionCommand = new SimpleCommand(TabUnTabSelection, CanTabUnTabSelection);
SongOptionViewModel = Core.SettingsViewModel.GlobalSongOptions.AsLinkedOptions();
}
public ChordProFileViewModel(CoreViewModel ACore) : this (ACore, null, null)
{
}
private bool CanConvertSelectionToOrFromBlock(CommandWorkingOnSelectionTextArguments Args, string ABlockStart, string ABlockEnd)
{
var ContainsSoc = Regex.IsMatch(Args.SelectedText, @"^\s*{" + ABlockStart + @"}\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
var ContainsEoc = Regex.IsMatch(Args.SelectedText, @"^\s*{" + ABlockEnd + @"}\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
//Check for partial seledction
if (ContainsEoc && !ContainsSoc)
return false;
return !ContainsSoc || ContainsEoc;
}
private void ConvertSelectionToOrFromBlock(CommandWorkingOnSelectionTextArguments Args, string ABlockStart, string ABlockEnd)
{
var ContainsBlockStart = Regex.IsMatch(Args.SelectedText, @"^\s*{" + ABlockStart + @"}\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
var ContainsBlockEnd = Regex.IsMatch(Args.SelectedText, @"^\s*{" + ABlockEnd + @"}\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
//Check for partial seledction
if (ContainsBlockEnd && !ContainsBlockStart)
return;
if (ContainsBlockStart && !ContainsBlockEnd)
return;
//Remember if selection already contained a chorus
var WasAlreadyABlockBefore = ContainsBlockStart;
//Remove old chorus marks in either case
Args.Result = Regex.Replace(Args.SelectedText, @"^\s*{" + ABlockStart + @"}\s*$", AMatch => string.Empty, RegexOptions.Multiline | RegexOptions.IgnoreCase);
Args.Result = Regex.Replace(Args.Result, @"^\s*{" + ABlockEnd + @"}\s*$", AMatch => string.Empty, RegexOptions.Multiline | RegexOptions.IgnoreCase);
Args.Result = Args.Result.Trim();
//Add new chorus marks if it hasn't been a chorus before
if (!WasAlreadyABlockBefore)
Args.Result = "{" + ABlockStart + "}" + Environment.NewLine + Args.Result + Environment.NewLine + "{" + ABlockEnd + "}" + Environment.NewLine;
else
Args.Result += Environment.NewLine;
Args.Success = true;
}
public bool CanChorusUnchorusSelection(object AParameter)
{
var Args = (AParameter as CommandWorkingOnSelectionTextArguments);
if (string.IsNullOrWhiteSpace(Args?.SelectedText))
return false;
return CanConvertSelectionToOrFromBlock(Args, "soc", "eoc");
}
public void ChorusUnchorusSelection(object AParameter)
{
var Args = (AParameter as CommandWorkingOnSelectionTextArguments);
if (Args != null)
ConvertSelectionToOrFromBlock(Args, "soc", "eoc");
}
public bool CanTabUnTabSelection(object AParameter)
{
var Args = (AParameter as CommandWorkingOnSelectionTextArguments);
if (string.IsNullOrWhiteSpace(Args?.SelectedText))
return false;
return CanConvertSelectionToOrFromBlock(Args, "sot", "eot");
}
public void TabUnTabSelection(object AParameter)
{
var Args = (AParameter as CommandWorkingOnSelectionTextArguments);
if (Args != null)
ConvertSelectionToOrFromBlock(Args, "sot", "eot");
}
public bool CanCommentUncommentSelection(object AParameter)
{
var Args = (AParameter as CommandWorkingOnSelectionTextArguments);
if (Args == null)
return false;
var M = m_ConvertCommentToPlainRegex.Match(Args.SelectedText);
if (M.Success)
return true; //Is already a comment, we can uncomment it
M = m_ConvertPlainToCommentRegex.Match(Args.SelectedText);
return M.Success; //Is plain text, but can be commented
}
public void CommentUncommentSelection(object AParameter)
{
var Args = (AParameter as CommandWorkingOnSelectionTextArguments);
if (Args == null)
return;
var M = m_ConvertCommentToPlainRegex.Match(Args.SelectedText);
if (M.Success)
{
//Is already a comment, we can uncomment it
Args.Result = M.Groups["text"].Value;
Args.Success = true;
return;
}
M = m_ConvertPlainToCommentRegex.Match(Args.SelectedText);
if (M.Success)
{
//Is plain text, but can converted to a comment
Args.Result = "{c:" + M.Groups["text"].Value + "}";
Args.Success = true;
}
}
public bool CanImportPlainText(object AParameter)
{
return (AParameter as CommandWorkingOnSelectionTextArguments)?.SelectionLength > 0;
}
public void ImportPlainText(object AParameter)
{
var Args = (AParameter as CommandWorkingOnSelectionTextArguments);
if (Args == null)
return;
if (!CanImportPlainText(AParameter))
return;
var Converter = new PlainTextSongToChordProConverter();
Args.Result = Converter.Convert(Args.SelectedText);
Args.Success = Args.Result != Args.SelectedText;
}
private bool CanSave(object AParameter)
{
return HasUnsavedChanges && !string.IsNullOrWhiteSpace(FileName) && File.Exists(FileName);
}
private bool CanSaveAs(object AParameter)
{
return !string.IsNullOrWhiteSpace(FileName);
}
private void Save(object AParameter)
{
var OverrideFileName = AParameter?.ToString();
if (string.IsNullOrWhiteSpace(OverrideFileName))
{
OverrideFileName = null;
if (!File.Exists(FileName))
{
SaveAs(AParameter);
return;
}
}
Core.DocumentsViewModel.SaveChordProFile(this, OverrideFileName);
OnPropertyChanged(nameof(TabHeaderText));
}
private void SaveAs(object AParameter)
{
var NewFileName = AParameter?.ToString();
if (string.IsNullOrWhiteSpace(NewFileName))
NewFileName = FileName;
var dialog = new SaveFileDialog();
dialog.Filter = Resources.ChordProFileDialogFilter;
dialog.FileName = NewFileName;
var result = dialog.ShowDialog();
if ((result.HasValue) && (result.Value))
NewFileName = dialog.FileName;
else
NewFileName = null;
if (string.IsNullOrWhiteSpace(NewFileName))
return;
Core.DocumentsViewModel.SaveChordProFile(this, NewFileName);
OnPropertyChanged(nameof(TabHeaderText));
}
private void SavePdf(object AParameter)
{
try
{
SavePdf();
}
catch (Exception ex)
{
Log.Error("Exporting PDF file failed", ex);
Core.IoC.Get<IMessageBoxService>().ShowErrorAsync("Export failed", ex.Message);
}
}
private void RunPdf(object AParameter)
{
string PdfFileName;
try
{
PdfFileName = SavePdf();
}
catch (Exception ex)
{
Log.Error("Exporting PDF file failed", ex);
Core.IoC.Get<IMessageBoxService>().ShowErrorAsync("Export failed", ex.Message);
return;
}
try
{
Process.Start(PdfFileName);
}
catch (Exception ex)
{
Log.Error("Starting PDF file failed", ex);
throw new Exception(string.Format(Resources.CannotRunFile, PdfFileName), ex);
}
}
private void Dummy(object AParameter)
{
}
private void Close(object AParameter)
{
Log.TraceFormat("Closing '{0}'", FileName);
Core.DocumentsViewModel.CloseDocument(this);
}
public LinkedSongOptionsViewModel SongOptionViewModel
{
get { return m_SongOptionViewModel; }
set { SetProperty(ref m_SongOptionViewModel, value, nameof(SongOptionViewModel)); }
}
public ICommand ImportPlainTextCommand
{
get { return m_ImportPlainTextCommand; }
set { SetProperty(ref m_ImportPlainTextCommand, value, nameof(ImportPlainTextCommand)); }
}
public ICommand CloseCommand
{
get { return m_CloseCommand; }
set { SetProperty(ref m_CloseCommand, value, nameof(CloseCommand)); }
}
public ICommand SaveCommand
{
get { return m_SaveCommand; }
set { SetProperty(ref m_SaveCommand, value, nameof(SaveCommand)); }
}
public ICommand CommentUncommentSelectionCommand
{
get { return m_CommentUncommentSelectionCommand; }
set { SetProperty(ref m_CommentUncommentSelectionCommand, value, nameof(CommentUncommentSelectionCommand)); }
}
public ICommand TabUnTabSelectionCommand
{
get { return m_TabUnTabSelectionCommand; }
set { SetProperty(ref m_TabUnTabSelectionCommand, value, nameof(TabUnTabSelectionCommand)); }
}
public ICommand ChorusUnchorusSelectionCommand
{
get { return m_ChorusUnchorusSelectionCommand; }
set { SetProperty(ref m_ChorusUnchorusSelectionCommand, value, nameof(ChorusUnchorusSelectionCommand)); }
}
public ICommand SaveAsCommand
{
get { return m_SaveAsCommand; }
set { SetProperty(ref m_SaveAsCommand, value, nameof(SaveAsCommand)); }
}
public ICommand PrintCommand
{
get { return m_PrintCommand; }
set { SetProperty(ref m_PrintCommand, value, nameof(PrintCommand)); }
}
public ICommand RunPdfCommand
{
get { return m_RunPdfCommand; }
set { SetProperty(ref m_RunPdfCommand, value, nameof(RunPdfCommand)); }
}
public ICommand SavePdfCommand
{
get { return m_SavePdfCommand; }
set { SetProperty(ref m_SavePdfCommand, value, nameof(SavePdfCommand)); }
}
public ICommand EditSongOptionsCommand
{
get { return m_EditSongOptionsCommand; }
set { SetProperty(ref m_EditSongOptionsCommand, value, nameof(EditSongOptionsCommand)); }
}
public ZoomViewModel ZoomViewModel
{
get { return m_ZoomViewModel; }
set { SetProperty(ref m_ZoomViewModel, value, nameof(ZoomViewModel)); }
}
public Encoding Encoding
{
get { return m_Encoding; }
set { SetProperty(ref m_Encoding, value, nameof(Encoding)); }
}
public string Content
{
get { return m_Content; }
set { SetProperty(ref m_Content, value, nameof(Content)); }
}
public CoreViewModel Core
{
get { return m_Core; }
set { SetProperty(ref m_Core, value, nameof(Core)); }
}
public Dispatcher Dispatcher
{
get { return m_Dispatcher; }
set
{
SetProperty(ref m_Dispatcher, value, nameof(Dispatcher));
if (ZoomViewModel != null)
ZoomViewModel.Dispatcher = value;
}
}
public string FileName
{
get { return m_FileName; }
set
{
if (SetProperty(ref m_FileName, value, nameof(FileName)))
{
OnPropertyChanged(nameof(TabHeaderText));
OnPropertyChanged(nameof(StatusBarText));
}
}
}
public string TabHeaderText => (string) new TabFileNameConverter().Convert(new object[] {FileName, HasUnsavedChanges}, typeof (string), null, null);
public string StatusBarText => FileName;
public string UniqueKey => FileName;
public bool HasUnsavedChanges
{
get { return m_HasUnsavedChanges; }
set
{
if (SetProperty(ref m_HasUnsavedChanges, value, nameof(HasUnsavedChanges)))
OnPropertyChanged(nameof(TabHeaderText));
}
}
public object GetTabContent()
{
if (m_ChordProFileView == null)
m_ChordProFileView = new ChordProFileView(this);
return m_ChordProFileView;
}
public SongBook GetSongBook()
{
var IoC = Core.IoC;
using (var strm = new StringStream(Content))
using (var Parser = new ChordProParser(IoC, strm))
{
Log.Trace("Reading file...");
Parser.ReadFile();
var DetectedEncoding = Parser.Encoding ?? Encoding.Default;
Log.TraceFormat("File parsing complete. Detected encoding '{0}'", DetectedEncoding.EncodingName);
if (DetectedEncoding.Equals(IoC.Get<Encoding>()))
{
IoC.Unregister(typeof(Encoding));
IoC.RegisterInstance(DetectedEncoding);
}
return Parser.SongBook;
}
}
public string GetAscii()
{
var IoC = Core.IoC;
Log.Trace("Rendering ASCII...");
var Book = GetSongBook();
using (var Renderer = new AsciiRenderer(IoC, Book, SongOptionViewModel))
{
return Renderer.Render();
}
}
public string GetDdl()
{
var IoC = Core.IoC;
Log.Trace("Rendering Ddl...");
var Book = GetSongBook();
using (var Renderer = new PdfRenderer(IoC, Book, SongOptionViewModel))
{
return Renderer.RenderToDdl();
}
}
public void SavePdf(string AFileName)
{
var IoC = Core.IoC;
Log.Trace("Exporting PDF...");
var Book = GetSongBook();
var OutFile = new FileInfo(AFileName);
Log.TraceFormat("Output file is {0}", OutFile.FullName);
using (var Renderer = new PdfRenderer(IoC, Book, SongOptionViewModel))
{
Log.Trace("Creating outfile...");
using (var OutStream = OutFile.Create())
{
Log.Trace("Rendering...");
Renderer.Render(OutStream);
Log.Trace("Flushing...");
}
}
}
private string SavePdf()
{
var PdfFileName = FileName;
if (string.IsNullOrWhiteSpace(PdfFileName) || !File.Exists(PdfFileName))
throw new Exception(Resources.SaveBevorePdf);
PdfFileName = Path.ChangeExtension(PdfFileName, ".pdf");
Log.TraceFormat("Exporting PDF file {0}", PdfFileName);
try
{
if (File.Exists(PdfFileName))
{
Log.Trace($"PDF file {PdfFileName} exists, deleting");
File.Delete(PdfFileName);
}
SavePdf(PdfFileName);
return PdfFileName;
}
catch (Exception ex)
{
Log.Error($"Exporting PDF file {PdfFileName} failed", ex);
throw new Exception(string.Format(Resources.CannotSaveFile, PdfFileName), ex);
}
}
public void BeforeClose(CloseEventArguments AArguments)
{
if (HasUnsavedChanges)
AArguments.AddConfirmationMessage(string.Format(Lib.Properties.Resources.The_song_0_has_unsaved_changes_, Path.GetFileName(FileName)));
}
}
}
| |
//
// Preferences.cs
//
// Author:
// Giannis Skoulis
// Thanos Papathanasiou
//
//
// 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.Net;
using GConf;
namespace Monogle
{
public class Preferences
{
public Client client = new Client();
static string KEY_BASE = "/apps/monogle";
static string KEY_RESULTS_SIZE = KEY_BASE + "/results_size";
static string KEY_PROXY_STATUS = KEY_BASE + "/proxy/status";
static string KEY_PROXY = KEY_BASE + "/proxy/url";
static string KEY_PROXY_PORT = KEY_BASE + "/proxy/port";
static string KEY_HOST_LANG = KEY_BASE + "/host_lang";
static string KEY_RESULTS_LANG = KEY_BASE + "/results_lang";
static string KEY_FILTER = KEY_BASE + "/filter";
static string KEY_SAFE = KEY_BASE + "/safe";
private string _pStatus;
private string _proxy;
private int _proxyPort;
private string _resultsSize;
private string _hostLang;
private string _resultsWritenInLang;
private string _filter;
private string _safe;
private string system_proxy_host;
private int system_proxy_port;
private bool system_proxy_auth;
private string system_proxy_user;
private string system_proxy_pass;
private bool system_use_proxy;
public WebProxy systemProxy{
get {
if (system_use_proxy){
try {
WebProxy myProxy = new WebProxy();
Uri newUri = new Uri(system_proxy_host + ":" + system_proxy_port);
myProxy.Address = newUri;
if (system_proxy_auth) {
myProxy.Credentials = new NetworkCredential(system_proxy_user,system_proxy_pass);
}
return myProxy;
}
catch (Exception){
return null;
}
}
return null;
}
}
public WebProxy userProxy{
get {
try {
WebProxy myProxy = new WebProxy();
Uri newUri = new Uri(proxy.TrimEnd() + ":" + proxyPort);
myProxy.Address = newUri;
return myProxy;
}
catch (Exception){
return null;
}
}
}
public string pStatus
{
get {
return _pStatus;
}
set {
client.Set (KEY_PROXY_STATUS, value);
_pStatus = value;
}
}
public string proxy
{
get{
return _proxy;
}
set{
client.Set (KEY_PROXY, value);
_proxy = value;
}
}
public int proxyPort
{
get{
return _proxyPort;
}
set{
client.Set (KEY_PROXY_PORT, value);
_proxyPort = value;
}
}
public string resultsSize
{
get{
return _resultsSize;
}
set{
client.Set (KEY_RESULTS_SIZE, value);
_resultsSize = value;
}
}
public string hostLang
{
get{
return _hostLang;
}
set{
client.Set (KEY_HOST_LANG, value);
_hostLang = value;
}
}
public string resultsWritenInLang
{
get{
return _resultsWritenInLang;
}
set{
client.Set (KEY_RESULTS_LANG, value);
_resultsWritenInLang = value;
}
}
public string safe
{
get{
return _safe;
}
set{
client.Set (KEY_SAFE, value);
_safe = value;
}
}
public string filter
{
get{
return _filter;
}
set{
client.Set (KEY_FILTER, value);
_filter = value;
}
}
public Preferences()
{
client = new Client();
GuiFromGconf();
client.AddNotify(KEY_BASE, new NotifyEventHandler (GConf_Changed));
}
private void GuiFromGconf()
{
try {
pStatus = (string) client.Get (KEY_PROXY_STATUS);
}
catch (Exception ex){
if (ex is NoSuchKeyException || ex is InvalidCastException){
pStatus = "no";
}
else throw;
}
try {
system_proxy_host = (string) client.Get ("/system/http_proxy/host");
system_proxy_port = (int) client.Get ("/system/http_proxy/port");
system_proxy_auth = (bool) client.Get ("/system/http_proxy/use_authentication");
system_proxy_user = (string) client.Get ("/system/http_proxy/authentication_user");
system_proxy_pass = (string) client.Get ("/system/http_proxy/authentication_password");
system_use_proxy = (bool) client.Get ("/system/http_proxy/use_http_proxy");
}
catch (Exception ex){
if (ex is NoSuchKeyException || ex is InvalidCastException){
pStatus = "no";
}
else throw;
}
try {
proxy = (string) client.Get (KEY_PROXY);
}
catch (Exception ex){
if (ex is NoSuchKeyException || ex is InvalidCastException){
proxy = "";
}
else throw;
}
try {
proxyPort = (int) client.Get (KEY_PROXY_PORT);
}
catch (Exception ex){
if (ex is NoSuchKeyException || ex is InvalidCastException){
proxyPort = 0;
}
else throw;
}
try {
resultsSize = (string) client.Get (KEY_RESULTS_SIZE);
}
catch (Exception ex){
if (ex is NoSuchKeyException || ex is InvalidCastException){
resultsSize = "small";
}
else throw;
}
try {
hostLang = (string) client.Get (KEY_HOST_LANG);
}
catch (Exception ex){
if (ex is NoSuchKeyException || ex is InvalidCastException){
hostLang = "en";
}
else throw;
}
try {
resultsWritenInLang = (string) client.Get (KEY_RESULTS_LANG);
}
catch (Exception ex){
if (ex is NoSuchKeyException || ex is InvalidCastException){
resultsWritenInLang = "lang_en";
}
else throw;
}
try {
safe = (string) client.Get (KEY_SAFE);
}
catch (Exception ex){
if (ex is NoSuchKeyException || ex is InvalidCastException){
safe = "moderate";
}
else throw;
}
try {
filter = (string) client.Get (KEY_FILTER);
}
catch (Exception ex){
if (ex is NoSuchKeyException || ex is InvalidCastException){
filter = "0";
}
else throw;
}
}
public void GConf_Changed(object sender, NotifyEventArgs args)
{
GuiFromGconf();
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Concurrency;
namespace Orleans.Streams
{
internal class PersistentStreamPullingAgent : SystemTarget, IPersistentStreamPullingAgent
{
private static readonly IBackoffProvider DefaultBackoffProvider = new ExponentialBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(1));
private readonly string streamProviderName;
private readonly IStreamProviderRuntime providerRuntime;
private readonly IStreamPubSub pubSub;
private readonly Dictionary<StreamId, StreamConsumerCollection> pubSubCache;
private readonly SafeRandom safeRandom;
private readonly TimeSpan queueGetPeriod;
private readonly TimeSpan initQueueTimeout;
private readonly TimeSpan maxDeliveryTime;
private readonly Logger logger;
private readonly CounterStatistic numReadMessagesCounter;
private readonly CounterStatistic numSentMessagesCounter;
private int numMessages;
private IQueueAdapter queueAdapter;
private IQueueCache queueCache;
private IQueueAdapterReceiver receiver;
private IStreamFailureHandler streamFailureHandler;
private IDisposable timer;
internal readonly QueueId QueueId;
internal PersistentStreamPullingAgent(
GrainId id,
string strProviderName,
IStreamProviderRuntime runtime,
QueueId queueId,
TimeSpan queueGetPeriod,
TimeSpan initQueueTimeout,
TimeSpan maxDeliveryTime)
: base(id, runtime.ExecutingSiloAddress, true)
{
if (runtime == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: runtime reference should not be null");
if (strProviderName == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: strProviderName should not be null");
QueueId = queueId;
streamProviderName = strProviderName;
providerRuntime = runtime;
pubSub = runtime.PubSub(StreamPubSubType.GrainBased);
pubSubCache = new Dictionary<StreamId, StreamConsumerCollection>();
safeRandom = new SafeRandom();
this.queueGetPeriod = queueGetPeriod;
this.initQueueTimeout = initQueueTimeout;
this.maxDeliveryTime = maxDeliveryTime;
numMessages = 0;
logger = providerRuntime.GetLogger(GrainId + "-" + streamProviderName);
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_01,
"Created {0} {1} for Stream Provider {2} on silo {3} for Queue {4}.",
GetType().Name, GrainId.ToDetailedString(), streamProviderName, Silo, QueueId.ToStringWithHashCode());
numReadMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_READ_MESSAGES, strProviderName));
numSentMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_SENT_MESSAGES, strProviderName));
}
/// <summary>
/// Take responsibility for a new queues that was assigned to me via a new range.
/// We first store the new queue in our internal data structure, try to initialize it and start a pumping timer.
/// ERROR HANDLING:
/// The resposibility to handle initializatoion and shutdown failures is inside the INewQueueAdapterReceiver code.
/// The agent will call Initialize once and log an error. It will not call initiliaze again.
/// The receiver itself may attempt later to recover from this error and do initialization again.
/// The agent will assume initialization has succeeded and will subsequently start calling pumping receive.
/// Same applies to shutdown.
/// </summary>
/// <param name="qAdapter"></param>
/// <param name="queueAdapterCache"></param>
/// <param name="failureHandler"></param>
/// <returns></returns>
public async Task Initialize(Immutable<IQueueAdapter> qAdapter, Immutable<IQueueAdapterCache> queueAdapterCache, Immutable<IStreamFailureHandler> failureHandler)
{
if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null");
if (failureHandler.Value == null) throw new ArgumentNullException("failureHandler", "Init: streamDeliveryFailureHandler should not be null");
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_02, "Init of {0} {1} on silo {2} for queue {3}.",
GetType().Name, GrainId.ToDetailedString(), Silo, QueueId.ToStringWithHashCode());
// Remove cast once we cleanup
queueAdapter = qAdapter.Value;
streamFailureHandler = failureHandler.Value;
try
{
receiver = queueAdapter.CreateReceiver(QueueId);
}
catch (Exception exc)
{
logger.Error((int)ErrorCode.PersistentStreamPullingAgent_02, String.Format("Exception while calling IQueueAdapter.CreateNewReceiver."), exc);
return;
}
try
{
if (queueAdapterCache.Value != null)
{
queueCache = queueAdapterCache.Value.CreateQueueCache(QueueId);
}
}
catch (Exception exc)
{
logger.Error((int)ErrorCode.PersistentStreamPullingAgent_23, String.Format("Exception while calling IQueueAdapterCache.CreateQueueCache."), exc);
return;
}
try
{
var task = OrleansTaskExtentions.SafeExecute(() => receiver.Initialize(initQueueTimeout));
task = task.LogException(logger, ErrorCode.PersistentStreamPullingAgent_03, String.Format("QueueAdapterReceiver {0} failed to Initialize.", QueueId.ToStringWithHashCode()));
await task;
}
catch
{
// Just ignore this exception and proceed as if Initialize has succeeded.
// We already logged individual exceptions for individual calls to Initialize. No need to log again.
}
// Setup a reader for a new receiver.
// Even if the receiver failed to initialise, treat it as OK and start pumping it. It's receiver responsibility to retry initialization.
var randomTimerOffset = safeRandom.NextTimeSpan(queueGetPeriod);
timer = providerRuntime.RegisterTimer(AsyncTimerCallback, QueueId, randomTimerOffset, queueGetPeriod);
logger.Info((int) ErrorCode.PersistentStreamPullingAgent_04, "Taking queue {0} under my responsibility.", QueueId.ToStringWithHashCode());
}
public async Task Shutdown()
{
// Stop pulling from queues that are not in my range anymore.
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_05, "Shutdown of {0} responsible for queue: {1}", GetType().Name, QueueId.ToStringWithHashCode());
if (timer != null)
{
var tmp = timer;
timer = null;
tmp.Dispose();
}
var unregisterTasks = new List<Task>();
var meAsStreamProducer = this.AsReference<IStreamProducerExtension>();
foreach (var streamId in pubSubCache.Keys)
{
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_06, "Unregister PersistentStreamPullingAgent Producer for stream {0}.", streamId);
unregisterTasks.Add(pubSub.UnregisterProducer(streamId, streamProviderName, meAsStreamProducer));
}
try
{
var task = OrleansTaskExtentions.SafeExecute(() => receiver.Shutdown(initQueueTimeout));
task = task.LogException(logger, ErrorCode.PersistentStreamPullingAgent_07,
String.Format("QueueAdapterReceiver {0} failed to Shutdown.", QueueId));
await task;
}
catch
{
// Just ignore this exception and proceed as if Shutdown has succeeded.
// We already logged individual exceptions for individual calls to Shutdown. No need to log again.
}
try
{
await Task.WhenAll(unregisterTasks);
}
catch (Exception exc)
{
logger.Warn((int)ErrorCode.PersistentStreamPullingAgent_08,
"Failed to unregister myself as stream producer to some streams taht used to be in my responsibility.", exc);
}
}
public Task AddSubscriber(
GuidId subscriptionId,
StreamId streamId,
IStreamConsumerExtension streamConsumer,
StreamSequenceToken token,
IStreamFilterPredicateWrapper filter)
{
if (logger.IsVerbose) logger.Verbose((int)ErrorCode.PersistentStreamPullingAgent_09, "AddSubscriber: Stream={0} Subscriber={1} Token={2}.", streamId, streamConsumer, token);
AddSubscriber_Impl(subscriptionId, streamId, streamConsumer, token, filter);
return TaskDone.Done;
}
// Called by rendezvous when new remote subscriber subscribes to this stream.
private void AddSubscriber_Impl(
GuidId subscriptionId,
StreamId streamId,
IStreamConsumerExtension streamConsumer,
StreamSequenceToken token,
IStreamFilterPredicateWrapper filter)
{
StreamConsumerCollection streamDataCollection;
if (!pubSubCache.TryGetValue(streamId, out streamDataCollection))
{
streamDataCollection = new StreamConsumerCollection();
pubSubCache.Add(streamId, streamDataCollection);
}
StreamConsumerData data;
if (!streamDataCollection.TryGetConsumer(subscriptionId, out data))
data = streamDataCollection.AddConsumer(subscriptionId, streamId, streamConsumer, token, filter);
// Set cursor if not cursor is set, or if subscription provides new token
if ((data.Cursor == null || token != null) && queueCache != null)
data.Cursor = queueCache.GetCacheCursor(streamId.Guid, streamId.Namespace, token);
if (data.State == StreamConsumerDataState.Inactive)
RunConsumerCursor(data, filter).Ignore(); // Start delivering events if not actively doing so
}
public Task RemoveSubscriber(GuidId subscriptionId, StreamId streamId)
{
RemoveSubscriber_Impl(subscriptionId, streamId);
return TaskDone.Done;
}
public void RemoveSubscriber_Impl(GuidId subscriptionId, StreamId streamId)
{
StreamConsumerCollection streamData;
if (!pubSubCache.TryGetValue(streamId, out streamData)) return;
// remove consumer
bool removed = streamData.RemoveConsumer(subscriptionId);
if (removed && logger.IsVerbose) logger.Verbose((int)ErrorCode.PersistentStreamPullingAgent_10, "Removed Consumer: subscription={0}, for stream {1}.", subscriptionId, streamId);
if (streamData.Count == 0)
pubSubCache.Remove(streamId);
}
private async Task AsyncTimerCallback(object state)
{
try
{
var myQueueId = (QueueId)(state);
if (timer == null) return; // timer was already removed, last tick
IQueueAdapterReceiver rcvr = receiver;
int maxCacheAddCount = queueCache != null ? queueCache.MaxAddCount : QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG;
// loop through the queue until it is empty.
while (true)
{
if (queueCache != null && queueCache.IsUnderPressure())
{
// Under back pressure. Exit the loop. Will attempt again in the next timer callback.
logger.Info((int)ErrorCode.PersistentStreamPullingAgent_24, String.Format("Stream cache is under pressure. Backing off."));
return;
}
// Retrive one multiBatch from the queue. Every multiBatch has an IEnumerable of IBatchContainers, each IBatchContainer may have multiple events.
IList<IBatchContainer> multiBatch = await rcvr.GetQueueMessagesAsync(maxCacheAddCount);
if (multiBatch == null || multiBatch.Count == 0) return; // queue is empty. Exit the loop. Will attempt again in the next timer callback.
if (queueCache != null)
{
queueCache.AddToCache(multiBatch);
}
numMessages += multiBatch.Count;
numReadMessagesCounter.IncrementBy(multiBatch.Count);
if (logger.IsVerbose2) logger.Verbose2((int)ErrorCode.PersistentStreamPullingAgent_11, "Got {0} messages from queue {1}. So far {2} msgs from this queue.",
multiBatch.Count, myQueueId.ToStringWithHashCode(), numMessages);
foreach (var group in multiBatch.Where(m => m != null)
.GroupBy(container => new Tuple<Guid, string>(container.StreamGuid, container.StreamNamespace)))
{
var streamId = StreamId.GetStreamId(group.Key.Item1, queueAdapter.Name, group.Key.Item2);
StreamConsumerCollection streamData;
if (pubSubCache.TryGetValue(streamId, out streamData))
StartInactiveCursors(streamId, streamData); // if this is an existing stream, start any inactive cursors
else
RegisterStream(streamId, group.First().SequenceToken).Ignore(); ; // if this is a new stream register as producer of stream in pub sub system
}
}
}
catch (Exception exc)
{
logger.Error((int)ErrorCode.PersistentStreamPullingAgent_12,
String.Format("Exception while PersistentStreamPullingAgentGrain.AsyncTimerCallback"), exc);
}
}
private async Task RegisterStream(StreamId streamId, StreamSequenceToken firstToken)
{
var streamData = new StreamConsumerCollection();
pubSubCache.Add(streamId, streamData);
// Create a fake cursor to point into a cache.
// That way we will not purge the event from the cache, until we talk to pub sub.
// This will help ensure the "casual consistency" between pre-existing subscripton (of a potentially new already subscribed consumer)
// and later production.
var pinCursor = queueCache.GetCacheCursor(streamId.Guid, streamId.Namespace, firstToken);
try
{
await RegisterAsStreamProducer(streamId, firstToken);
}finally
{
// Cleanup the fake pinning cursor.
pinCursor.Dispose();
}
}
private void StartInactiveCursors(StreamId streamId, StreamConsumerCollection streamData)
{
// if stream is already registered, just wake inactive consumers
// get list of inactive consumers
var inactiveStreamConsumers = streamData.AllConsumersForStream(streamId)
.Where(consumer => consumer.State == StreamConsumerDataState.Inactive)
.ToList();
// for each inactive stream
foreach (StreamConsumerData consumerData in inactiveStreamConsumers)
RunConsumerCursor(consumerData, consumerData.Filter).Ignore();
}
private async Task RunConsumerCursor(StreamConsumerData consumerData, IStreamFilterPredicateWrapper filterWrapper)
{
try
{
// double check in case of interleaving
if (consumerData.State == StreamConsumerDataState.Active ||
consumerData.Cursor == null) return;
consumerData.State = StreamConsumerDataState.Active;
while (consumerData.Cursor != null && consumerData.Cursor.MoveNext())
{
IBatchContainer batch = null;
Exception ex;
Task deliveryTask;
bool deliveryFailed = false;
try
{
batch = consumerData.Cursor.GetCurrent(out ex);
}
catch (DataNotAvailableException dataNotAvailable)
{
ex = dataNotAvailable;
}
// Apply filtering to this batch, if applicable
if (filterWrapper != null && batch != null)
{
try
{
// Apply batch filter to this input batch, to see whether we should deliver it to this consumer.
if (!batch.ShouldDeliver(
consumerData.StreamId,
filterWrapper.FilterData,
filterWrapper.ShouldReceive)) continue; // Skip this batch -- nothing to do
}
catch (Exception exc)
{
var message = string.Format("Ignoring exception while trying to evaluate subscription filter function {0} on stream {1} in PersistentStreamPullingAgentGrain.RunConsumerCursor", filterWrapper, consumerData.StreamId);
logger.Warn((int) ErrorCode.PersistentStreamPullingAgent_13, message, exc);
}
}
if (batch != null)
{
deliveryTask = AsyncExecutorWithRetries.ExecuteWithRetries(i => consumerData.StreamConsumer.DeliverBatch(consumerData.SubscriptionId, batch.AsImmutable()),
AsyncExecutorWithRetries.INFINITE_RETRIES, (exception, i) => true, maxDeliveryTime, DefaultBackoffProvider);
}
else if (ex == null)
{
deliveryTask = consumerData.StreamConsumer.CompleteStream(consumerData.SubscriptionId);
}
else
{
deliveryTask = consumerData.StreamConsumer.ErrorInStream(consumerData.SubscriptionId, ex);
}
try
{
numSentMessagesCounter.Increment();
await deliveryTask;
}
catch (Exception exc)
{
var message = string.Format("Exception while trying to deliver msgs to stream {0} in PersistentStreamPullingAgentGrain.RunConsumerCursor", consumerData.StreamId);
logger.Error((int)ErrorCode.PersistentStreamPullingAgent_14, message, exc);
deliveryFailed = true;
}
// if we failed to deliver a batch
if (deliveryFailed && batch != null)
{
// notify consumer of delivery error, if we can.
consumerData.StreamConsumer.ErrorInStream(consumerData.SubscriptionId, new StreamEventDeliveryFailureException(consumerData.StreamId)).Ignore();
// record that there was a delivery failure
await streamFailureHandler.OnDeliveryFailure(consumerData.SubscriptionId, streamProviderName,
consumerData.StreamId, batch.SequenceToken);
// if configured to fault on delivery failure and this is not an implicit subscription, fault and remove the subscription
if (streamFailureHandler.ShouldFaultSubsriptionOnError && !SubscriptionMarker.IsImplicitSubscription(consumerData.SubscriptionId.Guid))
{
try
{
// notify consumer of faulted subscription, if we can.
consumerData.StreamConsumer.ErrorInStream(consumerData.SubscriptionId,
new FaultedSubscriptionException(consumerData.SubscriptionId, consumerData.StreamId))
.Ignore();
// mark subscription as faulted.
await pubSub.FaultSubscription(consumerData.SubscriptionId, consumerData.StreamId);
}
finally
{
// remove subscription
RemoveSubscriber_Impl(consumerData.SubscriptionId, consumerData.StreamId);
}
return;
}
}
}
consumerData.State = StreamConsumerDataState.Inactive;
}
catch (Exception exc)
{
// RunConsumerCursor is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception
logger.Error((int)ErrorCode.PersistentStreamPullingAgent_15, "Ignored RunConsumerCursor Error", exc);
throw;
}
}
private async Task RegisterAsStreamProducer(StreamId streamId, StreamSequenceToken streamStartToken)
{
try
{
if (pubSub == null) throw new NullReferenceException("Found pubSub reference not set up correctly in RetreaveNewStream");
IStreamProducerExtension meAsStreamProducer = this.AsReference<IStreamProducerExtension>();
ISet<PubSubSubscriptionState> streamData = await pubSub.RegisterProducer(streamId, streamProviderName, meAsStreamProducer);
if (logger.IsVerbose) logger.Verbose((int)ErrorCode.PersistentStreamPullingAgent_16, "Got back {0} Subscribers for stream {1}.", streamData.Count, streamId);
foreach (PubSubSubscriptionState item in streamData)
{
var token = item.StreamSequenceToken ?? streamStartToken;
AddSubscriber_Impl(item.SubscriptionId, item.Stream, item.Consumer, token, item.Filter);
}
}
catch (Exception exc)
{
// RegisterAsStreamProducer is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception
logger.Error((int)ErrorCode.PersistentStreamPullingAgent_17, "Ignored RegisterAsStreamProducer Error", exc);
throw;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using chat.services;
using chat.model;
using chat.network.dto;
using chat.network.protocol;
namespace chat.network.server
{
///
/// <summary> * Created by IntelliJ IDEA.
/// * User: grigo
/// * Date: Mar 18, 2009
/// * Time: 4:36:34 PM </summary>
///
public class ChatServerProxy : IChatServer
{
private string host;
private int port;
private IChatObserver client;
private NetworkStream stream;
private IFormatter formatter;
private TcpClient connection;
private Queue<Response> responses;
private volatile bool finished;
private EventWaitHandle _waitHandle;
public ChatServerProxy(string host, int port)
{
this.host = host;
this.port = port;
responses=new Queue<Response>();
}
public virtual void login(User user, IChatObserver client)
{
initializeConnection();
UserDTO udto = DTOUtils.getDTO(user);
sendRequest(new LoginRequest(udto));
Response response =readResponse();
if (response is OkResponse)
{
this.client=client;
return;
}
if (response is ErrorResponse)
{
ErrorResponse err =(ErrorResponse)response;
closeConnection();
throw new ChatException(err.Message);
}
}
public virtual void sendMessage(Message message)
{
MessageDTO mdto =DTOUtils.getDTO(message);
sendRequest(new SendMessageRequest(mdto));
Response response =readResponse();
if (response is ErrorResponse)
{
ErrorResponse err =(ErrorResponse)response;
throw new ChatException(err.Message);
}
}
public virtual void logout(User user, IChatObserver client)
{
UserDTO udto =DTOUtils.getDTO(user);
sendRequest(new LogoutRequest(udto));
Response response =readResponse();
closeConnection();
if (response is ErrorResponse)
{
ErrorResponse err =(ErrorResponse)response;
throw new ChatException(err.Message);
}
}
public virtual User[] getLoggedFriends(User user)
{
UserDTO udto =DTOUtils.getDTO(user);
sendRequest(new GetLoggedFriendsRequest(udto));
Response response =readResponse();
if (response is ErrorResponse)
{
ErrorResponse err =(ErrorResponse)response;
throw new ChatException(err.Message);
}
GetLoggedFriendsResponse resp =(GetLoggedFriendsResponse)response;
UserDTO[] frDTO =resp.Friends;
User[] friends =DTOUtils.getFromDTO(frDTO);
return friends;
}
private void closeConnection()
{
finished=true;
try
{
stream.Close();
//output.close();
connection.Close();
_waitHandle.Close();
client=null;
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
private void sendRequest(Request request)
{
try
{
formatter.Serialize(stream, request);
stream.Flush();
}
catch (Exception e)
{
throw new ChatException("Error sending object "+e);
}
}
private Response readResponse()
{
Response response =null;
try
{
_waitHandle.WaitOne();
lock (responses)
{
//Monitor.Wait(responses);
response = responses.Dequeue();
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
return response;
}
private void initializeConnection()
{
try
{
connection=new TcpClient(host,port);
stream=connection.GetStream();
formatter = new BinaryFormatter();
finished=false;
_waitHandle = new AutoResetEvent(false);
startReader();
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
}
private void startReader()
{
Thread tw =new Thread(run);
tw.Start();
}
private void handleUpdate(UpdateResponse update)
{
if (update is FriendLoggedInResponse)
{
FriendLoggedInResponse frUpd =(FriendLoggedInResponse)update;
User friend =DTOUtils.getFromDTO(frUpd.Friend);
Console.WriteLine("Friend logged in "+friend);
try
{
client.friendLoggedIn(friend);
}
catch (ChatException e)
{
Console.WriteLine(e.StackTrace);
}
}
if (update is FriendLoggedOutResponse)
{
FriendLoggedOutResponse frOutRes =(FriendLoggedOutResponse)update;
User friend =DTOUtils.getFromDTO(frOutRes.Friend);
Console.WriteLine("Friend logged out "+friend);
try
{
client.friendLoggedOut(friend);
}
catch (ChatException e)
{
Console.WriteLine(e.StackTrace);
}
}
if (update is NewMessageResponse)
{
NewMessageResponse msgRes =(NewMessageResponse)update;
Message message =DTOUtils.getFromDTO(msgRes.Message);
try
{
client.messageReceived(message);
}
catch (ChatException e)
{
Console.WriteLine(e.StackTrace);
}
}
}
public virtual void run()
{
while(!finished)
{
try
{
object response = formatter.Deserialize(stream);
Console.WriteLine("response received "+response);
if (response is UpdateResponse)
{
handleUpdate((UpdateResponse)response);
}
else
{
lock (responses)
{
responses.Enqueue((Response)response);
}
_waitHandle.Set();
}
}
catch (Exception e)
{
Console.WriteLine("Reading error "+e);
}
}
}
//}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnUadParametro class.
/// </summary>
[Serializable]
public partial class PnUadParametroCollection : ActiveList<PnUadParametro, PnUadParametroCollection>
{
public PnUadParametroCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnUadParametroCollection</returns>
public PnUadParametroCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnUadParametro o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_uad_parametros table.
/// </summary>
[Serializable]
public partial class PnUadParametro : ActiveRecord<PnUadParametro>, IActiveRecord
{
#region .ctors and Default Settings
public PnUadParametro()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnUadParametro(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnUadParametro(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnUadParametro(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_uad_parametros", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdParametros = new TableSchema.TableColumn(schema);
colvarIdParametros.ColumnName = "id_parametros";
colvarIdParametros.DataType = DbType.Int32;
colvarIdParametros.MaxLength = 0;
colvarIdParametros.AutoIncrement = true;
colvarIdParametros.IsNullable = false;
colvarIdParametros.IsPrimaryKey = true;
colvarIdParametros.IsForeignKey = false;
colvarIdParametros.IsReadOnly = false;
colvarIdParametros.DefaultSetting = @"";
colvarIdParametros.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdParametros);
TableSchema.TableColumn colvarCodigoProvincia = new TableSchema.TableColumn(schema);
colvarCodigoProvincia.ColumnName = "codigo_provincia";
colvarCodigoProvincia.DataType = DbType.AnsiString;
colvarCodigoProvincia.MaxLength = 2;
colvarCodigoProvincia.AutoIncrement = false;
colvarCodigoProvincia.IsNullable = true;
colvarCodigoProvincia.IsPrimaryKey = false;
colvarCodigoProvincia.IsForeignKey = false;
colvarCodigoProvincia.IsReadOnly = false;
colvarCodigoProvincia.DefaultSetting = @"";
colvarCodigoProvincia.ForeignKeyTableName = "";
schema.Columns.Add(colvarCodigoProvincia);
TableSchema.TableColumn colvarCodigoUad = new TableSchema.TableColumn(schema);
colvarCodigoUad.ColumnName = "codigo_uad";
colvarCodigoUad.DataType = DbType.AnsiString;
colvarCodigoUad.MaxLength = 5;
colvarCodigoUad.AutoIncrement = false;
colvarCodigoUad.IsNullable = true;
colvarCodigoUad.IsPrimaryKey = false;
colvarCodigoUad.IsForeignKey = false;
colvarCodigoUad.IsReadOnly = false;
colvarCodigoUad.DefaultSetting = @"";
colvarCodigoUad.ForeignKeyTableName = "";
schema.Columns.Add(colvarCodigoUad);
TableSchema.TableColumn colvarNombreUad = new TableSchema.TableColumn(schema);
colvarNombreUad.ColumnName = "nombre_uad";
colvarNombreUad.DataType = DbType.AnsiString;
colvarNombreUad.MaxLength = 30;
colvarNombreUad.AutoIncrement = false;
colvarNombreUad.IsNullable = true;
colvarNombreUad.IsPrimaryKey = false;
colvarNombreUad.IsForeignKey = false;
colvarNombreUad.IsReadOnly = false;
colvarNombreUad.DefaultSetting = @"";
colvarNombreUad.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombreUad);
TableSchema.TableColumn colvarCodigoCi = new TableSchema.TableColumn(schema);
colvarCodigoCi.ColumnName = "codigo_ci";
colvarCodigoCi.DataType = DbType.AnsiString;
colvarCodigoCi.MaxLength = 5;
colvarCodigoCi.AutoIncrement = false;
colvarCodigoCi.IsNullable = true;
colvarCodigoCi.IsPrimaryKey = false;
colvarCodigoCi.IsForeignKey = false;
colvarCodigoCi.IsReadOnly = false;
colvarCodigoCi.DefaultSetting = @"";
colvarCodigoCi.ForeignKeyTableName = "";
schema.Columns.Add(colvarCodigoCi);
TableSchema.TableColumn colvarNombreCi = new TableSchema.TableColumn(schema);
colvarNombreCi.ColumnName = "nombre_ci";
colvarNombreCi.DataType = DbType.AnsiString;
colvarNombreCi.MaxLength = 30;
colvarNombreCi.AutoIncrement = false;
colvarNombreCi.IsNullable = true;
colvarNombreCi.IsPrimaryKey = false;
colvarNombreCi.IsForeignKey = false;
colvarNombreCi.IsReadOnly = false;
colvarNombreCi.DefaultSetting = @"";
colvarNombreCi.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombreCi);
TableSchema.TableColumn colvarNombreProvincia = new TableSchema.TableColumn(schema);
colvarNombreProvincia.ColumnName = "nombre_provincia";
colvarNombreProvincia.DataType = DbType.AnsiStringFixedLength;
colvarNombreProvincia.MaxLength = 20;
colvarNombreProvincia.AutoIncrement = false;
colvarNombreProvincia.IsNullable = true;
colvarNombreProvincia.IsPrimaryKey = false;
colvarNombreProvincia.IsForeignKey = false;
colvarNombreProvincia.IsReadOnly = false;
colvarNombreProvincia.DefaultSetting = @"";
colvarNombreProvincia.ForeignKeyTableName = "";
schema.Columns.Add(colvarNombreProvincia);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_uad_parametros",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdParametros")]
[Bindable(true)]
public int IdParametros
{
get { return GetColumnValue<int>(Columns.IdParametros); }
set { SetColumnValue(Columns.IdParametros, value); }
}
[XmlAttribute("CodigoProvincia")]
[Bindable(true)]
public string CodigoProvincia
{
get { return GetColumnValue<string>(Columns.CodigoProvincia); }
set { SetColumnValue(Columns.CodigoProvincia, value); }
}
[XmlAttribute("CodigoUad")]
[Bindable(true)]
public string CodigoUad
{
get { return GetColumnValue<string>(Columns.CodigoUad); }
set { SetColumnValue(Columns.CodigoUad, value); }
}
[XmlAttribute("NombreUad")]
[Bindable(true)]
public string NombreUad
{
get { return GetColumnValue<string>(Columns.NombreUad); }
set { SetColumnValue(Columns.NombreUad, value); }
}
[XmlAttribute("CodigoCi")]
[Bindable(true)]
public string CodigoCi
{
get { return GetColumnValue<string>(Columns.CodigoCi); }
set { SetColumnValue(Columns.CodigoCi, value); }
}
[XmlAttribute("NombreCi")]
[Bindable(true)]
public string NombreCi
{
get { return GetColumnValue<string>(Columns.NombreCi); }
set { SetColumnValue(Columns.NombreCi, value); }
}
[XmlAttribute("NombreProvincia")]
[Bindable(true)]
public string NombreProvincia
{
get { return GetColumnValue<string>(Columns.NombreProvincia); }
set { SetColumnValue(Columns.NombreProvincia, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varCodigoProvincia,string varCodigoUad,string varNombreUad,string varCodigoCi,string varNombreCi,string varNombreProvincia)
{
PnUadParametro item = new PnUadParametro();
item.CodigoProvincia = varCodigoProvincia;
item.CodigoUad = varCodigoUad;
item.NombreUad = varNombreUad;
item.CodigoCi = varCodigoCi;
item.NombreCi = varNombreCi;
item.NombreProvincia = varNombreProvincia;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdParametros,string varCodigoProvincia,string varCodigoUad,string varNombreUad,string varCodigoCi,string varNombreCi,string varNombreProvincia)
{
PnUadParametro item = new PnUadParametro();
item.IdParametros = varIdParametros;
item.CodigoProvincia = varCodigoProvincia;
item.CodigoUad = varCodigoUad;
item.NombreUad = varNombreUad;
item.CodigoCi = varCodigoCi;
item.NombreCi = varNombreCi;
item.NombreProvincia = varNombreProvincia;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdParametrosColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CodigoProvinciaColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn CodigoUadColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn NombreUadColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn CodigoCiColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn NombreCiColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn NombreProvinciaColumn
{
get { return Schema.Columns[6]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdParametros = @"id_parametros";
public static string CodigoProvincia = @"codigo_provincia";
public static string CodigoUad = @"codigo_uad";
public static string NombreUad = @"nombre_uad";
public static string CodigoCi = @"codigo_ci";
public static string NombreCi = @"nombre_ci";
public static string NombreProvincia = @"nombre_provincia";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using OpenMetaverse;
namespace OpenSim.Framework
{
public class EstateSettings
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public delegate void SaveDelegate(EstateSettings rs);
public event SaveDelegate OnSave;
// Only the client uses these
//
private uint m_EstateID = 100;
public uint EstateID
{
get { return m_EstateID; }
set { m_EstateID = value; }
}
private string m_EstateName = "My Estate";
public string EstateName
{
get { return m_EstateName; }
set { m_EstateName = value; }
}
private uint m_ParentEstateID = 1;
public uint ParentEstateID
{
get { return m_ParentEstateID; }
set { m_ParentEstateID = value; }
}
private float m_BillableFactor;
public float BillableFactor
{
get { return m_BillableFactor; }
set { m_BillableFactor = value; }
}
private int m_PricePerMeter;
public int PricePerMeter
{
get { return m_PricePerMeter; }
set { m_PricePerMeter = value; }
}
private int m_RedirectGridX;
public int RedirectGridX
{
get { return m_RedirectGridX; }
set { m_RedirectGridX = value; }
}
private int m_RedirectGridY;
public int RedirectGridY
{
get { return m_RedirectGridY; }
set { m_RedirectGridY = value; }
}
// Used by the sim
//
private bool m_UseGlobalTime = true;
public bool UseGlobalTime
{
get { return m_UseGlobalTime; }
set { m_UseGlobalTime = value; }
}
private bool m_FixedSun = false;
public bool FixedSun
{
get { return m_FixedSun; }
set { m_FixedSun = value; }
}
private double m_SunPosition = 0.0;
public double SunPosition
{
get { return m_SunPosition; }
set { m_SunPosition = value; }
}
private bool m_AllowVoice = true;
public bool AllowVoice
{
get { return m_AllowVoice; }
set { m_AllowVoice = value; }
}
private bool m_AllowDirectTeleport = true;
public bool AllowDirectTeleport
{
get { return m_AllowDirectTeleport; }
set { m_AllowDirectTeleport = value; }
}
private bool m_DenyAnonymous = false;
public bool DenyAnonymous
{
get { return m_DenyAnonymous; }
set { m_DenyAnonymous = value; }
}
private bool m_DenyIdentified = false;
public bool DenyIdentified
{
get { return m_DenyIdentified; }
set { m_DenyIdentified = value; }
}
private bool m_DenyTransacted = false;
public bool DenyTransacted
{
get { return m_DenyTransacted; }
set { m_DenyTransacted = value; }
}
private bool m_AbuseEmailToEstateOwner = false;
public bool AbuseEmailToEstateOwner
{
get { return m_AbuseEmailToEstateOwner; }
set { m_AbuseEmailToEstateOwner = value; }
}
private bool m_BlockDwell = false;
public bool BlockDwell
{
get { return m_BlockDwell; }
set { m_BlockDwell = value; }
}
private bool m_EstateSkipScripts = false;
public bool EstateSkipScripts
{
get { return m_EstateSkipScripts; }
set { m_EstateSkipScripts = value; }
}
private bool m_ResetHomeOnTeleport = false;
public bool ResetHomeOnTeleport
{
get { return m_ResetHomeOnTeleport; }
set { m_ResetHomeOnTeleport = value; }
}
private bool m_TaxFree = false;
public bool TaxFree
{
get { return m_TaxFree; }
set { m_TaxFree = value; }
}
private bool m_PublicAccess = true;
public bool PublicAccess
{
get { return m_PublicAccess; }
set { m_PublicAccess = value; }
}
private string m_AbuseEmail = String.Empty;
public string AbuseEmail
{
get { return m_AbuseEmail; }
set { m_AbuseEmail= value; }
}
private UUID m_EstateOwner = UUID.Zero;
public UUID EstateOwner
{
get { return m_EstateOwner; }
set { m_EstateOwner = value; }
}
private bool m_DenyMinors = false;
public bool DenyMinors
{
get { return m_DenyMinors; }
set { m_DenyMinors = value; }
}
// All those lists...
//
private List<UUID> l_EstateManagers = new List<UUID>();
public UUID[] EstateManagers
{
get { return l_EstateManagers.ToArray(); }
set { l_EstateManagers = new List<UUID>(value); }
}
private List<EstateBan> l_EstateBans = new List<EstateBan>();
public EstateBan[] EstateBans
{
get { return l_EstateBans.ToArray(); }
set { l_EstateBans = new List<EstateBan>(value); }
}
private List<UUID> l_EstateAccess = new List<UUID>();
public UUID[] EstateAccess
{
get { return l_EstateAccess.ToArray(); }
set { l_EstateAccess = new List<UUID>(value); }
}
private List<UUID> l_EstateGroups = new List<UUID>();
public UUID[] EstateGroups
{
get { return l_EstateGroups.ToArray(); }
set { l_EstateGroups = new List<UUID>(value); }
}
public EstateSettings()
{
}
public void Save()
{
if (OnSave != null)
OnSave(this);
}
public void AddEstateUser(UUID avatarID)
{
if (avatarID == UUID.Zero)
return;
if (!l_EstateAccess.Contains(avatarID))
l_EstateAccess.Add(avatarID);
}
public void RemoveEstateUser(UUID avatarID)
{
if (l_EstateAccess.Contains(avatarID))
l_EstateAccess.Remove(avatarID);
}
public void AddEstateGroup(UUID avatarID)
{
if (avatarID == UUID.Zero)
return;
if (!l_EstateGroups.Contains(avatarID))
l_EstateGroups.Add(avatarID);
}
public void RemoveEstateGroup(UUID avatarID)
{
if (l_EstateGroups.Contains(avatarID))
l_EstateGroups.Remove(avatarID);
}
public void AddEstateManager(UUID avatarID)
{
if (avatarID == UUID.Zero)
return;
if (!l_EstateManagers.Contains(avatarID))
l_EstateManagers.Add(avatarID);
}
public void RemoveEstateManager(UUID avatarID)
{
if (l_EstateManagers.Contains(avatarID))
l_EstateManagers.Remove(avatarID);
}
public bool IsEstateManager(UUID avatarID)
{
if (IsEstateOwner(avatarID))
return true;
return l_EstateManagers.Contains(avatarID);
}
public bool IsEstateOwner(UUID avatarID)
{
if (avatarID == m_EstateOwner)
return true;
return false;
}
public bool IsBanned(UUID avatarID)
{
foreach (EstateBan ban in l_EstateBans)
if (ban.BannedUserID == avatarID)
return true;
return false;
}
public void AddBan(EstateBan ban)
{
if (ban == null)
return;
if (!IsBanned(ban.BannedUserID))
l_EstateBans.Add(ban);
}
public void ClearBans()
{
l_EstateBans.Clear();
}
public void RemoveBan(UUID avatarID)
{
foreach (EstateBan ban in new List<EstateBan>(l_EstateBans))
if (ban.BannedUserID == avatarID)
l_EstateBans.Remove(ban);
}
public bool HasAccess(UUID user)
{
if (IsEstateManager(user))
return true;
return l_EstateAccess.Contains(user);
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Iscsi
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
internal enum SessionType
{
[ProtocolKeyValue("Discovery")]
Discovery = 0,
[ProtocolKeyValue("Normal")]
Normal = 1
}
/// <summary>
/// Represents a connection to a particular Target.
/// </summary>
public sealed class Session : IDisposable
{
private static int s_nextInitiatorSessionId = new Random().Next();
private IList<TargetAddress> _addresses;
private string _userName;
private string _password;
private Connection _currentConnection;
private ushort _targetSessionId; // a.k.a. TSIH
private uint _commandSequenceNumber;
private uint _nextInitiaterTaskTag;
private ushort _nextConnectionId;
private uint _initiatorSessionId;
/// <summary>
/// The set of all 'parameters' we've negotiated.
/// </summary>
private Dictionary<string, string> _negotiatedParameters;
internal Session(SessionType type, string targetName, params TargetAddress[] addresses)
: this(type, targetName, null, null, addresses)
{
}
internal Session(SessionType type, string targetName, string userName, string password, IList<TargetAddress> addresses)
{
_initiatorSessionId = (uint)Interlocked.Increment(ref s_nextInitiatorSessionId);
_addresses = addresses;
_userName = userName;
_password = password;
SessionType = type;
TargetName = targetName;
_commandSequenceNumber = 1;
_nextInitiaterTaskTag = 1;
// Default negotiated values...
MaxConnections = 1;
InitialR2T = true;
ImmediateData = true;
MaxBurstLength = 262144;
FirstBurstLength = 65536;
DefaultTime2Wait = 0;
DefaultTime2Retain = 60;
MaxOutstandingR2T = 1;
DataPDUInOrder = true;
DataSequenceInOrder = true;
_negotiatedParameters = new Dictionary<string, string>();
if (string.IsNullOrEmpty(userName))
{
_currentConnection = new Connection(this, _addresses[0], new Authenticator[] { new NullAuthenticator() });
}
else
{
_currentConnection = new Connection(this, _addresses[0], new Authenticator[] { new NullAuthenticator(), new ChapAuthenticator(_userName, _password) });
}
}
#region Protocol Features
/// <summary>
/// Gets the name of the iSCSI target this session is connected to.
/// </summary>
[ProtocolKey("TargetName", null, KeyUsagePhase.SecurityNegotiation, KeySender.Initiator, KeyType.Declarative, UsedForDiscovery = true)]
public string TargetName { get; internal set; }
/// <summary>
/// Gets the name of the iSCSI initiator seen by the target for this session.
/// </summary>
[ProtocolKey("InitiatorName", null, KeyUsagePhase.SecurityNegotiation, KeySender.Initiator, KeyType.Declarative, UsedForDiscovery = true)]
public string InitiatorName
{
get { return "iqn.2008-2010-04.discutils.codeplex.com"; }
}
/// <summary>
/// Gets the friendly name of the iSCSI target this session is connected to.
/// </summary>
[ProtocolKey("TargetAlias", "", KeyUsagePhase.All, KeySender.Target, KeyType.Declarative)]
public string TargetAlias { get; internal set; }
[ProtocolKey("SessionType", null, KeyUsagePhase.SecurityNegotiation, KeySender.Initiator, KeyType.Declarative, UsedForDiscovery = true)]
internal SessionType SessionType { get; set; }
[ProtocolKey("MaxConnections", "1", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int MaxConnections { get; set; }
[ProtocolKey("InitiatorAlias", "", KeyUsagePhase.All, KeySender.Initiator, KeyType.Declarative)]
internal string InitiatorAlias { get; set; }
[ProtocolKey("TargetPortalGroupTag", null, KeyUsagePhase.SecurityNegotiation, KeySender.Target, KeyType.Declarative)]
internal int TargetPortalGroupTag { get; set; }
[ProtocolKey("InitialR2T", "Yes", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal bool InitialR2T { get; set; }
[ProtocolKey("ImmediateData", "Yes", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal bool ImmediateData { get; set; }
[ProtocolKey("MaxBurstLength", "262144", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int MaxBurstLength { get; set; }
[ProtocolKey("FirstBurstLength", "65536", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int FirstBurstLength { get; set; }
[ProtocolKey("DefaultTime2Wait", "2", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int DefaultTime2Wait { get; set; }
[ProtocolKey("DefaultTime2Retain", "20", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int DefaultTime2Retain { get; set; }
[ProtocolKey("MaxOutstandingR2T", "1", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int MaxOutstandingR2T { get; set; }
[ProtocolKey("DataPDUInOrder", "Yes", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal bool DataPDUInOrder { get; set; }
[ProtocolKey("DataSequenceInOrder", "Yes", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal bool DataSequenceInOrder { get; set; }
[ProtocolKey("ErrorRecoveryLevel", "0", KeyUsagePhase.OperationalNegotiation, KeySender.Both, KeyType.Negotiated, LeadingConnectionOnly = true)]
internal int ErrorRecoveryLevel { get; set; }
#endregion
internal Connection ActiveConnection
{
get { return _currentConnection; }
}
internal uint InitiatorSessionId
{
get { return _initiatorSessionId; }
}
internal ushort TargetSessionId
{
get { return _targetSessionId; }
set { _targetSessionId = value; }
}
internal uint CommandSequenceNumber
{
get { return _commandSequenceNumber; }
}
internal uint CurrentTaskTag
{
get { return _nextInitiaterTaskTag; }
}
/// <summary>
/// Disposes of this instance, closing the session with the Target.
/// </summary>
public void Dispose()
{
if (_currentConnection != null)
{
_currentConnection.Close(LogoutReason.CloseSession);
}
_currentConnection = null;
}
/// <summary>
/// Enumerates all of the Targets.
/// </summary>
/// <returns>The list of Targets.</returns>
/// <remarks>In practice, for an established session, this just returns details of
/// the connected Target.</remarks>
public TargetInfo[] EnumerateTargets()
{
return _currentConnection.EnumerateTargets();
}
/// <summary>
/// Gets information about the LUNs available from the Target.
/// </summary>
/// <returns>The LUNs available.</returns>
public LunInfo[] GetLuns()
{
ScsiReportLunsCommand cmd = new ScsiReportLunsCommand(ScsiReportLunsCommand.InitialResponseSize);
ScsiReportLunsResponse resp = Send<ScsiReportLunsResponse>(cmd, null, 0, 0, ScsiReportLunsCommand.InitialResponseSize);
if (resp.Truncated)
{
cmd = new ScsiReportLunsCommand(resp.NeededDataLength);
resp = Send<ScsiReportLunsResponse>(cmd, null, 0, 0, (int)resp.NeededDataLength);
}
if (resp.Truncated)
{
throw new InvalidProtocolException("Truncated response");
}
LunInfo[] result = new LunInfo[resp.Luns.Count];
for (int i = 0; i < resp.Luns.Count; ++i)
{
result[i] = GetInfo((long)resp.Luns[i]);
}
return result;
}
/// <summary>
/// Gets all the block-device LUNs available from the Target.
/// </summary>
/// <returns>The block-device LUNs.</returns>
public long[] GetBlockDeviceLuns()
{
List<long> luns = new List<long>();
foreach (var info in GetLuns())
{
if (info.DeviceType == LunClass.BlockStorage)
{
luns.Add(info.Lun);
}
}
return luns.ToArray();
}
/// <summary>
/// Gets information about a particular LUN.
/// </summary>
/// <param name="lun">The LUN to query.</param>
/// <returns>Information about the LUN.</returns>
public LunInfo GetInfo(long lun)
{
ScsiInquiryCommand cmd = new ScsiInquiryCommand((ulong)lun, ScsiInquiryCommand.InitialResponseDataLength);
ScsiInquiryStandardResponse resp = Send<ScsiInquiryStandardResponse>(cmd, null, 0, 0, ScsiInquiryCommand.InitialResponseDataLength);
TargetInfo targetInfo = new TargetInfo(TargetName, new List<TargetAddress>(_addresses).ToArray());
return new LunInfo(targetInfo, lun, resp.DeviceType, resp.Removable, resp.VendorId, resp.ProductId, resp.ProductRevision);
}
/// <summary>
/// Gets the capacity of a particular LUN.
/// </summary>
/// <param name="lun">The LUN to query.</param>
/// <returns>The LUN's capacity.</returns>
public LunCapacity GetCapacity(long lun)
{
ScsiReadCapacityCommand cmd = new ScsiReadCapacityCommand((ulong)lun);
ScsiReadCapacityResponse resp = Send<ScsiReadCapacityResponse>(cmd, null, 0, 0, ScsiReadCapacityCommand.ResponseDataLength);
if (resp.Truncated)
{
throw new InvalidProtocolException("Truncated response");
}
return new LunCapacity(resp.NumLogicalBlocks, (int)resp.LogicalBlockSize);
}
/// <summary>
/// Provides read-write access to a LUN as a VirtualDisk.
/// </summary>
/// <param name="lun">The LUN to access.</param>
/// <returns>The new VirtualDisk instance.</returns>
public Disk OpenDisk(long lun)
{
return OpenDisk(lun, FileAccess.ReadWrite);
}
/// <summary>
/// Provides access to a LUN as a VirtualDisk.
/// </summary>
/// <param name="lun">The LUN to access.</param>
/// <param name="access">The type of access desired.</param>
/// <returns>The new VirtualDisk instance.</returns>
public Disk OpenDisk(long lun, FileAccess access)
{
return new Disk(this, lun, access);
}
/// <summary>
/// Reads some data from a LUN.
/// </summary>
/// <param name="lun">The LUN to read from.</param>
/// <param name="startBlock">The first block to read.</param>
/// <param name="blockCount">The number of blocks to read.</param>
/// <param name="buffer">The buffer to fill.</param>
/// <param name="offset">The offset of the first byte to fill.</param>
/// <returns>The number of bytes read.</returns>
public int Read(long lun, long startBlock, short blockCount, byte[] buffer, int offset)
{
ScsiReadCommand cmd = new ScsiReadCommand((ulong)lun, (uint)startBlock, (ushort)blockCount);
return Send(cmd, null, 0, 0, buffer, offset, buffer.Length - offset);
}
/// <summary>
/// Writes some data to a LUN.
/// </summary>
/// <param name="lun">The LUN to write to.</param>
/// <param name="startBlock">The first block to write.</param>
/// <param name="blockCount">The number of blocks to write.</param>
/// <param name="blockSize">The size of each block (must match the actual LUN geometry).</param>
/// <param name="buffer">The data to write.</param>
/// <param name="offset">The offset of the first byte to write in buffer.</param>
public void Write(long lun, long startBlock, short blockCount, int blockSize, byte[] buffer, int offset)
{
ScsiWriteCommand cmd = new ScsiWriteCommand((ulong)lun, (uint)startBlock, (ushort)blockCount);
Send(cmd, buffer, offset, blockCount * blockSize, null, 0, 0);
}
/// <summary>
/// Performs a raw SCSI command.
/// </summary>
/// <param name="lun">The target LUN for the command.</param>
/// <param name="command">The command (a SCSI Command Descriptor Block, aka CDB).</param>
/// <param name="outBuffer">Buffer of data to send with the command (or <c>null</c>).</param>
/// <param name="outBufferOffset">Offset of first byte of data to send with the command.</param>
/// <param name="outBufferLength">Amount of data to send with the command.</param>
/// <param name="inBuffer">Buffer to receive data from the command (or <c>null</c>).</param>
/// <param name="inBufferOffset">Offset of the first byte position to fill with received data.</param>
/// <param name="inBufferLength">The expected amount of data to receive.</param>
/// <returns>The number of bytes of data received.</returns>
/// <remarks>
/// <para>This method permits the caller to send raw SCSI commands to a LUN.</para>
/// <para>The command .</para>
/// </remarks>
public int RawCommand(long lun, byte[] command, byte[] outBuffer, int outBufferOffset, int outBufferLength, byte[] inBuffer, int inBufferOffset, int inBufferLength)
{
if (outBuffer == null && outBufferLength != 0)
{
throw new ArgumentException("outBufferLength must be 0 if outBuffer null", "outBufferLength");
}
if (inBuffer == null && inBufferLength != 0)
{
throw new ArgumentException("inBufferLength must be 0 if inBuffer null", "inBufferLength");
}
ScsiRawCommand cmd = new ScsiRawCommand((ulong)lun, command, 0, command.Length);
return Send(cmd, outBuffer, outBufferOffset, outBufferLength, inBuffer, inBufferOffset, inBufferLength);
}
internal uint NextCommandSequenceNumber()
{
return ++_commandSequenceNumber;
}
internal uint NextTaskTag()
{
return ++_nextInitiaterTaskTag;
}
internal ushort NextConnectionId()
{
return ++_nextConnectionId;
}
internal void GetParametersToNegotiate(TextBuffer parameters, KeyUsagePhase phase)
{
PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var propInfo in properties)
{
ProtocolKeyAttribute attr = (ProtocolKeyAttribute)ReflectionHelper.GetCustomAttribute(propInfo, typeof(ProtocolKeyAttribute));
if (attr != null)
{
object value = propInfo.GetGetMethod(true).Invoke(this, null);
if (attr.ShouldTransmit(value, propInfo.PropertyType, phase, SessionType == SessionType.Discovery))
{
parameters.Add(attr.Name, ProtocolKeyAttribute.GetValueAsString(value, propInfo.PropertyType));
_negotiatedParameters.Add(attr.Name, string.Empty);
}
}
}
}
internal void ConsumeParameters(TextBuffer inParameters, TextBuffer outParameters)
{
PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var propInfo in properties)
{
ProtocolKeyAttribute attr = (ProtocolKeyAttribute)ReflectionHelper.GetCustomAttribute(propInfo, typeof(ProtocolKeyAttribute));
if (attr != null)
{
if (inParameters[attr.Name] != null)
{
object value = ProtocolKeyAttribute.GetValueAsObject(inParameters[attr.Name], propInfo.PropertyType);
propInfo.GetSetMethod(true).Invoke(this, new object[] { value });
inParameters.Remove(attr.Name);
if (attr.Type == KeyType.Negotiated && !_negotiatedParameters.ContainsKey(attr.Name))
{
value = propInfo.GetGetMethod(true).Invoke(this, null);
outParameters.Add(attr.Name, ProtocolKeyAttribute.GetValueAsString(value, propInfo.PropertyType));
_negotiatedParameters.Add(attr.Name, string.Empty);
}
}
}
}
}
#region Scsi Bus
/// <summary>
/// Sends an SCSI command (aka task) to a LUN via the connected target.
/// </summary>
/// <param name="cmd">The command to send.</param>
/// <param name="outBuffer">The data to send with the command.</param>
/// <param name="outBufferOffset">The offset of the first byte to send.</param>
/// <param name="outBufferCount">The number of bytes to send, if any.</param>
/// <param name="inBuffer">The buffer to fill with returned data.</param>
/// <param name="inBufferOffset">The first byte to fill with returned data.</param>
/// <param name="inBufferMax">The maximum amount of data to receive.</param>
/// <returns>The number of bytes received.</returns>
private int Send(ScsiCommand cmd, byte[] outBuffer, int outBufferOffset, int outBufferCount, byte[] inBuffer, int inBufferOffset, int inBufferMax)
{
return _currentConnection.Send(cmd, outBuffer, outBufferOffset, outBufferCount, inBuffer, inBufferOffset, inBufferMax);
}
private T Send<T>(ScsiCommand cmd, byte[] buffer, int offset, int count, int expected)
where T : ScsiResponse, new()
{
return _currentConnection.Send<T>(cmd, buffer, offset, count, expected);
}
#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.Tests
{
public abstract class ECKeyFileTests<T> where T : AsymmetricAlgorithm
{
protected abstract T CreateKey();
protected abstract byte[] ExportECPrivateKey(T key);
protected abstract bool TryExportECPrivateKey(T key, Span<byte> destination, out int bytesWritten);
protected abstract void ImportECPrivateKey(T key, ReadOnlySpan<byte> source, out int bytesRead);
protected abstract void ImportParameters(T key, ECParameters ecParameters);
protected abstract ECParameters ExportParameters(T key, bool includePrivate);
public static bool SupportsBrainpool { get; } = IsCurveSupported(ECCurve.NamedCurves.brainpoolP160r1.Oid);
public static bool SupportsSect163k1 { get; } = IsCurveSupported(EccTestData.Sect163k1Key1.Curve.Oid);
public static bool SupportsSect283k1 { get; } = IsCurveSupported(EccTestData.Sect283k1Key1.Curve.Oid);
public static bool SupportsC2pnb163v1 { get; } = IsCurveSupported(EccTestData.C2pnb163v1Key1.Curve.Oid);
// This would need to be virtualized if there was ever a platform that
// allowed explicit in ECDH or ECDSA but not the other.
public static bool SupportsExplicitCurves { get; } = EcDiffieHellman.Tests.ECDiffieHellmanFactory.ExplicitCurvesSupported;
private static bool IsCurveSupported(Oid oid)
{
return EcDiffieHellman.Tests.ECDiffieHellmanFactory.IsCurveValid(oid);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void UseAfterDispose(bool importKey)
{
T key = CreateKey();
if (importKey)
{
ImportParameters(key, EccTestData.GetNistP256ReferenceKey());
}
byte[] ecPrivate;
byte[] pkcs8Private;
byte[] pkcs8EncryptedPrivate;
byte[] subjectPublicKeyInfo;
string pwStr = "Hello";
// Because the PBE algorithm uses PBES2 the string->byte encoding is UTF-8.
byte[] pwBytes = Encoding.UTF8.GetBytes(pwStr);
PbeParameters pbeParameters = new PbeParameters(
PbeEncryptionAlgorithm.Aes192Cbc,
HashAlgorithmName.SHA256,
3072);
// Ensure the key was loaded, then dispose it.
// Also ensures all of the inputs are valid for the disposed tests.
using (key)
{
ecPrivate = ExportECPrivateKey(key);
pkcs8Private = key.ExportPkcs8PrivateKey();
pkcs8EncryptedPrivate = key.ExportEncryptedPkcs8PrivateKey(pwStr, pbeParameters);
subjectPublicKeyInfo = key.ExportSubjectPublicKeyInfo();
}
Assert.Throws<ObjectDisposedException>(() => ImportECPrivateKey(key, ecPrivate, out _));
Assert.Throws<ObjectDisposedException>(() => key.ImportPkcs8PrivateKey(pkcs8Private, out _));
Assert.Throws<ObjectDisposedException>(() => key.ImportEncryptedPkcs8PrivateKey(pwStr, pkcs8EncryptedPrivate, out _));
Assert.Throws<ObjectDisposedException>(() => key.ImportEncryptedPkcs8PrivateKey(pwBytes, pkcs8EncryptedPrivate, out _));
Assert.Throws<ObjectDisposedException>(() => key.ImportSubjectPublicKeyInfo(subjectPublicKeyInfo, out _));
Assert.Throws<ObjectDisposedException>(() => ExportECPrivateKey(key));
Assert.Throws<ObjectDisposedException>(() => TryExportECPrivateKey(key, ecPrivate, out _));
Assert.Throws<ObjectDisposedException>(() => key.ExportPkcs8PrivateKey());
Assert.Throws<ObjectDisposedException>(() => key.TryExportPkcs8PrivateKey(pkcs8Private, out _));
Assert.Throws<ObjectDisposedException>(() => key.ExportEncryptedPkcs8PrivateKey(pwStr, pbeParameters));
Assert.Throws<ObjectDisposedException>(() => key.TryExportEncryptedPkcs8PrivateKey(pwStr, pbeParameters, pkcs8EncryptedPrivate, out _));
Assert.Throws<ObjectDisposedException>(() => key.ExportEncryptedPkcs8PrivateKey(pwBytes, pbeParameters));
Assert.Throws<ObjectDisposedException>(() => key.TryExportEncryptedPkcs8PrivateKey(pwBytes, pbeParameters, pkcs8EncryptedPrivate, out _));
Assert.Throws<ObjectDisposedException>(() => key.ExportSubjectPublicKeyInfo());
Assert.Throws<ObjectDisposedException>(() => key.TryExportSubjectPublicKeyInfo(subjectPublicKeyInfo, out _));
// Check encrypted import with the wrong password.
// It shouldn't do enough work to realize it was wrong.
pwBytes = Array.Empty<byte>();
Assert.Throws<ObjectDisposedException>(() => key.ImportEncryptedPkcs8PrivateKey("", pkcs8EncryptedPrivate, out _));
Assert.Throws<ObjectDisposedException>(() => key.ImportEncryptedPkcs8PrivateKey(pwBytes, pkcs8EncryptedPrivate, out _));
}
[Fact]
public void ReadWriteNistP521Pkcs8()
{
const string base64 = @"
MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIBpV+HhaVzC67h1rPT
AQaff9ZNiwTM6lfv1ZYeaPM/q0NUUWbKZVPNOP9xPRKJxpi9fQhrVeAbW9XtJ+Nj
A3axFmahgYkDgYYABAB1HyYyTHPO9dReuzKTfjBg41GWCldZStA+scoMXqdHEhM2
a6mR0kQGcX+G/e/eCG4JuVSlfcD16UWXVtYMKq5t4AGo3bs/AsjCNSRyn1SLfiMy
UjPvZ90wdSuSTyl0WePC4Sro2PT+RFTjhHwYslXKzvWXN7kY4d5A+V6f/k9Xt5FT
oA==";
ReadWriteBase64Pkcs8(base64, EccTestData.GetNistP521Key2());
}
[Fact]
public void ReadWriteNistP521Pkcs8_ECDH()
{
const string base64 = @"
MIHsAgEAMA4GBSuBBAEMBgUrgQQAIwSB1jCB0wIBAQRCAaVfh4Wlcwuu4daz0wEG
n3/WTYsEzOpX79WWHmjzP6tDVFFmymVTzTj/cT0SicaYvX0Ia1XgG1vV7SfjYwN2
sRZmoYGJA4GGAAQAdR8mMkxzzvXUXrsyk34wYONRlgpXWUrQPrHKDF6nRxITNmup
kdJEBnF/hv3v3ghuCblUpX3A9elFl1bWDCqubeABqN27PwLIwjUkcp9Ui34jMlIz
72fdMHUrkk8pdFnjwuEq6Nj0/kRU44R8GLJVys71lze5GOHeQPlen/5PV7eRU6A=";
ReadWriteBase64Pkcs8(
base64,
EccTestData.GetNistP521Key2(),
isSupported: false);
}
[Fact]
public void ReadWriteNistP521SubjectPublicKeyInfo()
{
const string base64 = @"
MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAdR8mMkxzzvXUXrsyk34wYONRlgpX
WUrQPrHKDF6nRxITNmupkdJEBnF/hv3v3ghuCblUpX3A9elFl1bWDCqubeABqN27
PwLIwjUkcp9Ui34jMlIz72fdMHUrkk8pdFnjwuEq6Nj0/kRU44R8GLJVys71lze5
GOHeQPlen/5PV7eRU6A=";
ReadWriteBase64SubjectPublicKeyInfo(base64, EccTestData.GetNistP521Key2());
}
[Fact]
public void ReadWriteNistP521SubjectPublicKeyInfo_ECDH()
{
const string base64 = @"
MIGZMA4GBSuBBAEMBgUrgQQAIwOBhgAEAHUfJjJMc8711F67MpN+MGDjUZYKV1lK
0D6xygxep0cSEzZrqZHSRAZxf4b9794Ibgm5VKV9wPXpRZdW1gwqrm3gAajduz8C
yMI1JHKfVIt+IzJSM+9n3TB1K5JPKXRZ48LhKujY9P5EVOOEfBiyVcrO9Zc3uRjh
3kD5Xp/+T1e3kVOg";
ReadWriteBase64SubjectPublicKeyInfo(
base64,
EccTestData.GetNistP521Key2(),
isSupported: false);
}
[Fact]
public void ReadNistP521EncryptedPkcs8_Pbes2_Aes128_Sha384()
{
// PBES2, PBKDF2 (SHA384), AES128
const string base64 = @"
MIIBXTBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQI/JyXWyp/t3kCAggA
MAwGCCqGSIb3DQIKBQAwHQYJYIZIAWUDBAECBBA3H8mbFK5afB5GzIemCCQkBIIB
AKAz1z09ATUA8UfoDMwTyXiHUS8Mb/zkUCH+I7rav4orhAnSyYAyLKcHeGne+kUa
8ewQ5S7oMMLXE0HHQ8CpORlSgxTssqTAHigXEqdRb8nQ8hJJa2dFtNXyUeFtxZ7p
x+aSLD6Y3J+mgzeVp1ICgROtuRjA9RYjUdd/3cy2BAlW+Atfs/300Jhkke3H0Gqc
F71o65UNB+verEgN49rQK7FAFtoVI2oRjHLO1cGjxZkbWe2KLtgJWsgmexRq3/a+
Pfuapj3LAHALZtDNMZ+QCFN2ZXUSFNWiBSwnwCAtfFCn/EchPo3MFR3K0q/qXTua
qtlbnispri1a/EghiaPQ0po=";
ReadWriteBase64EncryptedPkcs8(
base64,
"qwerty",
new PbeParameters(
PbeEncryptionAlgorithm.TripleDes3KeyPkcs12,
HashAlgorithmName.SHA1,
12321),
EccTestData.GetNistP521Key2());
}
[Fact]
public void ReadNistP521EncryptedPkcs8_Pbes2_Aes128_Sha384_PasswordBytes()
{
// PBES2, PBKDF2 (SHA384), AES128
const string base64 = @"
MIIBXTBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQI/JyXWyp/t3kCAggA
MAwGCCqGSIb3DQIKBQAwHQYJYIZIAWUDBAECBBA3H8mbFK5afB5GzIemCCQkBIIB
AKAz1z09ATUA8UfoDMwTyXiHUS8Mb/zkUCH+I7rav4orhAnSyYAyLKcHeGne+kUa
8ewQ5S7oMMLXE0HHQ8CpORlSgxTssqTAHigXEqdRb8nQ8hJJa2dFtNXyUeFtxZ7p
x+aSLD6Y3J+mgzeVp1ICgROtuRjA9RYjUdd/3cy2BAlW+Atfs/300Jhkke3H0Gqc
F71o65UNB+verEgN49rQK7FAFtoVI2oRjHLO1cGjxZkbWe2KLtgJWsgmexRq3/a+
Pfuapj3LAHALZtDNMZ+QCFN2ZXUSFNWiBSwnwCAtfFCn/EchPo3MFR3K0q/qXTua
qtlbnispri1a/EghiaPQ0po=";
ReadWriteBase64EncryptedPkcs8(
base64,
Encoding.UTF8.GetBytes("qwerty"),
new PbeParameters(
PbeEncryptionAlgorithm.Aes256Cbc,
HashAlgorithmName.SHA1,
12321),
EccTestData.GetNistP521Key2());
}
[Fact]
public void ReadNistP256EncryptedPkcs8_Pbes1_RC2_MD5()
{
const string base64 = @"
MIGwMBsGCSqGSIb3DQEFBjAOBAiVk8SDhLdiNwICCAAEgZB2rI9tf7jjGdEwJNrS
8F/xNIo/0OSUSkQyg5n/ovRK1IodzPpWqipqM8TGfZk4sxn7h7RBmX2FlMkTLO4i
mVannH3jd9cmCAz0aewDO0/LgmvDnzWiJ/CoDamzwC8bzDocq1Y/PsVYsYzSrJ7n
m8STNpW+zSpHWlpHpWHgXGq4wrUKJifxOv6Rm5KTYcvUT38=";
ReadWriteBase64EncryptedPkcs8(
base64,
"secp256r1",
new PbeParameters(
PbeEncryptionAlgorithm.TripleDes3KeyPkcs12,
HashAlgorithmName.SHA1,
1024),
EccTestData.GetNistP256ReferenceKey());
}
[Fact]
public void ReadWriteNistP256ECPrivateKey()
{
const string base64 = @"
MHcCAQEEIHChLC2xaEXtVv9oz8IaRys/BNfWhRv2NJ8tfVs0UrOKoAoGCCqGSM49
AwEHoUQDQgAEgQHs5HRkpurXDPaabivT2IaRoyYtIsuk92Ner/JmgKjYoSumHVmS
NfZ9nLTVjxeD08pD548KWrqmJAeZNsDDqQ==";
ReadWriteBase64ECPrivateKey(
base64,
EccTestData.GetNistP256ReferenceKey());
}
[Fact]
public void ReadWriteNistP256ExplicitECPrivateKey()
{
ReadWriteBase64ECPrivateKey(
@"
MIIBaAIBAQQgcKEsLbFoRe1W/2jPwhpHKz8E19aFG/Y0ny19WzRSs4qggfowgfcC
AQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAAAAAAAAAAAAAA////////////////
MFsEIP////8AAAABAAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57Pr
vVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEE
axfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54W
K84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8
YyVRAgEBoUQDQgAEgQHs5HRkpurXDPaabivT2IaRoyYtIsuk92Ner/JmgKjYoSum
HVmSNfZ9nLTVjxeD08pD548KWrqmJAeZNsDDqQ==",
EccTestData.GetNistP256ReferenceKeyExplicit(),
SupportsExplicitCurves);
}
[Fact]
public void ReadWriteNistP256ExplicitPkcs8()
{
ReadWriteBase64Pkcs8(
@"
MIIBeQIBADCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAAB
AAAAAAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA
///////////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMV
AMSdNgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg
9KE5RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8A
AAAA//////////+85vqtpxeehPO5ysL8YyVRAgEBBG0wawIBAQQgcKEsLbFoRe1W
/2jPwhpHKz8E19aFG/Y0ny19WzRSs4qhRANCAASBAezkdGSm6tcM9ppuK9PYhpGj
Ji0iy6T3Y16v8maAqNihK6YdWZI19n2ctNWPF4PTykPnjwpauqYkB5k2wMOp",
EccTestData.GetNistP256ReferenceKeyExplicit(),
SupportsExplicitCurves);
}
[Fact]
public void ReadWriteNistP256ExplicitEncryptedPkcs8()
{
ReadWriteBase64EncryptedPkcs8(
@"
MIIBoTAbBgkqhkiG9w0BBQMwDgQIQqYZ3N87K0ICAggABIIBgOHAWa6wz144p0uT
qZsQAbQcIpAFBQRC382dxiOHCV11OyZg264SmxS9iY1OEwIr/peACLu+Fk7zPKhv
Ox1hYz/OeLoKKdtBMqrp65JmH73jG8qeAMuYNj83AIERY7Cckuc2fEC2GTEJcNWs
olE+0p4H6yIvXI48NEQazj5w9zfOGvLmP6Kw6nX+SV3fzM9jHskU226LnDdokGVg
an6/hV1r+2+n2MujhfNzQd/5vW5zx7PN/1aMVMz3wUv9t8scDppeMR5CNCMkxlRA
cQ2lfx2vqFuY70EckgumDqm7AtKK2bLlA6XGTb8HuqKHA0l1zrul9AOBC1g33isD
5CJu1CCT34adV4E4G44uiRQUtf+K8m5Oeo8FI/gGBxdQyOh1k8TNsM+p32gTU8HH
89M5R+s1ayQI7jVPGHXm8Ch7lxvqo6FZAu6+vh23vTwVShUTpGYd0XguE6XKJjGx
eWDIWFuFRj58uAQ65/viFausHWt1BdywcwcyVRb2eLI5MR7DWA==",
"explicit",
new PbeParameters(
PbeEncryptionAlgorithm.Aes128Cbc,
HashAlgorithmName.SHA256,
1234),
EccTestData.GetNistP256ReferenceKeyExplicit(),
SupportsExplicitCurves);
}
[Fact]
public void ReadWriteNistP256ExplicitSubjectPublicKeyInfo()
{
ReadWriteBase64SubjectPublicKeyInfo(
@"
MIIBSzCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAA
AAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA////
///////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSd
NgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5
RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA
//////////+85vqtpxeehPO5ysL8YyVRAgEBA0IABIEB7OR0ZKbq1wz2mm4r09iG
kaMmLSLLpPdjXq/yZoCo2KErph1ZkjX2fZy01Y8Xg9PKQ+ePClq6piQHmTbAw6k=",
EccTestData.GetNistP256ReferenceKeyExplicit(),
SupportsExplicitCurves);
}
[Fact]
public void ReadWriteBrainpoolKey1ECPrivateKey()
{
ReadWriteBase64ECPrivateKey(
@"
MFQCAQEEFMXZRFR94RXbJYjcb966O0c+nE2WoAsGCSskAwMCCAEBAaEsAyoABI5i
jwk5x2KSdsrb/pnAHDZQk1TictLI7vH2zDIF0AV+ud5sqeMQUJY=",
EccTestData.BrainpoolP160r1Key1,
SupportsBrainpool);
}
[Fact]
public void ReadWriteBrainpoolKey1Pkcs8()
{
ReadWriteBase64Pkcs8(
@"
MGQCAQAwFAYHKoZIzj0CAQYJKyQDAwIIAQEBBEkwRwIBAQQUxdlEVH3hFdsliNxv
3ro7Rz6cTZahLAMqAASOYo8JOcdiknbK2/6ZwBw2UJNU4nLSyO7x9swyBdAFfrne
bKnjEFCW",
EccTestData.BrainpoolP160r1Key1,
SupportsBrainpool);
}
[Fact]
public void ReadWriteBrainpoolKey1EncryptedPkcs8()
{
ReadWriteBase64EncryptedPkcs8(
@"
MIGHMBsGCSqGSIb3DQEFAzAOBAhSgCZvbsatLQICCAAEaKGDyoSVej1yNPCn7K6q
ooI857+joe6NZjR+w1xuH4JfrQZGvelWZ2AWtQezuz4UzPLnL3Nyf6jjPPuKarpk
HiDaMtpw7yT5+32Vkxv5C2jvqNPpicmEFpf2wJ8yVLQtMOKAF2sOwxN/",
"12345",
new PbeParameters(
PbeEncryptionAlgorithm.Aes192Cbc,
HashAlgorithmName.SHA384,
4096),
EccTestData.BrainpoolP160r1Key1,
SupportsBrainpool);
}
[Fact]
public void ReadWriteBrainpoolKey1SubjectPublicKeyInfo()
{
ReadWriteBase64SubjectPublicKeyInfo(
@"
MEIwFAYHKoZIzj0CAQYJKyQDAwIIAQEBAyoABI5ijwk5x2KSdsrb/pnAHDZQk1Ti
ctLI7vH2zDIF0AV+ud5sqeMQUJY=",
EccTestData.BrainpoolP160r1Key1,
SupportsBrainpool);
}
[Fact]
public void ReadWriteSect163k1Key1ECPrivateKey()
{
ReadWriteBase64ECPrivateKey(
@"
MFMCAQEEFQPBmVrfrowFGNwT3+YwS7AQF+akEqAHBgUrgQQAAaEuAywABAYXnjcZ
zIElQ1/mRYnV/KbcGIdVHQeI/rti/8kkjYs5iv4+C1w8ArP+Nw==",
EccTestData.Sect163k1Key1,
SupportsSect163k1);
}
[Fact]
public void ReadWriteSect163k1Key1Pkcs8()
{
ReadWriteBase64Pkcs8(
@"
MGMCAQAwEAYHKoZIzj0CAQYFK4EEAAEETDBKAgEBBBUDwZla366MBRjcE9/mMEuw
EBfmpBKhLgMsAAQGF543GcyBJUNf5kWJ1fym3BiHVR0HiP67Yv/JJI2LOYr+Pgtc
PAKz/jc=",
EccTestData.Sect163k1Key1,
SupportsSect163k1);
}
[Fact]
public void ReadWriteSect163k1Key1EncryptedPkcs8()
{
ReadWriteBase64EncryptedPkcs8(
@"
MIGHMBsGCSqGSIb3DQEFAzAOBAjLBuCZyPt15QICCAAEaPa9V9VJoB8G+RIgZaYv
z4xl+rpvkDrDI0Xnh8oj1CLQldy2N77pdk3pOg9TwJo+r+eKfIJgBVezW2O615ww
f+ESRyxDnBgKz6H2RKeenyrwVhxF98SyJzAdP637vR3QmDNAWWAgoUhg",
"Koblitz",
new PbeParameters(
PbeEncryptionAlgorithm.Aes256Cbc,
HashAlgorithmName.SHA256,
7),
EccTestData.Sect163k1Key1,
SupportsSect163k1);
}
[Fact]
public void ReadWriteSect163k1Key1SubjectPublicKeyInfo()
{
ReadWriteBase64SubjectPublicKeyInfo(
@"
MEAwEAYHKoZIzj0CAQYFK4EEAAEDLAAEBheeNxnMgSVDX+ZFidX8ptwYh1UdB4j+
u2L/ySSNizmK/j4LXDwCs/43",
EccTestData.Sect163k1Key1,
SupportsSect163k1);
}
[Fact]
public void ReadWriteSect163k1Key1ExplicitECPrivateKey()
{
ReadWriteBase64ECPrivateKey(
@"
MIHHAgEBBBUDwZla366MBRjcE9/mMEuwEBfmpBKgezB5AgEBMCUGByqGSM49AQIw
GgICAKMGCSqGSM49AQIDAzAJAgEDAgEGAgEHMAYEAQEEAQEEKwQC/hPAU3u8Eayq
B9eT3k5tXlyU7ugCiQcPsF04/1gyHy6ABTbVOMzao9kCFQQAAAAAAAAAAAACAQii
4MwNmfil7wIBAqEuAywABAYXnjcZzIElQ1/mRYnV/KbcGIdVHQeI/rti/8kkjYs5
iv4+C1w8ArP+Nw==",
EccTestData.Sect163k1Key1Explicit,
SupportsSect163k1);
}
[Fact]
public void ReadWriteSect163k1Key1ExplicitPkcs8()
{
ReadWriteBase64Pkcs8(
@"
MIHYAgEAMIGEBgcqhkjOPQIBMHkCAQEwJQYHKoZIzj0BAjAaAgIAowYJKoZIzj0B
AgMDMAkCAQMCAQYCAQcwBgQBAQQBAQQrBAL+E8BTe7wRrKoH15PeTm1eXJTu6AKJ
Bw+wXTj/WDIfLoAFNtU4zNqj2QIVBAAAAAAAAAAAAAIBCKLgzA2Z+KXvAgECBEww
SgIBAQQVA8GZWt+ujAUY3BPf5jBLsBAX5qQSoS4DLAAEBheeNxnMgSVDX+ZFidX8
ptwYh1UdB4j+u2L/ySSNizmK/j4LXDwCs/43",
EccTestData.Sect163k1Key1Explicit,
SupportsSect163k1);
}
[Fact]
public void ReadWriteSect163k1Key1ExplicitEncryptedPkcs8()
{
ReadWriteBase64EncryptedPkcs8(
@"
MIIBADAbBgkqhkiG9w0BBQMwDgQICAkWq2tKYZUCAggABIHgjBfngwE9DbCEaznz
+55MjSGbQH0NMgIRCJtQLbrI7888+KmTL6hWYPH6CQzTsi1unWrMAH2JKa7dkIe9
FWNXW7bmhcokVDh/OTXOV9QPZ3O4m19a9XOl0wNlbi47XQ3KUkcbzyFNYlDMSzFw
HRfW8+aIkyYAvYCoA4buRfigBe0xy1VKyE5aUkX0EFjx4gqC3Q5mjDMFOxlKNjVV
clSZg6tg9J7bTQsDAN0uYpBc1r8DiSQbKMxg+q13yBciXJzfmkQRtNVXQPsseiUm
z2NFvWcpK0Fh9fCVGuXV9sjJ5qE=",
"Koblitz",
new PbeParameters(
PbeEncryptionAlgorithm.Aes128Cbc,
HashAlgorithmName.SHA256,
12),
EccTestData.Sect163k1Key1Explicit,
SupportsSect163k1);
}
[Fact]
public void ReadWriteSect163k1Key1ExplicitSubjectPublicKeyInfo()
{
ReadWriteBase64SubjectPublicKeyInfo(
@"
MIG1MIGEBgcqhkjOPQIBMHkCAQEwJQYHKoZIzj0BAjAaAgIAowYJKoZIzj0BAgMD
MAkCAQMCAQYCAQcwBgQBAQQBAQQrBAL+E8BTe7wRrKoH15PeTm1eXJTu6AKJBw+w
XTj/WDIfLoAFNtU4zNqj2QIVBAAAAAAAAAAAAAIBCKLgzA2Z+KXvAgECAywABAYX
njcZzIElQ1/mRYnV/KbcGIdVHQeI/rti/8kkjYs5iv4+C1w8ArP+Nw==",
EccTestData.Sect163k1Key1Explicit,
SupportsSect163k1);
}
[Fact]
public void ReadWriteSect283k1Key1ECPrivateKey()
{
ReadWriteBase64ECPrivateKey(
@"
MIGAAgEBBCQAtPGuHn/c1LDoIFPAipCIUrJiMebAFnD8xsPqLF0/7UDt8DegBwYF
K4EEABChTANKAAQHUncL0z5qbuIJbLaxIOdJe0e2wHehR8tX2vaTkJ2EBxbup6oE
fbmZXDVgPF5rL4zf8Otx03rjQxughJ66sTpMkAPHlp9VzZA=",
EccTestData.Sect283k1Key1,
SupportsSect283k1);
}
[Fact]
public void ReadWriteSect283k1Key1Pkcs8()
{
ReadWriteBase64Pkcs8(
@"
MIGQAgEAMBAGByqGSM49AgEGBSuBBAAQBHkwdwIBAQQkALTxrh5/3NSw6CBTwIqQ
iFKyYjHmwBZw/MbD6ixdP+1A7fA3oUwDSgAEB1J3C9M+am7iCWy2sSDnSXtHtsB3
oUfLV9r2k5CdhAcW7qeqBH25mVw1YDxeay+M3/DrcdN640MboISeurE6TJADx5af
Vc2Q",
EccTestData.Sect283k1Key1,
SupportsSect283k1);
}
[Fact]
public void ReadWriteSect283k1Key1EncryptedPkcs8()
{
ReadWriteBase64EncryptedPkcs8(
@"
MIG4MBsGCSqGSIb3DQEFAzAOBAhf/Ix8WHVvxQICCAAEgZheT2iB2sBmNjV2qIgI
DsNyPY+0rwbWR8MHZcRN0zAL9Q3kawaZyWeKe4j3m3Y39YWURVymYeLAm70syrEw
057W6kNVXxR/hEq4MlHJZxZdS+R6LGpEvWFEWiuN0wBtmhO24+KmqPMH8XhGszBv
nTvuaAMG/xvXzKoigakX+1D60cmftPsC7t23SF+xMdzfZNlJGrxXFYX1Gg==",
"12345",
new PbeParameters(
PbeEncryptionAlgorithm.Aes192Cbc,
HashAlgorithmName.SHA384,
4096),
EccTestData.Sect283k1Key1,
SupportsSect283k1);
}
[Fact]
public void ReadWriteSect283k1Key1SubjectPublicKeyInfo()
{
ReadWriteBase64SubjectPublicKeyInfo(
@"
MF4wEAYHKoZIzj0CAQYFK4EEABADSgAEB1J3C9M+am7iCWy2sSDnSXtHtsB3oUfL
V9r2k5CdhAcW7qeqBH25mVw1YDxeay+M3/DrcdN640MboISeurE6TJADx5afVc2Q",
EccTestData.Sect283k1Key1,
SupportsSect283k1);
}
[Fact]
public void ReadWriteC2pnb163v1ECPrivateKey()
{
ReadWriteBase64ECPrivateKey(
@"
MFYCAQEEFQD00koUBxIvRFlnvh2TwAk6ZTZ5hqAKBggqhkjOPQMAAaEuAywABAIR
Jy8cVYJCaIjpG9aSV3SUIyJIqgQnCDD3oQCa1nCojekr1ZJIzIE7RQ==",
EccTestData.C2pnb163v1Key1,
SupportsC2pnb163v1);
}
[Fact]
public void ReadWriteC2pnb163v1Pkcs8()
{
ReadWriteBase64Pkcs8(
@"
MGYCAQAwEwYHKoZIzj0CAQYIKoZIzj0DAAEETDBKAgEBBBUA9NJKFAcSL0RZZ74d
k8AJOmU2eYahLgMsAAQCEScvHFWCQmiI6RvWkld0lCMiSKoEJwgw96EAmtZwqI3p
K9WSSMyBO0U=",
EccTestData.C2pnb163v1Key1,
SupportsC2pnb163v1);
}
[Fact]
public void ReadWriteC2pnb163v1EncryptedPkcs8()
{
ReadWriteBase64EncryptedPkcs8(
@"
MIGPMBsGCSqGSIb3DQEFAzAOBAjdV9IDq+L+5gICCAAEcI1e6RA8kMcYB+PvOcCU
Jj65nXTIrMPmZ0DmFMF9WBg0J+yzxgDhBVynpT2uJntY4FuDlvdpcLRK1EGLZYKf
qYc5zJMYkRZ178bE3DtfrP3UxD34YvbRl2aeu334+wJOm7ApXv81ugt4OoCiPhdg
wiA=",
"secret",
new PbeParameters(
PbeEncryptionAlgorithm.Aes192Cbc,
HashAlgorithmName.SHA512,
1024),
EccTestData.C2pnb163v1Key1,
SupportsC2pnb163v1);
}
[Fact]
public void ReadWriteC2pnb163v1SubjectPublicKeyInfo()
{
ReadWriteBase64SubjectPublicKeyInfo(
@"
MEMwEwYHKoZIzj0CAQYIKoZIzj0DAAEDLAAEAhEnLxxVgkJoiOkb1pJXdJQjIkiq
BCcIMPehAJrWcKiN6SvVkkjMgTtF",
EccTestData.C2pnb163v1Key1,
SupportsC2pnb163v1);
}
[Fact]
public void ReadWriteC2pnb163v1ExplicitECPrivateKey()
{
ReadWriteBase64ECPrivateKey(
@"
MIIBBwIBAQQVAPTSShQHEi9EWWe+HZPACTplNnmGoIG6MIG3AgEBMCUGByqGSM49
AQIwGgICAKMGCSqGSM49AQIDAzAJAgEBAgECAgEIMEQEFQclRrVDUjSkIuB4lnX0
MsiUNd5SQgQUyVF9BtUkDTz/OMdLILbNTW+d1NkDFQDSwPsVdghg3vHu9NaW5naH
VhUXVAQrBAevaZiVRhA9eTKfzD10iA8zu+gDywHsIyEbWWat6h0/h/fqWEiu8LfK
nwIVBAAAAAAAAAAAAAHmD8iCHMdNrq/BAgECoS4DLAAEAhEnLxxVgkJoiOkb1pJX
dJQjIkiqBCcIMPehAJrWcKiN6SvVkkjMgTtF",
EccTestData.C2pnb163v1Key1Explicit,
SupportsC2pnb163v1);
}
[Fact]
public void ReadWriteC2pnb163v1ExplicitPkcs8()
{
ReadWriteBase64Pkcs8(
@"
MIIBFwIBADCBwwYHKoZIzj0CATCBtwIBATAlBgcqhkjOPQECMBoCAgCjBgkqhkjO
PQECAwMwCQIBAQIBAgIBCDBEBBUHJUa1Q1I0pCLgeJZ19DLIlDXeUkIEFMlRfQbV
JA08/zjHSyC2zU1vndTZAxUA0sD7FXYIYN7x7vTWluZ2h1YVF1QEKwQHr2mYlUYQ
PXkyn8w9dIgPM7voA8sB7CMhG1lmreodP4f36lhIrvC3yp8CFQQAAAAAAAAAAAAB
5g/IghzHTa6vwQIBAgRMMEoCAQEEFQD00koUBxIvRFlnvh2TwAk6ZTZ5hqEuAywA
BAIRJy8cVYJCaIjpG9aSV3SUIyJIqgQnCDD3oQCa1nCojekr1ZJIzIE7RQ==",
EccTestData.C2pnb163v1Key1Explicit,
SupportsC2pnb163v1);
}
[Fact]
public void ReadWriteC2pnb163v1ExplicitEncryptedPkcs8()
{
ReadWriteBase64EncryptedPkcs8(
@"
MIIBQTAbBgkqhkiG9w0BBQMwDgQI9+ZZnHaqxb0CAggABIIBIM+n6x/Q1hs5OW0F
oOKZmQ0mKNRKb23SMqwo0bJlxseIOVdYzOV2LH1hSWeJb7FMxo6OJXb2CpYSPqv1
v3lhdLC5t/ViqAOhG70KF+Dy/vZr8rWXRFqy+OdqwxOes/lBsG+Ws9+uEk8+Gm2G
xMHXJNKliSUePlT3wC7z8bCkEvLF7hkGjEAgcABry5Ohq3W2by6Dnd8YWJNgeiW/
Vu5rT1ThAus7w2TJjWrrEqBbIlQ9nm6/MMj9nYnVVfpPAOk/qX9Or7TmK+Sei88Q
staXBhfJk9ec8laiPpNbhHJSZ2Ph3Snb6SA7MYi5nIMP4RPxOM2eUet4/ueV1O3U
wxcZ+wOsnebIwy4ftKL+klh5EXv/9S5sCjC8g8J2cA6GmcZbiQ==",
"secret",
new PbeParameters(
PbeEncryptionAlgorithm.Aes192Cbc,
HashAlgorithmName.SHA512,
1024),
EccTestData.C2pnb163v1Key1Explicit,
SupportsC2pnb163v1);
}
[Fact]
public void ReadWriteC2pnb163v1ExplicitSubjectPublicKeyInfo()
{
ReadWriteBase64SubjectPublicKeyInfo(
@"
MIH0MIHDBgcqhkjOPQIBMIG3AgEBMCUGByqGSM49AQIwGgICAKMGCSqGSM49AQID
AzAJAgEBAgECAgEIMEQEFQclRrVDUjSkIuB4lnX0MsiUNd5SQgQUyVF9BtUkDTz/
OMdLILbNTW+d1NkDFQDSwPsVdghg3vHu9NaW5naHVhUXVAQrBAevaZiVRhA9eTKf
zD10iA8zu+gDywHsIyEbWWat6h0/h/fqWEiu8LfKnwIVBAAAAAAAAAAAAAHmD8iC
HMdNrq/BAgECAywABAIRJy8cVYJCaIjpG9aSV3SUIyJIqgQnCDD3oQCa1nCojekr
1ZJIzIE7RQ==",
EccTestData.C2pnb163v1Key1Explicit,
SupportsC2pnb163v1);
}
[Fact]
public void NoFuzzySubjectPublicKeyInfo()
{
using (T key = CreateKey())
{
int bytesRead = -1;
byte[] ecPriv = ExportECPrivateKey(key);
Assert.ThrowsAny<CryptographicException>(
() => key.ImportSubjectPublicKeyInfo(ecPriv, out bytesRead));
Assert.Equal(-1, bytesRead);
byte[] pkcs8 = key.ExportPkcs8PrivateKey();
Assert.ThrowsAny<CryptographicException>(
() => key.ImportSubjectPublicKeyInfo(pkcs8, out bytesRead));
Assert.Equal(-1, bytesRead);
ReadOnlySpan<byte> passwordBytes = ecPriv.AsSpan(0, 15);
byte[] encryptedPkcs8 = key.ExportEncryptedPkcs8PrivateKey(
passwordBytes,
new PbeParameters(
PbeEncryptionAlgorithm.Aes256Cbc,
HashAlgorithmName.SHA512,
123));
Assert.ThrowsAny<CryptographicException>(
() => key.ImportSubjectPublicKeyInfo(encryptedPkcs8, out bytesRead));
Assert.Equal(-1, bytesRead);
}
}
[Fact]
public void NoFuzzyECPrivateKey()
{
using (T key = CreateKey())
{
int bytesRead = -1;
byte[] spki = key.ExportSubjectPublicKeyInfo();
Assert.ThrowsAny<CryptographicException>(
() => ImportECPrivateKey(key, spki, out bytesRead));
Assert.Equal(-1, bytesRead);
byte[] pkcs8 = key.ExportPkcs8PrivateKey();
Assert.ThrowsAny<CryptographicException>(
() => ImportECPrivateKey(key, pkcs8, out bytesRead));
Assert.Equal(-1, bytesRead);
ReadOnlySpan<byte> passwordBytes = spki.AsSpan(0, 15);
byte[] encryptedPkcs8 = key.ExportEncryptedPkcs8PrivateKey(
passwordBytes,
new PbeParameters(
PbeEncryptionAlgorithm.Aes256Cbc,
HashAlgorithmName.SHA512,
123));
Assert.ThrowsAny<CryptographicException>(
() => ImportECPrivateKey(key, encryptedPkcs8, out bytesRead));
Assert.Equal(-1, bytesRead);
}
}
[Fact]
public void NoFuzzyPkcs8()
{
using (T key = CreateKey())
{
int bytesRead = -1;
byte[] spki = key.ExportSubjectPublicKeyInfo();
Assert.ThrowsAny<CryptographicException>(
() => key.ImportPkcs8PrivateKey(spki, out bytesRead));
Assert.Equal(-1, bytesRead);
byte[] ecPriv = ExportECPrivateKey(key);
Assert.ThrowsAny<CryptographicException>(
() => key.ImportPkcs8PrivateKey(ecPriv, out bytesRead));
Assert.Equal(-1, bytesRead);
ReadOnlySpan<byte> passwordBytes = spki.AsSpan(0, 15);
byte[] encryptedPkcs8 = key.ExportEncryptedPkcs8PrivateKey(
passwordBytes,
new PbeParameters(
PbeEncryptionAlgorithm.Aes256Cbc,
HashAlgorithmName.SHA512,
123));
Assert.ThrowsAny<CryptographicException>(
() => key.ImportPkcs8PrivateKey(encryptedPkcs8, out bytesRead));
Assert.Equal(-1, bytesRead);
}
}
[Fact]
public void NoFuzzyEncryptedPkcs8()
{
using (T key = CreateKey())
{
int bytesRead = -1;
byte[] spki = key.ExportSubjectPublicKeyInfo();
byte[] empty = Array.Empty<byte>();
Assert.ThrowsAny<CryptographicException>(
() => key.ImportEncryptedPkcs8PrivateKey(empty, spki, out bytesRead));
Assert.Equal(-1, bytesRead);
byte[] ecPriv = ExportECPrivateKey(key);
Assert.ThrowsAny<CryptographicException>(
() => key.ImportEncryptedPkcs8PrivateKey(empty, ecPriv, out bytesRead));
Assert.Equal(-1, bytesRead);
byte[] pkcs8 = key.ExportPkcs8PrivateKey();
Assert.ThrowsAny<CryptographicException>(
() => key.ImportEncryptedPkcs8PrivateKey(empty, pkcs8, out bytesRead));
Assert.Equal(-1, bytesRead);
}
}
[Fact]
public void NoPrivKeyFromPublicOnly()
{
using (T key = CreateKey())
{
ECParameters parameters = EccTestData.GetNistP521Key2();
parameters.D = null;
ImportParameters(key, parameters);
Assert.ThrowsAny<CryptographicException>(
() => ExportECPrivateKey(key));
Assert.ThrowsAny<CryptographicException>(
() => TryExportECPrivateKey(key, Span<byte>.Empty, out _));
Assert.ThrowsAny<CryptographicException>(
() => key.ExportPkcs8PrivateKey());
Assert.ThrowsAny<CryptographicException>(
() => key.TryExportPkcs8PrivateKey(Span<byte>.Empty, out _));
Assert.ThrowsAny<CryptographicException>(
() => key.ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte>.Empty,
new PbeParameters(PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, 72)));
Assert.ThrowsAny<CryptographicException>(
() => key.TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte>.Empty,
new PbeParameters(PbeEncryptionAlgorithm.Aes192Cbc, HashAlgorithmName.SHA256, 72),
Span<byte>.Empty,
out _));
}
}
[Fact]
public void BadPbeParameters()
{
using (T key = CreateKey())
{
Assert.ThrowsAny<ArgumentNullException>(
() => key.ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte>.Empty,
null));
Assert.ThrowsAny<ArgumentNullException>(
() => key.ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char>.Empty,
null));
Assert.ThrowsAny<ArgumentNullException>(
() => key.TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte>.Empty,
null,
Span<byte>.Empty,
out _));
Assert.ThrowsAny<ArgumentNullException>(
() => key.TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char>.Empty,
null,
Span<byte>.Empty,
out _));
// PKCS12 requires SHA-1
Assert.ThrowsAny<CryptographicException>(
() => key.ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte>.Empty,
new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA256, 72)));
Assert.ThrowsAny<CryptographicException>(
() => key.TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte>.Empty,
new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA256, 72),
Span<byte>.Empty,
out _));
// PKCS12 requires SHA-1
Assert.ThrowsAny<CryptographicException>(
() => key.ExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte>.Empty,
new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.MD5, 72)));
Assert.ThrowsAny<CryptographicException>(
() => key.TryExportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte>.Empty,
new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.MD5, 72),
Span<byte>.Empty,
out _));
// PKCS12 requires a char-based password
Assert.ThrowsAny<CryptographicException>(
() => key.ExportEncryptedPkcs8PrivateKey(
new byte[3],
new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 72)));
Assert.ThrowsAny<CryptographicException>(
() => key.TryExportEncryptedPkcs8PrivateKey(
new byte[3],
new PbeParameters(PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, HashAlgorithmName.SHA1, 72),
Span<byte>.Empty,
out _));
// Unknown encryption algorithm
Assert.ThrowsAny<CryptographicException>(
() => key.ExportEncryptedPkcs8PrivateKey(
new byte[3],
new PbeParameters(0, HashAlgorithmName.SHA1, 72)));
Assert.ThrowsAny<CryptographicException>(
() => key.TryExportEncryptedPkcs8PrivateKey(
new byte[3],
new PbeParameters(0, HashAlgorithmName.SHA1, 72),
Span<byte>.Empty,
out _));
// Unknown encryption algorithm (negative enum value)
Assert.ThrowsAny<CryptographicException>(
() => key.ExportEncryptedPkcs8PrivateKey(
new byte[3],
new PbeParameters((PbeEncryptionAlgorithm)(-5), HashAlgorithmName.SHA1, 72)));
Assert.ThrowsAny<CryptographicException>(
() => key.TryExportEncryptedPkcs8PrivateKey(
new byte[3],
new PbeParameters((PbeEncryptionAlgorithm)(-5), HashAlgorithmName.SHA1, 72),
Span<byte>.Empty,
out _));
// Unknown encryption algorithm (overly-large enum value)
Assert.ThrowsAny<CryptographicException>(
() => key.ExportEncryptedPkcs8PrivateKey(
new byte[3],
new PbeParameters((PbeEncryptionAlgorithm)15, HashAlgorithmName.SHA1, 72)));
Assert.ThrowsAny<CryptographicException>(
() => key.TryExportEncryptedPkcs8PrivateKey(
new byte[3],
new PbeParameters((PbeEncryptionAlgorithm)15, HashAlgorithmName.SHA1, 72),
Span<byte>.Empty,
out _));
// Unknown hash algorithm
Assert.ThrowsAny<CryptographicException>(
() => key.ExportEncryptedPkcs8PrivateKey(
new byte[3],
new PbeParameters(PbeEncryptionAlgorithm.Aes192Cbc, new HashAlgorithmName("Potato"), 72)));
Assert.ThrowsAny<CryptographicException>(
() => key.TryExportEncryptedPkcs8PrivateKey(
new byte[3],
new PbeParameters(PbeEncryptionAlgorithm.Aes192Cbc, new HashAlgorithmName("Potato"), 72),
Span<byte>.Empty,
out _));
}
}
[Fact]
public void DecryptPkcs12WithBytes()
{
using (T key = CreateKey())
{
string charBased = "hello";
byte[] byteBased = Encoding.UTF8.GetBytes(charBased);
byte[] encrypted = key.ExportEncryptedPkcs8PrivateKey(
charBased,
new PbeParameters(
PbeEncryptionAlgorithm.TripleDes3KeyPkcs12,
HashAlgorithmName.SHA1,
123));
Assert.ThrowsAny<CryptographicException>(
() => key.ImportEncryptedPkcs8PrivateKey(byteBased, encrypted, out _));
}
}
private void ReadWriteBase64EncryptedPkcs8(
string base64EncryptedPkcs8,
string password,
PbeParameters pbe,
in ECParameters expected,
bool isSupported=true)
{
if (isSupported)
{
ReadWriteKey(
base64EncryptedPkcs8,
expected,
(T key, ReadOnlySpan<byte> source, out int read) =>
key.ImportEncryptedPkcs8PrivateKey(password, source, out read),
key => key.ExportEncryptedPkcs8PrivateKey(password, pbe),
(T key, Span<byte> destination, out int bytesWritten) =>
key.TryExportEncryptedPkcs8PrivateKey(password, pbe, destination, out bytesWritten),
isEncrypted: true);
}
else
{
byte[] encrypted = Convert.FromBase64String(base64EncryptedPkcs8);
using (T key = CreateKey())
{
// Wrong password
Assert.ThrowsAny<CryptographicException>(
() => key.ImportEncryptedPkcs8PrivateKey(encrypted.AsSpan(1, 14), encrypted, out _));
Assert.ThrowsAny<CryptographicException>(
() => key.ImportEncryptedPkcs8PrivateKey(password + password, encrypted, out _));
int bytesRead = -1;
Exception e = Assert.ThrowsAny<Exception>(
() => key.ImportEncryptedPkcs8PrivateKey(password, encrypted, out bytesRead));
Assert.True(
e is PlatformNotSupportedException || e is CryptographicException,
"e is PlatformNotSupportedException || e is CryptographicException");
Assert.Equal(-1, bytesRead);
}
}
}
private void ReadWriteBase64EncryptedPkcs8(
string base64EncryptedPkcs8,
byte[] passwordBytes,
PbeParameters pbe,
in ECParameters expected,
bool isSupported=true)
{
if (isSupported)
{
ReadWriteKey(
base64EncryptedPkcs8,
expected,
(T key, ReadOnlySpan<byte> source, out int read) =>
key.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out read),
key => key.ExportEncryptedPkcs8PrivateKey(passwordBytes, pbe),
(T key, Span<byte> destination, out int bytesWritten) =>
key.TryExportEncryptedPkcs8PrivateKey(passwordBytes, pbe, destination, out bytesWritten),
isEncrypted: true);
}
else
{
byte[] encrypted = Convert.FromBase64String(base64EncryptedPkcs8);
byte[] wrongPassword = new byte[passwordBytes.Length + 2];
RandomNumberGenerator.Fill(wrongPassword);
using (T key = CreateKey())
{
// Wrong password
Assert.ThrowsAny<CryptographicException>(
() => key.ImportEncryptedPkcs8PrivateKey(wrongPassword, encrypted, out _));
Assert.ThrowsAny<CryptographicException>(
() => key.ImportEncryptedPkcs8PrivateKey("ThisBetterNotBeThePassword!", encrypted, out _));
int bytesRead = -1;
Exception e = Assert.ThrowsAny<Exception>(
() => key.ImportEncryptedPkcs8PrivateKey(passwordBytes, encrypted, out bytesRead));
Assert.True(
e is PlatformNotSupportedException || e is CryptographicException,
"e is PlatformNotSupportedException || e is CryptographicException");
Assert.Equal(-1, bytesRead);
}
}
}
private void ReadWriteBase64ECPrivateKey(string base64Pkcs8, in ECParameters expected, bool isSupported=true)
{
if (isSupported)
{
ReadWriteKey(
base64Pkcs8,
expected,
(T key, ReadOnlySpan<byte> source, out int read) =>
ImportECPrivateKey(key, source, out read),
key => ExportECPrivateKey(key),
(T key, Span<byte> destination, out int bytesWritten) =>
TryExportECPrivateKey(key, destination, out bytesWritten));
}
else
{
using (T key = CreateKey())
{
Exception e = Assert.ThrowsAny<Exception>(
() => ImportECPrivateKey(key, Convert.FromBase64String(base64Pkcs8), out _));
Assert.True(
e is PlatformNotSupportedException || e is CryptographicException,
"e is PlatformNotSupportedException || e is CryptographicException");
}
}
}
private void ReadWriteBase64Pkcs8(string base64Pkcs8, in ECParameters expected, bool isSupported=true)
{
if (isSupported)
{
ReadWriteKey(
base64Pkcs8,
expected,
(T key, ReadOnlySpan<byte> source, out int read) =>
key.ImportPkcs8PrivateKey(source, out read),
key => key.ExportPkcs8PrivateKey(),
(T key, Span<byte> destination, out int bytesWritten) =>
key.TryExportPkcs8PrivateKey(destination, out bytesWritten));
}
else
{
using (T key = CreateKey())
{
Exception e = Assert.ThrowsAny<Exception>(
() => key.ImportPkcs8PrivateKey(Convert.FromBase64String(base64Pkcs8), out _));
Assert.True(
e is PlatformNotSupportedException || e is CryptographicException,
"e is PlatformNotSupportedException || e is CryptographicException");
}
}
}
private void ReadWriteBase64SubjectPublicKeyInfo(
string base64SubjectPublicKeyInfo,
in ECParameters expected,
bool isSupported = true)
{
if (isSupported)
{
ECParameters expectedPublic = expected;
expectedPublic.D = null;
ReadWriteKey(
base64SubjectPublicKeyInfo,
expectedPublic,
(T key, ReadOnlySpan<byte> source, out int read) =>
key.ImportSubjectPublicKeyInfo(source, out read),
key => key.ExportSubjectPublicKeyInfo(),
(T key, Span<byte> destination, out int written) =>
key.TryExportSubjectPublicKeyInfo(destination, out written));
}
else
{
using (T key = CreateKey())
{
Exception e = Assert.ThrowsAny<Exception>(
() => key.ImportSubjectPublicKeyInfo(Convert.FromBase64String(base64SubjectPublicKeyInfo), out _));
Assert.True(
e is PlatformNotSupportedException || e is CryptographicException,
"e is PlatformNotSupportedException || e is CryptographicException");
}
}
}
private void ReadWriteKey(
string base64,
in ECParameters expected,
ReadKeyAction readAction,
Func<T, byte[]> writeArrayFunc,
WriteKeyToSpanFunc writeSpanFunc,
bool isEncrypted = false)
{
bool isPrivateKey = expected.D != null;
byte[] derBytes = Convert.FromBase64String(base64);
byte[] arrayExport;
byte[] tooBig;
const int OverAllocate = 30;
const int WriteShift = 6;
using (T key = CreateKey())
{
readAction(key, derBytes, out int bytesRead);
Assert.Equal(derBytes.Length, bytesRead);
arrayExport = writeArrayFunc(key);
ECParameters ecParameters = ExportParameters(key, isPrivateKey);
EccTestBase.AssertEqual(expected, ecParameters);
}
// It's not reasonable to assume that arrayExport and derBytes have the same
// contents, because the SubjectPublicKeyInfo and PrivateKeyInfo formats both
// have the curve identifier in the AlgorithmIdentifier.Parameters field, and
// either the input or the output may have chosen to then not emit it in the
// optional domainParameters field of the ECPrivateKey blob.
//
// Once we have exported the data to normalize it, though, we should see
// consistency in the answer format.
using (T key = CreateKey())
{
Assert.ThrowsAny<CryptographicException>(
() => readAction(key, arrayExport.AsSpan(1), out _));
Assert.ThrowsAny<CryptographicException>(
() => readAction(key, arrayExport.AsSpan(0, arrayExport.Length - 1), out _));
readAction(key, arrayExport, out int bytesRead);
Assert.Equal(arrayExport.Length, bytesRead);
ECParameters ecParameters = ExportParameters(key, isPrivateKey);
EccTestBase.AssertEqual(expected, ecParameters);
Assert.False(
writeSpanFunc(key, Span<byte>.Empty, out int bytesWritten),
"Write to empty span");
Assert.Equal(0, bytesWritten);
Assert.False(
writeSpanFunc(
key,
derBytes.AsSpan(0, Math.Min(derBytes.Length, arrayExport.Length) - 1),
out bytesWritten),
"Write to too-small span");
Assert.Equal(0, bytesWritten);
tooBig = new byte[arrayExport.Length + OverAllocate];
tooBig.AsSpan().Fill(0xC4);
Assert.True(writeSpanFunc(key, tooBig.AsSpan(WriteShift), out bytesWritten));
Assert.Equal(arrayExport.Length, bytesWritten);
Assert.Equal(0xC4, tooBig[WriteShift - 1]);
Assert.Equal(0xC4, tooBig[WriteShift + bytesWritten + 1]);
// If encrypted, the data should have had a random salt applied, so unstable.
// Otherwise, we've normalized the data (even for private keys) so the output
// should match what it output previously.
if (isEncrypted)
{
Assert.NotEqual(
arrayExport.ByteArrayToHex(),
tooBig.AsSpan(WriteShift, bytesWritten).ByteArrayToHex());
}
else
{
Assert.Equal(
arrayExport.ByteArrayToHex(),
tooBig.AsSpan(WriteShift, bytesWritten).ByteArrayToHex());
}
}
using (T key = CreateKey())
{
readAction(key, tooBig.AsSpan(WriteShift), out int bytesRead);
Assert.Equal(arrayExport.Length, bytesRead);
arrayExport.AsSpan().Fill(0xCA);
Assert.True(
writeSpanFunc(key, arrayExport, out int bytesWritten),
"Write to precisely allocated Span");
if (isEncrypted)
{
Assert.NotEqual(
tooBig.AsSpan(WriteShift, bytesWritten).ByteArrayToHex(),
arrayExport.ByteArrayToHex());
}
else
{
Assert.Equal(
tooBig.AsSpan(WriteShift, bytesWritten).ByteArrayToHex(),
arrayExport.ByteArrayToHex());
}
}
}
private delegate void ReadKeyAction(T key, ReadOnlySpan<byte> source, out int bytesRead);
private delegate bool WriteKeyToSpanFunc(T key, Span<byte> destination, out int bytesWritten);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void AsInt32()
{
var test = new VectorAs__AsInt32();
// Validates basic functionality works
test.RunBasicScenario();
// Validates basic functionality works using the generic form, rather than the type-specific form of the method
test.RunGenericScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorAs__AsInt32
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Vector128<Int32> value;
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<byte> byteResult = value.AsByte();
ValidateResult(byteResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<double> doubleResult = value.AsDouble();
ValidateResult(doubleResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<short> shortResult = value.AsInt16();
ValidateResult(shortResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<int> intResult = value.AsInt32();
ValidateResult(intResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<long> longResult = value.AsInt64();
ValidateResult(longResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<sbyte> sbyteResult = value.AsSByte();
ValidateResult(sbyteResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<float> floatResult = value.AsSingle();
ValidateResult(floatResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<ushort> ushortResult = value.AsUInt16();
ValidateResult(ushortResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<uint> uintResult = value.AsUInt32();
ValidateResult(uintResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<ulong> ulongResult = value.AsUInt64();
ValidateResult(ulongResult, value);
}
public void RunGenericScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario));
Vector128<Int32> value;
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<byte> byteResult = value.As<Int32, byte>();
ValidateResult(byteResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<double> doubleResult = value.As<Int32, double>();
ValidateResult(doubleResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<short> shortResult = value.As<Int32, short>();
ValidateResult(shortResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<int> intResult = value.As<Int32, int>();
ValidateResult(intResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<long> longResult = value.As<Int32, long>();
ValidateResult(longResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<sbyte> sbyteResult = value.As<Int32, sbyte>();
ValidateResult(sbyteResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<float> floatResult = value.As<Int32, float>();
ValidateResult(floatResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<ushort> ushortResult = value.As<Int32, ushort>();
ValidateResult(ushortResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<uint> uintResult = value.As<Int32, uint>();
ValidateResult(uintResult, value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
Vector128<ulong> ulongResult = value.As<Int32, ulong>();
ValidateResult(ulongResult, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Vector128<Int32> value;
value = Vector128.Create(TestLibrary.Generator.GetInt32());
object byteResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsByte))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<byte>)(byteResult), value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
object doubleResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsDouble))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<double>)(doubleResult), value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
object shortResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsInt16))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<short>)(shortResult), value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
object intResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsInt32))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<int>)(intResult), value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
object longResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsInt64))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<long>)(longResult), value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
object sbyteResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsSByte))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<sbyte>)(sbyteResult), value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
object floatResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsSingle))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<float>)(floatResult), value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
object ushortResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsUInt16))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<ushort>)(ushortResult), value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
object uintResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsUInt32))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<uint>)(uintResult), value);
value = Vector128.Create(TestLibrary.Generator.GetInt32());
object ulongResult = typeof(Vector128)
.GetMethod(nameof(Vector128.AsUInt64))
.MakeGenericMethod(typeof(Int32))
.Invoke(null, new object[] { value });
ValidateResult((Vector128<ulong>)(ulongResult), value);
}
private void ValidateResult<T>(Vector128<T> result, Vector128<Int32> value, [CallerMemberName] string method = "")
where T : struct
{
Int32[] resultElements = new Int32[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref resultElements[0]), result);
Int32[] valueElements = new Int32[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref valueElements[0]), value);
ValidateResult(resultElements, valueElements, typeof(T), method);
}
private void ValidateResult(Int32[] resultElements, Int32[] valueElements, Type targetType, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < ElementCount; i++)
{
if (resultElements[i] != valueElements[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<Int32>.As{targetType.Name}: {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
#region -- License Terms --
//
// NLiblet
//
// Copyright (C) 2011 FUJIWARA, Yusuke
//
// 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 -- License Terms --
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
namespace NLiblet.Collections
{
/// <summary>
/// <see cref="ISet{T}"/> implementation which preserves inserting order.
/// </summary>
/// <typeparam name="T">Type of the item.</typeparam>
/// <remarks>
/// This class is similer to Java Collection Framework's LinkedHashSet.
/// <note>
/// For LINQ Last(), LastOrDefault(), and Reverse() operators, it is more efficient to use this class directly than via interface.
/// </note>
/// </remarks>
[Serializable]
[DebuggerDisplay( "Count={Count}" )]
[DebuggerTypeProxy( typeof( CollectionDebuggerProxy<> ) )]
public partial class LinkedHashSet<T> : ISet<T>
{
// For lookup, use LinkedDictionary<T,T> for backing store.
private readonly Dictionary<T, LinkedSetNode<T>> _lookup;
private int _version;
// Bridge to bulk clear.
private Bridge _currentBridge;
#region -- Properties --
#region ---- Head and Tail ----
private LinkedSetNode<T> _head;
/// <summary>
/// Get the head node of this set.
/// </summary>
/// <value>
/// The head node of this set. If this set is empty then <c>null</c>.
/// </value>
/// <remarks>
/// Note that the node holds reference to other nodes and underlying collection, so it could cause unpected resource leak.
/// </remarks>
[Pure]
public LinkedSetNode<T> Head
{
get
{
Contract.Ensures(
this.Count == 0 && Contract.Result<LinkedSetNode<T>>() == null
|| 0 < this.Count && Contract.Result<LinkedSetNode<T>>() != null
);
return this._head;
}
}
private LinkedSetNode<T> _tail;
/// <summary>
/// Get the tail node of this set.
/// </summary>
/// <value>
/// The tail node of this set. If this set is empty then <c>null</c>.
/// </value>
/// <remarks>
/// Note that the node holds reference to other nodes and underlying collection, so it could cause unpected resource leak.
/// </remarks>
[Pure]
public LinkedSetNode<T> Tail
{
get
{
Contract.Ensures(
this.Count == 0 && Contract.Result<LinkedSetNode<T>>() == null
|| 0 < this.Count && Contract.Result<LinkedSetNode<T>>() != null
);
return this._tail;
}
}
#endregion ---- Head and Tail ----
#region ---- Count and Comparer ----
/// <summary>
/// Gets the <see cref="IEqualityComparer{T}"/> that is used to determine equality for the values in the set.
/// </summary>
/// <value>
/// The <see cref="IEqualityComparer{T}"/> object that is used to determine equality for the values in the set.
/// </value>
[Pure]
public IEqualityComparer<T> Comparer
{
get
{
Contract.Ensures( Contract.Result<IEqualityComparer<T>>() != null );
return this._lookup.Comparer;
}
}
/// <summary>
/// Gets the number of elements contained in this set.
/// </summary>
/// <returns>
/// The number of elements contained in this set.
/// </returns>
public int Count
{
get
{
Contract.Ensures( 0 <= Contract.Result<int>() );
return this._lookup.Count;
}
}
#endregion ---- Count and Comparer ----
#region ---- Interface Explicit Implementations ----
[SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Easy to re-declare." )]
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
#endregion ---- Interface Explicit Implementations ----
#endregion -- Properties --
#region -- Constructors --
/// <summary>
/// Initializes a new empty instance of the <see cref="LinkedHashSet{T}"/> class.
/// with default comparer.
/// </summary>
public LinkedHashSet()
{
this._lookup = new Dictionary<T, LinkedSetNode<T>>();
this._currentBridge = new Bridge( this );
}
/// <summary>
/// Initializes a new empty instance of the <see cref="LinkedHashSet{T}"/> class.
/// with specified comparer.
/// </summary>
/// <param name="comparer">
/// The <see cref="IEqualityComparer{T}"/> object that is used to determine equality for the values in the set.
/// </param>
public LinkedHashSet( IEqualityComparer<T> comparer )
{
this._lookup = new Dictionary<T, LinkedSetNode<T>>( comparer );
this._currentBridge = new Bridge( this );
}
/// <summary>
/// Initializes a new instance of the <see cref="LinkedHashSet{T}"/> class
/// with specified initial items and comparer.
/// </summary>
/// <param name="initial">The initial collection to be copied.</param>
/// <param name="comparer">
/// The <see cref="IEqualityComparer{T}"/> object that is used to determine equality for the values in the set.
/// </param>
public LinkedHashSet( IEnumerable<T> initial, IEqualityComparer<T> comparer )
{
Contract.Requires<ArgumentNullException>( initial != null );
var asCollection = initial as ICollection<T>;
this._lookup =
asCollection != null
? new Dictionary<T, LinkedSetNode<T>>( asCollection.Count, comparer )
: new Dictionary<T, LinkedSetNode<T>>( comparer );
this._currentBridge = new Bridge( this );
foreach ( var item in initial )
{
this.AddItemCore( item );
}
}
#endregion -- Constructors --
#region -- Methods --
#region ---- Template Methods ----
/// <summary>
/// Adds the specified element to a set.
/// </summary>
/// <param name="item">
/// The element to add to the set.
/// </param>
/// <returns>
/// New node if the element is added to this set; <c>null</c> if the element is already present.
/// </returns>
/// <remarks>
/// <para>
/// Derived class can override this method to intercept manipulation.
/// </para>
/// <note>
/// <strong>Note for implementers:</strong> You must call base implementation from overrides, but you can invoke in any timing as you want to do.
/// </note>
/// <para>
/// Note that the node holds reference to other nodes and underlying collection, so it could cause unpected resource leak.
/// </para>
/// </remarks>
protected virtual LinkedSetNode<T> AddItem( T item )
{
Contract.Ensures(
( Contract.OldValue( this.Contains( item ) ) && Contract.Result<LinkedSetNode<T>>() == null )
|| ( !Contract.OldValue( this.Contains( item ) ) && Contract.Result<LinkedSetNode<T>>() != null )
);
Contract.Ensures( this.Contains( item ) );
return this.AddItemCore( item );
}
private LinkedSetNode<T> AddItemCore( T item )
{
if ( this._lookup.ContainsKey( item ) )
{
return null;
}
var oldTail = this._tail;
var node = new LinkedSetNode<T>( item, this._currentBridge, oldTail, null );
if ( oldTail != null )
{
oldTail.InternalNext = node;
}
this._tail = node;
if ( this._head == null )
{
this._head = node;
}
this._lookup.Add( item, node );
this._version++;
return node;
}
/// <summary>
/// Removes the specified element from this set.
/// </summary>
/// <param name="item">
/// The element to remove.
/// </param>
/// <returns>
/// Removed node if the element is successfully found and removed;
/// otherwise, <c>null</c>.
/// </returns>
/// <remarks>
/// <para>
/// Derived class can override this method to intercept manipulation.
/// </para>
/// <note>
/// <strong>Note for implementers:</strong> You must call base implementation from overrides, but you can invoke in any timing as you want to do.
/// </note>
/// <para>
/// Note that the node holds reference to other nodes and underlying collection, so it could cause unpected resource leak.
/// </para>
/// </remarks>
protected virtual LinkedSetNode<T> RemoveItem( T item )
{
Contract.Ensures(
( Contract.OldValue( this.Contains( item ) ) && Contract.Result<LinkedSetNode<T>>() != null )
|| ( !Contract.OldValue( this.Contains( item ) ) && Contract.Result<LinkedSetNode<T>>() == null )
);
Contract.Ensures( !this.Contains( item ) );
LinkedSetNode<T> existingNode;
if ( !this._lookup.TryGetValue( item, out existingNode ) )
{
return null;
}
Contract.Assert( existingNode != null );
var oldPrevious = existingNode.InternalPrevious;
var oldNext = existingNode.InternalNext;
this._lookup.Remove( item );
existingNode.InternalBridge = null;
existingNode.InternalNext = null;
existingNode.InternalPrevious = null;
if ( oldPrevious != null )
{
oldPrevious.InternalNext = oldNext;
}
else
{
this._head = oldNext;
}
if ( oldNext != null )
{
oldNext.InternalPrevious = oldPrevious;
}
else
{
this._tail = oldPrevious;
}
this._version++;
return existingNode;
}
/// <summary>
/// Removes all items from this set.
/// </summary>
/// <remarks>
/// <para>
/// Derived class can override this method to intercept manipulation.
/// </para>
/// <note>
/// <strong>Note for implementers:</strong> You must call base implementation from overrides, but you can invoke in any timing as you want to do.
/// </note>
/// <para>
/// Note that the node holds reference to other nodes and underlying collection, so it could cause unpected resource leak.
/// </para>
/// </remarks>
protected virtual void ClearItems()
{
Contract.Ensures( this.Count == 0 );
var oldBridge = this._currentBridge;
this._currentBridge = new Bridge( this );
// Bulk reject.
oldBridge.Set = null;
this._lookup.Clear();
this._head = null;
this._tail = null;
this._version++;
}
#endregion ---- Template Methods ----
#region ---- Node manipulation ----
/// <summary>
/// Get node for specified item.
/// </summary>
/// <param name="item">
/// The element related to node.
/// </param>
/// <returns>
/// If node for specifid item is present then the node;
/// otherwise, <c>null</c>.
/// </returns>
[Pure]
protected LinkedSetNode<T> GetNodeDirect( T item )
{
LinkedSetNode<T> existingNode;
this._lookup.TryGetValue( item, out existingNode );
return existingNode;
}
/// <summary>
/// Replace specified node's value.
/// </summary>
/// <param name="node">The target node.</param>
/// <param name="value">The value to be replaced.</param>
/// <returns>The old value of <paramref name="node"/>.</returns>
/// <exception cref="ArgumentException">
/// <paramref name="value"/> is already owned by another node.
/// </exception>
protected T ReplaceValueDirect( LinkedSetNode<T> node, T value )
{
Contract.Requires<ArgumentNullException>( node != null );
Contract.Requires<ArithmeticException>( node.Set == this );
if ( this.Comparer.Equals( node.Value, value ) )
{
return node.Value;
}
if ( this._lookup.ContainsKey( value ) )
{
throw new ArgumentException( "value is owned by another node.", "value" );
}
#if DEBUG
var oldPrevious = node.Previous;
var oldNext = node.Next;
#endif
var oldValue = node.Value;
LinkedSetNode<T> backingNode = this._lookup[ node.InternalValue ];
this._lookup.Remove( node.InternalValue );
backingNode.InternalValue = value;
this._lookup.Add( value, node );
#if DEBUG
Contract.Assert( node.Previous == oldPrevious );
Contract.Assert( node.Next == oldNext );
Contract.Assert( node == oldPrevious.Next );
Contract.Assert( node == oldNext.Previous );
#endif
return oldValue;
}
/// <summary>
/// Move specified node to head.
/// </summary>
/// <param name="moving">
/// Moving node.
/// </param>
protected void MoveNodeToHead( LinkedSetNode<T> moving )
{
Contract.Requires<ArgumentNullException>( moving != null );
if ( moving == this.Head )
{
return;
}
this.MoveNodeToBeforeCore( this.Head, moving );
}
/// <summary>
/// Move specified node to before from specified destination node.
/// </summary>
/// <param name="destination">
/// Destination node.
/// </param>
/// <param name="moving">
/// Moving node.
/// </param>
protected void MoveNodeToBefore( LinkedSetNode<T> destination, LinkedSetNode<T> moving )
{
Contract.Requires<ArgumentNullException>( destination != null );
Contract.Requires<ArgumentNullException>( moving != null );
this.MoveNodeToBeforeCore( destination, moving );
}
private void MoveNodeToBeforeCore( LinkedSetNode<T> destination, LinkedSetNode<T> moving )
{
if ( destination == moving.InternalNext )
{
return;
}
this.MoveNode(
moving,
newPrevious: destination.InternalPrevious,
newNext: destination
);
}
/// <summary>
/// Move specified node to head.
/// </summary>
/// <param name="moving">
/// Moving node.
/// </param>
protected void MoveNodeToTail( LinkedSetNode<T> moving )
{
Contract.Requires<ArgumentNullException>( moving != null );
if ( moving == this.Tail )
{
return;
}
this.MoveNodeToAfterCore( this.Tail, moving );
}
/// <summary>
/// Move specified node to next to specified destination node.
/// </summary>
/// <param name="destination">
/// Destination node.
/// </param>
/// <param name="moving">
/// Moving node.
/// </param>
protected void MoveNodeToAfter( LinkedSetNode<T> destination, LinkedSetNode<T> moving )
{
Contract.Requires<ArgumentNullException>( destination != null );
Contract.Requires<ArgumentNullException>( moving != null );
this.MoveNodeToAfterCore( destination, moving );
}
private void MoveNodeToAfterCore( LinkedSetNode<T> destination, LinkedSetNode<T> moving )
{
if ( destination == moving.InternalPrevious )
{
return;
}
this.MoveNode(
moving,
newPrevious: destination,
newNext: destination.InternalNext
);
}
/// <summary>
/// Moves the node to specified destination.
/// </summary>
/// <param name="moving">The moving node.</param>
/// <param name="newPrevious">The node to be previous of <paramref name="moving"/>.</param>
/// <param name="newNext">The node to be next of <paramref name="moving"/>.</param>
protected virtual void MoveNode( LinkedSetNode<T> moving, LinkedSetNode<T> newPrevious, LinkedSetNode<T> newNext )
{
Contract.Requires<ArgumentNullException>( moving != null );
Contract.Requires<ArgumentException>( moving.Set == this );
Contract.Requires<ArgumentException>( newPrevious == null || newPrevious.Set == this );
Contract.Requires<ArgumentException>( newNext == null || newNext.Set == this );
Contract.Requires<ArgumentException>( newPrevious == null || newPrevious.Next == newNext || newPrevious == moving.Previous );
Contract.Requires<ArgumentException>( newNext == null || newNext.Previous == newPrevious || newNext == moving.Next );
Contract.Requires<ArgumentException>( newPrevious == null || newPrevious.Previous != newNext );
Contract.Requires<ArgumentException>( newNext == null || newNext.Next != newPrevious );
if ( moving.InternalNext == newNext )
{
Contract.Assert( moving.InternalPrevious == newPrevious );
// Nothing to do.
return;
}
var oldPrevious = moving.InternalPrevious;
var oldNext = moving.InternalNext;
if ( newPrevious != null )
{
newPrevious.InternalNext = moving;
}
else
{
this._head = moving;
}
moving.InternalPrevious = newPrevious;
if ( newNext != null )
{
newNext.InternalPrevious = moving;
}
else
{
this._tail = moving;
}
moving.InternalNext = newNext;
if ( oldPrevious != null )
{
oldPrevious.InternalNext = oldNext;
}
else
{
this._head = oldNext;
}
if ( oldNext != null )
{
oldNext.InternalPrevious = oldPrevious;
}
else
{
this._tail = oldPrevious;
}
this._version++;
}
#endregion ---- Node manipulation ----
#region ---- Add ----
/// <summary>
/// Adds the specified element to a set.
/// </summary>
/// <param name="item">
/// The element to add to the set.
/// </param>
/// <returns>
/// New node if the element is added to this set; <c>null</c> if the element is already present.
/// </returns>
public LinkedSetNode<T> Add( T item )
{
Contract.Ensures(
( Contract.OldValue( this.Contains( item ) ) && Contract.Result<LinkedSetNode<T>>() == null )
|| ( !Contract.OldValue( this.Contains( item ) ) && Contract.Result<LinkedSetNode<T>>() != null )
);
Contract.Ensures( this.Contains( item ) );
return this.AddItem( item );
}
bool ISet<T>.Add( T item )
{
return this.Add( item ) != null;
}
void ICollection<T>.Add( T item )
{
this.Add( item );
}
#endregion ---- Add ----
#region ---- Remove ----
/// <summary>
/// Removes the specified element from this set.
/// </summary>
/// <param name="item">
/// The element to remove.
/// </param>
/// <returns>
/// Removed node if the element is successfully found and removed;
/// otherwise, <c>null</c>.
/// </returns>
public LinkedSetNode<T> Remove( T item )
{
Contract.Ensures(
( Contract.OldValue( this.Contains( item ) ) && Contract.Result<LinkedSetNode<T>>() != null )
|| ( !Contract.OldValue( this.Contains( item ) ) && Contract.Result<LinkedSetNode<T>>() == null )
);
Contract.Ensures( !this.Contains( item ) );
return this.RemoveItem( item );
}
/// <summary>
/// Removes the specified node from this set.
/// </summary>
/// <param name="node">
/// The node to be removed.
/// </param>
public void Remove( LinkedSetNode<T> node )
{
Contract.Requires<ArgumentNullException>( node != null );
Contract.Requires<ArgumentException>( node.Set == this );
Contract.Ensures( node.Set == null );
Contract.Ensures( !this.Contains( node.Value ) );
this.RemoveItem( node.Value );
}
bool ICollection<T>.Remove( T item )
{
return this.RemoveItem( item ) != null;
}
#endregion ---- Remove ----
#region ---- Clear ----
/// <summary>
/// Removes all items from this set.
/// </summary>
public void Clear()
{
this.ClearItems();
}
#endregion ---- Clear ----
#region ---- Contains ----
/// <summary>
/// Determines whether this set contains an element.
/// </summary>
/// <param name="item">
/// The item to locate in this set.</param>
/// <returns>
/// <c>true</c> if this set contains an element; otherwise, <c>false</c>.
/// </returns>
public bool Contains( T item )
{
return this._lookup.ContainsKey( item );
}
#endregion ---- Contains ----
#region ---- Copy ----
/// <summary>
/// Copies the entire set to a compatible one-dimensional array, starting at the beginning of the target array.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements copied from this set.
/// The <see cref="Array"/> must have zero-based indexing.
/// </param>
[Pure]
public void CopyTo( T[] array )
{
Contract.Requires<ArgumentNullException>( array != null );
CollectionOperation.CopyTo( this, this.Count, 0, array, 0, this.Count );
}
/// <summary>
/// Copies the entire set to a compatible one-dimensional array,
/// starting at the specified index of the target array.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements copied from this set.
/// The <see cref="Array"/> must have zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in <paramref name="array"/> at which copying begins.
/// </param>
public void CopyTo( T[] array, int arrayIndex )
{
CollectionOperation.CopyTo( this, this.Count, 0, array, arrayIndex, this.Count );
}
/// <summary>
/// Copies a range of elements from this set to a compatible one-dimensional array,
/// starting at the specified index of the target array.
/// </summary>
/// <param name="index">
/// The zero-based index in the source set at which copying begins.
/// </param>
/// <param name="array">
/// The one-dimensional <see cref="Array"/> that is the destination of the elements copied from this set.
/// The <see cref="Array"/> must have zero-based indexing.
/// </param>
/// <param name="arrayIndex">
/// The zero-based index in <paramref name="array"/> at which copying begins.
/// </param>
/// <param name="count">
/// The number of elements to copy.
/// </param>
[Pure]
public void CopyTo( int index, T[] array, int arrayIndex, int count )
{
Contract.Requires<ArgumentNullException>( array != null );
Contract.Requires<ArgumentOutOfRangeException>( 0 <= index );
Contract.Requires<ArgumentException>( this.Count == 0 || index < this.Count );
Contract.Requires<ArgumentOutOfRangeException>( 0 <= arrayIndex );
Contract.Requires<ArgumentOutOfRangeException>( 0 <= count );
Contract.Requires<ArgumentException>( arrayIndex < array.Length - count );
CollectionOperation.CopyTo( this, this.Count, index, array, arrayIndex, count );
}
#endregion ---- Copy ----
#region ---- GetEnumerator ----
/// <summary>
/// Returns an enumerator that iterates through the <see cref="LinkedHashSet{T}"/>.
/// </summary>
/// <returns>
/// Returns an enumerator that iterates through the <see cref="LinkedHashSet{T}"/>.
/// </returns>
public Enumerator GetEnumerator()
{
return new Enumerator( this );
}
/// <summary>
/// Returns an enumerator that iterates in reverse order through the <see cref="LinkedHashSet{T}"/>.
/// </summary>
/// <returns>
/// Returns an enumerator that iterates in reverse order through the <see cref="LinkedHashSet{T}"/>.
/// </returns>
[Pure]
[SuppressMessage( "Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Method is preferred because logically returns new object." )]
public ReverseEnumerator GetReverseEnumerator()
{
return new ReverseEnumerator( this );
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion ---- GetEnumerator ----
#region ---- LINQ support ----
/// <summary>
/// Returns the first element of a sequence.
/// </summary>
/// <returns>
/// The first element in this set.
/// </returns>
[Pure]
public T First()
{
// This API follows Enumerable.First<T>(IEnumerable<T>) contract.
return Enumerable.First( this );
}
/// <summary>
/// Returns the first element in a sequence that satisfies a specified condition.
/// </summary>
/// <param name="predicate">
/// A function to test each element for a condition.
/// </param>
/// <returns>
/// The first element in the sequence that passes the test in the specified <paramref name="predicate"/> function.
/// </returns>
[Pure]
public T First( Func<T, bool> predicate )
{
// This API follows Enumerable.First<T>(IEnumerable<T>,Func<T,bool>) contract.
return Enumerable.First( this, predicate );
}
/// <summary>
/// Returns the first element of a sequence, or a default value if no element is found.
/// </summary>
/// <returns>
/// <c>default(<typeparamref name="T"/></c> if source is empty; otherwise, the first element in source.
/// </returns>
[Pure]
public T FirstOrDefault()
{
// This API follows Enumerable.FirstOrDefault<T>(IEnumerable<T>) contract.
return Enumerable.FirstOrDefault( this );
}
/// <summary>
/// Returns the first element of the sequence that satisfies a condition or a default value if no such element is found.
/// </summary>
/// <param name="predicate">
/// A function to test each element for a condition.
/// </param>
/// <returns>
/// <c>default(<typeparamref name="T"/></c> if source is empty or if no element passes the test specified by <paramref name="predicate"/>;
/// otherwise, the first element in source that passes the test specified by <paramref name="predicate"/>.
/// </returns>
[Pure]
public T FirstOrDefault( Func<T, bool> predicate )
{
// This API follows Enumerable.FirstOrDefault<T>(IEnumerable<T>,Func<T,bool>) contract.
return Enumerable.FirstOrDefault( this, predicate );
}
/// <summary>
/// Returns the last element of a sequence.
/// </summary>
/// <returns>
/// The value at the last position in the source sequence.
/// </returns>
public T Last()
{
// This API follows Enumerable.Last<T>(IEnumerable<T>) contract.
var node = this.Tail;
if ( node == null )
{
throw new InvalidOperationException( "Sequence is empty." );
}
return node.Value;
}
/// <summary>
/// Returns the last element of a sequence that satisfies a specified condition.
/// </summary>
/// <param name="predicate">
/// A function to test each element for a condition.
/// </param>
/// <returns>
/// The last element in the sequence that passes the test in the specified <paramref name="predicate"/> function.
/// </returns>
public T Last( Func<T, bool> predicate )
{
// This API follows Enumerable.Last<T>(IEnumerable<T>,Func<T,bool>) contract.
return this.Reverse().First( predicate );
}
/// <summary>
/// Returns the last element of a sequence, or a default value if the sequence contains no elements.
/// </summary>
/// <returns>
/// <c>default(<typeparamref name="T"/></c> if source is empty; otherwise, the last element in source.
/// </returns>
public T LastOrDefault()
{
// This API follows Enumerable.LastOrDefault<T>(IEnumerable<T>) contract.
var node = this.Tail;
if ( node == null )
{
return default( T );
}
return node.Value;
}
/// <summary>
/// Returns the last element of the sequence that satisfies a condition or a default value if no such element is found.
/// </summary>
/// <param name="predicate">
/// A function to test each element for a condition.
/// </param>
/// <returns>
/// <c>default(<see cref="KeyValuePair{TKey,TValue}"/></c> if source is empty or if no element passes the test specified by <paramref name="predicate"/>;
/// otherwise, the last element in source that passes the test specified by <paramref name="predicate"/>.
/// </returns>
public T LastOrDefault( Func<T, bool> predicate )
{
// This API follows Enumerable.LastOrDefault<T>(IEnumerable<T>,Func<T,bool>) contract.
return this.Reverse().FirstOrDefault( predicate );
}
/// <summary>
/// Inverts the order of the elements in this set.
/// </summary>
/// <returns>
/// A sequence whose elements correspond to those of the input sequence in reverse order.
/// </returns>
public IEnumerable<T> Reverse()
{
// This API follows Enumerable.Reverse<T>(IEnumerable<T>) contract.
Contract.Ensures( Contract.Result<IEnumerable<T>>() != null );
return new ReverseView( this );
}
#endregion ---- LINQ support ----
#region ---- Set Operators ----
/// <summary>
/// Removes all elements in the specified collection from the current set.
/// </summary>
/// <param name="other">
/// The collection of items to remove from the set.
/// </param>
public void ExceptWith( IEnumerable<T> other )
{
foreach ( var item in other )
{
this.Remove( item );
}
}
/// <summary>
/// Modifies the current set so that it contains only elements that are present either in the current set or in the specified collection, but not both.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
public void SymmetricExceptWith( IEnumerable<T> other )
{
var additions = new HashSet<T>();
var removals = new HashSet<T>();
foreach ( var item in other )
{
if ( this.Contains( item ) )
{
removals.Add( item );
}
else
{
additions.Add( item );
}
}
foreach ( var removal in removals )
{
this.Remove( removal );
}
foreach ( var addition in additions )
{
this.Add( addition );
}
}
/// <summary>
/// Modifies the current set so that it contains only elements that are also in a specified collection.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
public void IntersectWith( IEnumerable<T> other )
{
var otherSet = new HashSet<T>( other );
var removals = new HashSet<T>();
foreach ( var item in otherSet )
{
if ( !this.Contains( item ) )
{
removals.Add( item );
}
}
foreach ( var item in this )
{
if ( !otherSet.Contains( item ) )
{
removals.Add( item );
}
}
foreach ( var removal in removals )
{
this.Remove( removal );
}
}
/// <summary>
/// Modifies the current set so that it contains all elements that are present in both the current set and in the specified collection.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
public void UnionWith( IEnumerable<T> other )
{
foreach ( var item in other )
{
this.Add( item );
}
}
/// <summary>
/// Determines whether the current set is a property (strict) subset of a specified collection.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
/// <returns>
/// <c>true</c> if the current set is a correct subset of <paramref name="other"/>; otherwise, <c>false</c>.
/// </returns>
public bool IsProperSubsetOf( IEnumerable<T> other )
{
return SetOperation.IsProperSubsetOf( this, other );
}
/// <summary>
/// Determines whether the current set is a property (strict) superset of a specified collection.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
/// <returns>
/// <c>true</c> if the current set is a correct superset of <paramref name="other"/>; otherwise, <c>false</c>.
/// </returns>
public bool IsProperSupersetOf( IEnumerable<T> other )
{
return SetOperation.IsProperSupersetOf( this, other );
}
/// <summary>
/// Determines whether a set is a subset of a specified collection.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
/// <returns>
/// <c>true</c> if the current set is a subset of <paramref name="other"/>; otherwise, <c>false</c>.
/// </returns>
public bool IsSubsetOf( IEnumerable<T> other )
{
return SetOperation.IsSubsetOf( this, other );
}
/// <summary>
/// Determines whether a set is a superset of a specified collection.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
/// <returns>
/// <c>true</c> if the current set is a superset of <paramref name="other"/>; otherwise, <c>false</c>.
/// </returns>
public bool IsSupersetOf( IEnumerable<T> other )
{
return SetOperation.IsSupersetOf( this, other );
}
/// <summary>
/// Determines whether the current set overlaps with the specified collection.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
/// <returns>
/// <c>true</c> if the current set and <paramref name="other"/> share at least one common element; otherwise, <c>false</c>.
/// </returns>
public bool Overlaps( IEnumerable<T> other )
{
return SetOperation.Overlaps( this, other );
}
/// <summary>
/// Determines whether the current set and the specified collection contain the same elements.
/// </summary>
/// <param name="other">
/// The collection to compare to the current set.
/// </param>
/// <returns>
/// <c>true</c> if the current set is equal to <paramref name="other"/>; otherwise, <c>false</c>.
/// </returns>
public bool SetEquals( IEnumerable<T> other )
{
return SetOperation.SetEquals( this, other );
}
#endregion ---- Set Operators ----
#endregion -- Method --
#region -- Misc Nested Types --
/// <summary>
/// Support for bulk unlinking of nodes.
/// </summary>
[Serializable]
internal sealed class Bridge
{
// This member is intentionally mutable for bulk unlinking on ClearItems().
public LinkedHashSet<T> Set;
public Bridge( LinkedHashSet<T> set )
{
this.Set = set;
}
}
/// <summary>
/// <see cref="IEnumerable{T}"/> for reserve order view.
/// </summary>
private sealed class ReverseView : IEnumerable<T>
{
private readonly LinkedHashSet<T> _set;
public ReverseView( LinkedHashSet<T> set )
{
this._set = set;
}
public IEnumerator<T> GetEnumerator()
{
return this._set.GetReverseEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
#endregion -- Misc Nested Types --
}
}
| |
// 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.Text;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class is used to construct and contain the state of an inprogress targets. The primary data
/// includes build requests blocked until this target completes and build requests that must complete
/// before this target can make forward process.
/// </summary>
internal class TargetInProgessState
{
#region Constructors
internal TargetInProgessState()
{
}
internal TargetInProgessState
(
EngineCallback engineCallback,
Target target,
List<ProjectBuildState> waitingBuildStates,
ProjectBuildState initiatingRequest,
BuildRequest [] outstandingBuildRequests,
string projectName
)
{
this.targetId = new TargetIdWrapper(target);
this.outstandingBuildRequests = outstandingBuildRequests;
// For each waiting build context try to find the parent target
this.parentBuildRequests = new List<BuildRequest>();
this.parentTargets = new List<TargetIdWrapper>();
this.projectName = projectName;
// Process the waiting contexts if there are any
if (waitingBuildStates != null)
{
for (int i = 0; i < waitingBuildStates.Count; i++)
{
ProcessBuildContext(engineCallback, waitingBuildStates[i], target);
}
}
// Process the initiating context
ProcessBuildContext(engineCallback, initiatingRequest, target);
}
/// <summary>
/// Figure out the parent target or the parent build request for the given context
/// </summary>
private void ProcessBuildContext(EngineCallback engineCallback, ProjectBuildState buildContext, Target target)
{
BuildRequest parentRequest = null;
TargetIdWrapper parentName = FindParentTarget(engineCallback, buildContext, target, out parentRequest);
if (parentName != null)
{
parentTargets.Add(parentName);
}
if (parentRequest != null)
{
parentBuildRequests.Add(parentRequest);
}
}
#endregion
#region Properties
/// <summary>
/// Unique identifier for the target
/// </summary>
internal TargetIdWrapper TargetId
{
get
{
return this.targetId;
}
}
/// <summary>
/// List of unique identifiers for the targets that are blocked until the current
/// target completes
/// </summary>
internal List<TargetIdWrapper> ParentTargets
{
get
{
return this.parentTargets;
}
}
/// <summary>
/// List of build requests that are blocked until the current
/// target completes
/// </summary>
internal List<BuildRequest> ParentBuildRequests
{
get
{
return this.parentBuildRequests;
}
}
/// <summary>
/// Array of build requests that must complete before the current
/// target can make forward process
internal BuildRequest[] OutstandingBuildRequests
{
get
{
return this.outstandingBuildRequests;
}
}
/// <summary>
/// An array of unique identifiers for the targets that generated the build requests (parentBuildRequests)
/// that are blocked until the current target completes. This array can only be calculated given
/// the target information for all the nodes in the system.
/// </summary>
internal TargetIdWrapper[] ParentTargetsForBuildRequests
{
get
{
return this.parentTargetsForBuildRequests;
}
set
{
this.parentTargetsForBuildRequests = value;
}
}
/// <summary>
/// True if the target was requested by the host. The value is only valid for targets on the
/// parent node.
/// </summary>
internal bool RequestedByHost
{
get
{
if (targetId.nodeId == 0)
{
return requestedByHost;
}
return false;
}
}
/// <summary>
/// Name of the project containing the target (only used for logging)
/// </summary>
internal string ProjectName
{
get
{
return projectName;
}
}
#endregion
#region Methods
/// <summary>
/// Given a build state try to find the parent target that caused this build state to
/// come into being either via dependent, on error relationship or via IBuildEngine call
/// </summary>
internal TargetIdWrapper FindParentTarget
(
EngineCallback engineCallback,
ProjectBuildState buildContext,
Target target,
out BuildRequest parentRequest
)
{
// We need to find the parent target
parentRequest = null;
// Skip build states that have already been filled
if (buildContext.CurrentBuildContextState == ProjectBuildState.BuildContextState.RequestFilled)
{
return null;
}
// Check if the target was called due to a onerror or depends on call
if (buildContext.ContainsBlockingTarget(target.Name))
{
// Figure out the record for the parent target
Project containingProject = target.ParentProject;
Target parentTarget = containingProject.Targets[buildContext.GetParentTarget(target.Name)];
return new TargetIdWrapper(parentTarget);
}
else
{
// The build context must have formed due to IBuildEngine call
ErrorUtilities.VerifyThrow(
String.Compare(EscapingUtilities.UnescapeAll(buildContext.NameOfTargetInProgress), target.Name, StringComparison.OrdinalIgnoreCase) == 0,
"The target should be the in progress target for the context");
// This target is called due to IBuildEngine or host request
return FindParentTargetForBuildRequest(engineCallback, buildContext.BuildRequest, out parentRequest);
}
}
/// <summary>
/// Given a build request try to find the target that caused it to come into being
/// </summary>
private TargetIdWrapper FindParentTargetForBuildRequest
(
EngineCallback engineCallback,
BuildRequest triggeringBuildRequest,
out BuildRequest parentTriggeringRequest
)
{
parentTriggeringRequest = null;
// If request is non-external and generated due to IBuildEngine call try
// to find the target that caused the IBuildEngine call
if (triggeringBuildRequest.IsGeneratedRequest && !triggeringBuildRequest.IsExternalRequest)
{
ExecutionContext executionContext =
engineCallback.GetExecutionContextFromHandleId(triggeringBuildRequest.HandleId);
// If the parent context is not a routing context than we can
// get the parent target from it
if (executionContext is TaskExecutionContext)
{
return new TargetIdWrapper(((TaskExecutionContext)executionContext).ParentTarget);
}
// If the parent context if a routing context the parent target is not available
// on the current node, so store the request instead
else
{
parentTriggeringRequest = triggeringBuildRequest;
}
}
// If the request is external to the node - store the request since the parent target
// is not available
else if (triggeringBuildRequest.IsExternalRequest)
{
parentTriggeringRequest = triggeringBuildRequest;
}
else
{
requestedByHost = true;
}
return null;
}
/// <summary>
/// This function checks if the given ProjectBuildState is caused by a given parent target (via
/// a dependency, onerror or IBuildEngine relationship)
/// </summary>
internal bool CheckBuildContextForParentMatch
(
EngineCallback engineCallback,
TargetIdWrapper parentId,
Target target,
ProjectBuildState projectBuildState
)
{
BuildRequest parentRequest = null;
TargetInProgessState.TargetIdWrapper parentName =
FindParentTarget(engineCallback, projectBuildState, target, out parentRequest);
if (parentName != null && parentName.Equals(parentId))
{
return true;
}
if (parentRequest != null)
{
for (int j = 0; j < parentBuildRequests.Count; j++)
{
if (parentRequest.HandleId == parentBuildRequests[j].HandleId &&
parentRequest.RequestId == parentBuildRequests[j].RequestId)
{
if (parentTargetsForBuildRequests[j].Equals(parentId))
{
return true;
}
else
{
return false;
}
}
}
}
return false;
}
#endregion
#region Data
// Unique identifier for the target
TargetIdWrapper targetId;
// List of targets waiting on the current target
List<TargetIdWrapper> parentTargets;
// List of build requests waiting on the current target
List<BuildRequest> parentBuildRequests;
// List of the build requests the target is waiting on
BuildRequest[] outstandingBuildRequests;
// Mapping between list of build requests waiting on the current target and targets
// from which these build reuquests originated
TargetIdWrapper [] parentTargetsForBuildRequests;
// Name of the project containing the target (only used for logging)
string projectName;
// Set to true if the target had a been requested by host (direct requests from host only occur on
// parent node)
bool requestedByHost;
#endregion
#region CustomSerializationToStream
internal void WriteToStream(BinaryWriter writer)
{
#region TargetId
if (targetId == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
targetId.WriteToStream(writer);
}
#endregion
#region ParentTargets
if (parentTargets == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
writer.Write((Int32)parentTargets.Count);
foreach (TargetIdWrapper target in parentTargets)
{
if (target == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
target.WriteToStream(writer);
}
}
}
#endregion
#region ParentBuildRequests
if (parentBuildRequests == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
writer.Write((Int32)parentBuildRequests.Count);
foreach (BuildRequest request in parentBuildRequests)
{
if (request == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
request.WriteToStream(writer);
}
}
}
#endregion
#region OutstandingBuildRequests
if (outstandingBuildRequests == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
writer.Write((Int32)outstandingBuildRequests.Length);
for (int i = 0; i < outstandingBuildRequests.Length; i++)
{
if (outstandingBuildRequests[i] == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
outstandingBuildRequests[i].WriteToStream(writer);
}
}
}
#endregion
#region ParentTargetsForBuildRequests
if (parentTargetsForBuildRequests == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
writer.Write((Int32)parentTargetsForBuildRequests.Length);
for (int i = 0; i < parentTargetsForBuildRequests.Length; i++)
{
if (parentTargetsForBuildRequests[i] == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
parentTargetsForBuildRequests[i].WriteToStream(writer);
}
}
}
#endregion
#region ProjectName
if (projectName == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
writer.Write(projectName);
}
#endregion
}
internal void CreateFromStream(BinaryReader reader)
{
#region TargetId
if (reader.ReadByte() == 0)
{
targetId = null;
}
else
{
targetId = new TargetIdWrapper();
targetId.CreateFromStream(reader);
}
#endregion
#region ParentTargets
if (reader.ReadByte() == 0)
{
parentTargets = null;
}
else
{
int numberOfTargets = reader.ReadInt32();
parentTargets = new List<TargetIdWrapper>(numberOfTargets);
for (int i = 0; i < numberOfTargets; i++)
{
if (reader.ReadByte() == 0)
{
parentTargets.Add(null);
}
else
{
TargetIdWrapper wrapper = new TargetIdWrapper();
wrapper.CreateFromStream(reader);
parentTargets.Add(wrapper);
}
}
}
#endregion
#region ParentBuildRequests
if (reader.ReadByte() == 0)
{
parentBuildRequests = null;
}
else
{
int numberOfRequests = reader.ReadInt32();
parentBuildRequests = new List<BuildRequest>(numberOfRequests);
for (int i = 0; i < numberOfRequests; i++)
{
if (reader.ReadByte() == 0)
{
parentBuildRequests.Add(null);
}
else
{
parentBuildRequests.Add(BuildRequest.CreateFromStream(reader));
}
}
}
#endregion
#region OutstandingBuildRequests
if (reader.ReadByte() == 0)
{
outstandingBuildRequests = null;
}
else
{
int numberOfBuildRequests = reader.ReadInt32();
outstandingBuildRequests = new BuildRequest[numberOfBuildRequests];
for (int i = 0; i < numberOfBuildRequests; i++)
{
if (reader.ReadByte() == 0)
{
outstandingBuildRequests[i] = null;
}
else
{
outstandingBuildRequests[i] = BuildRequest.CreateFromStream(reader);
}
}
}
#endregion
#region ParentTargetsForBuildRequests
if (reader.ReadByte() == 0)
{
parentTargetsForBuildRequests = null;
}
else
{
int numberOfTargetsForBuildRequests = reader.ReadInt32();
parentTargetsForBuildRequests = new TargetIdWrapper[numberOfTargetsForBuildRequests];
for (int i = 0; i < numberOfTargetsForBuildRequests; i++)
{
if (reader.ReadByte() == 0)
{
parentTargetsForBuildRequests[i] = null;
}
else
{
TargetIdWrapper wrapper = new TargetIdWrapper();
wrapper.CreateFromStream(reader);
parentTargetsForBuildRequests[i] = wrapper;
}
}
}
#endregion
#region ProjectName
if (reader.ReadByte() == 0)
{
projectName = null;
}
else
{
projectName = reader.ReadString();
}
#endregion
}
#endregion
/// <summary>
/// A class that contains information to uniquely identify a target
/// </summary>
internal class TargetIdWrapper
{
internal TargetIdWrapper()
{
}
internal TargetIdWrapper(Target target)
{
this.name = target.Name;
this.projectId = target.ParentProject.Id;
this.nodeId = target.ParentEngine.NodeId;
this.id = target.Id;
}
/// <summary>
/// Override the equals operator to give valuetype comparison semantics
/// </summary>
public override bool Equals(object obj)
{
TargetIdWrapper other = obj as TargetIdWrapper;
if (other != null)
{
if (other.projectId == projectId && other.nodeId == nodeId &&
(String.Compare(other.name, name, StringComparison.OrdinalIgnoreCase) == 0))
{
return true;
}
return false;
}
return base.Equals(obj);
}
public override int GetHashCode()
{
return projectId;
}
// Target name
internal string name;
// Id for the parent project
internal int projectId;
// Id for the node where the target exists
internal int nodeId;
// Target Id
internal int id;
#region CustomSerializationToStream
internal void WriteToStream(BinaryWriter writer)
{
if (name == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
writer.Write(name);
}
writer.Write((Int32)projectId);
writer.Write((Int32)nodeId);
writer.Write((Int32)id);
}
internal void CreateFromStream(BinaryReader reader)
{
if (reader.ReadByte() == 0)
{
name = null;
}
else
{
name = reader.ReadString();
}
projectId = reader.ReadInt32();
nodeId = reader.ReadInt32();
id = reader.ReadInt32();
}
#endregion
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2015 FUJIWARA, Yusuke
//
// 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 -- License Terms --
#if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
#if !UNITY
#if XAMIOS || XAMDROID
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // XAMIOS || XAMDROID
#endif // !UNITY
using System.Globalization;
using System.Linq;
using System.Reflection;
using MsgPack.Serialization.Reflection;
namespace MsgPack.Serialization
{
internal static class ReflectionExtensions
{
private static readonly Type[] ExceptionConstructorWithInnerParameterTypes = { typeof( string ), typeof( Exception ) };
public static object InvokePreservingExceptionType( this ConstructorInfo source, params object[] parameters )
{
try
{
return source.Invoke( parameters );
}
catch ( TargetInvocationException ex )
{
var rethrowing = HoistUpInnerException( ex );
if ( rethrowing == null )
{
// ctor.Invoke threw exception, so rethrow original TIE.
throw;
}
else
{
throw rethrowing;
}
}
}
public static object InvokePreservingExceptionType( this MethodInfo source, object instance, params object[] parameters )
{
try
{
return source.Invoke( instance, parameters );
}
catch ( TargetInvocationException ex )
{
var rethrowing = HoistUpInnerException( ex );
if ( rethrowing == null )
{
// ctor.Invoke threw exception, so rethrow original TIE.
throw;
}
else
{
throw rethrowing;
}
}
}
public static T CreateInstancePreservingExceptionType<T>( Type instanceType, params object[] constructorParameters )
{
return ( T )CreateInstancePreservingExceptionType( instanceType, constructorParameters );
}
public static object CreateInstancePreservingExceptionType( Type type, params object[] constructorParameters )
{
try
{
return Activator.CreateInstance( type, constructorParameters );
}
catch ( TargetInvocationException ex )
{
var rethrowing = HoistUpInnerException( ex );
if ( rethrowing == null )
{
// ctor.Invoke threw exception, so rethrow original TIE.
throw;
}
else
{
throw rethrowing;
}
}
}
private static Exception HoistUpInnerException( TargetInvocationException targetInvocationException )
{
if ( targetInvocationException.InnerException == null )
{
return null;
}
var ctor = targetInvocationException.InnerException.GetType().GetConstructor( ExceptionConstructorWithInnerParameterTypes );
if ( ctor == null )
{
return null;
}
try
{
return ctor.Invoke( new object[] { targetInvocationException.InnerException.Message, targetInvocationException } ) as Exception;
}
#if !UNITY || MSGPACK_UNITY_FULL
catch ( Exception ex )
#else
catch ( Exception )
#endif // !UNITY || MSGPACK_UNITY_FULL
{
#if !UNITY || MSGPACK_UNITY_FULL
Debug.WriteLine( "HoistUpInnerException:" + ex );
#endif // !UNITY || MSGPACK_UNITY_FULL
return null;
}
}
public static Type GetMemberValueType( this MemberInfo source )
{
if ( source == null )
{
throw new ArgumentNullException( "source" );
}
var asProperty = source as PropertyInfo;
var asField = source as FieldInfo;
if ( asProperty == null && asField == null )
{
throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "'{0}'({1}) is not field nor property.", source, source.GetType() ) );
}
return asProperty != null ? asProperty.PropertyType : asField.FieldType;
}
public static CollectionTraits GetCollectionTraits( this Type source )
{
#if !UNITY && DEBUG
Contract.Assert( !source.GetContainsGenericParameters(), "!source.GetContainsGenericParameters()" );
#endif // !UNITY
/*
* SPEC
* If the object has single public method TEnumerator GetEnumerator() ( where TEnumerator implements IEnumerator<TItem>),
* then the object is considered as the collection of TItem.
* When the object is considered as the collection of TItem, TItem is KeyValuePair<TKey,TValue>,
* and the object implements IDictionary<TKey,TValue>, then the object is considered as dictionary of TKey and TValue.
* Else, if the object has single public method IEnumerator GetEnumerator(), then the object is considered as the collection of Object.
* When it also implements IDictionary, however, it is considered dictionary of Object and Object.
* Otherwise, that means it implements multiple collection interface, is following.
* First, if the object implements IDictionary<MessagePackObject,MessagePackObject>, then it is considered as MPO dictionary.
* Second, if the object implements IEnumerable<MPO>, then it is considered as MPO dictionary.
* Third, if the object implement SINGLE IDictionary<TKey,TValue> and multiple IEnumerable<T>, then it is considered as dictionary of TKey and TValue.
* Fourth, the object is considered as UNSERIALIZABLE member. This behavior similer to DataContract serialization behavor
* (see http://msdn.microsoft.com/en-us/library/aa347850.aspx ).
*/
if ( !source.IsAssignableTo( typeof( IEnumerable ) ) )
{
return CollectionTraits.NotCollection;
}
if ( source.IsArray )
{
return
new CollectionTraits(
CollectionDetailedKind.Array,
null, // Add() : Never used for array.
null, // get_Count() : Never used for array.
null, // GetEnumerator() : Never used for array.
source.GetElementType()
);
}
var getEnumerator = source.GetMethod( "GetEnumerator", ReflectionAbstractions.EmptyTypes );
if ( getEnumerator != null && getEnumerator.ReturnType.IsAssignableTo( typeof( IEnumerator ) ) )
{
// If public 'GetEnumerator' is found, it is primary collection traits.
CollectionTraits result;
if ( TryCreateCollectionTraitsForHasGetEnumeratorType( source, getEnumerator, out result ) )
{
return result;
}
}
Type ienumerableT = null;
Type icollectionT = null;
#if !NETFX_35 && !UNITY
Type isetT = null;
#endif // !NETFX_35 && !UNITY
Type ilistT = null;
Type idictionaryT = null;
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
Type ireadOnlyCollectionT = null;
Type ireadOnlyListT = null;
Type ireadOnlyDictionaryT = null;
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
Type ienumerable = null;
Type icollection = null;
Type ilist = null;
Type idictionary = null;
var sourceInterfaces = source.FindInterfaces( FilterCollectionType, null );
if ( source.GetIsInterface() && FilterCollectionType( source, null ) )
{
var originalSourceInterfaces = sourceInterfaces.ToArray();
var concatenatedSourceInterface = new Type[ originalSourceInterfaces.Length + 1 ];
concatenatedSourceInterface[ 0 ] = source;
for ( int i = 0; i < originalSourceInterfaces.Length; i++ )
{
concatenatedSourceInterface[ i + 1 ] = originalSourceInterfaces[ i ];
}
sourceInterfaces = concatenatedSourceInterface;
}
foreach ( var type in sourceInterfaces )
{
CollectionTraits result;
if ( TryCreateGenericCollectionTraits( source, type, out result ) )
{
return result;
}
if ( !DetermineCollectionInterfaces(
type,
ref idictionaryT,
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
ref ireadOnlyDictionaryT,
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
ref ilistT,
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
ref ireadOnlyListT,
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
#if !NETFX_35 && !UNITY
ref isetT,
#endif // !NETFX_35 && !UNITY
ref icollectionT,
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
ref ireadOnlyCollectionT,
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
ref ienumerableT,
ref idictionary,
ref ilist,
ref icollection,
ref ienumerable
)
)
{
return CollectionTraits.Unserializable;
}
}
if ( idictionaryT != null )
{
var elementType = typeof( KeyValuePair<,> ).MakeGenericType( idictionaryT.GetGenericArguments() );
return
new CollectionTraits(
CollectionDetailedKind.GenericDictionary,
GetAddMethod( source, idictionaryT.GetGenericArguments()[ 0 ], idictionaryT.GetGenericArguments()[ 1 ] ),
GetCountGetterMethod( source, elementType ),
FindInterfaceMethod( source, typeof( IEnumerable<> ).MakeGenericType( elementType ), "GetEnumerator", ReflectionAbstractions.EmptyTypes ),
elementType
);
}
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
if ( ireadOnlyDictionaryT != null )
{
var elementType = typeof( KeyValuePair<,> ).MakeGenericType( ireadOnlyDictionaryT.GetGenericArguments() );
return
new CollectionTraits(
CollectionDetailedKind.GenericReadOnlyDictionary,
null,
GetCountGetterMethod( source, elementType ),
FindInterfaceMethod( source, typeof( IEnumerable<> ).MakeGenericType( elementType ), "GetEnumerator", ReflectionAbstractions.EmptyTypes ),
elementType
);
}
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
if ( ienumerableT != null )
{
var elementType = ienumerableT.GetGenericArguments()[ 0 ];
return
new CollectionTraits(
( ilistT != null )
? CollectionDetailedKind.GenericList
#if !NETFX_35 && !UNITY
: ( isetT != null )
? CollectionDetailedKind.GenericSet
#endif // !NETFX_35 && !UNITY
: ( icollectionT != null )
? CollectionDetailedKind.GenericCollection
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
: ( ireadOnlyListT != null )
? CollectionDetailedKind.GenericReadOnlyList
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
: ( ireadOnlyCollectionT != null )
? CollectionDetailedKind.GenericReadOnlyCollection
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
: CollectionDetailedKind.GenericEnumerable,
GetAddMethod( source, elementType ),
GetCountGetterMethod( source, elementType ),
FindInterfaceMethod( source, ienumerableT, "GetEnumerator", ReflectionAbstractions.EmptyTypes ),
elementType
);
}
if ( idictionary != null )
{
return
new CollectionTraits(
CollectionDetailedKind.NonGenericDictionary,
GetAddMethod( source, typeof( object ), typeof( object ) ),
GetCountGetterMethod( source, typeof( object ) ),
FindInterfaceMethod( source, idictionary, "GetEnumerator", ReflectionAbstractions.EmptyTypes ),
typeof( object )
);
}
if ( ienumerable != null )
{
var addMethod = GetAddMethod( source, typeof( object ) );
if ( addMethod != null )
{
return
new CollectionTraits(
( ilist != null )
? CollectionDetailedKind.NonGenericList
: ( icollection != null )
? CollectionDetailedKind.NonGenericCollection
: CollectionDetailedKind.NonGenericEnumerable,
addMethod,
GetCountGetterMethod( source, typeof( object ) ),
FindInterfaceMethod( source, ienumerable, "GetEnumerator", ReflectionAbstractions.EmptyTypes ),
typeof( object )
);
}
}
return CollectionTraits.NotCollection;
}
private static bool TryCreateCollectionTraitsForHasGetEnumeratorType(
Type source,
MethodInfo getEnumerator,
out CollectionTraits result
)
{
if ( source.Implements( typeof( IDictionary<,> ) )
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
|| source.Implements( typeof( IReadOnlyDictionary<,> ) )
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
)
{
var ienumetaorT =
getEnumerator.ReturnType.GetInterfaces()
.FirstOrDefault( @interface =>
@interface.GetIsGenericType() && @interface.GetGenericTypeDefinition() == typeof( IEnumerator<> )
);
if ( ienumetaorT != null )
{
var elementType = ienumetaorT.GetGenericArguments()[ 0 ];
{
result = new CollectionTraits(
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
source.Implements( typeof( IDictionary<,> ) )
? CollectionDetailedKind.GenericDictionary
: CollectionDetailedKind.GenericReadOnlyDictionary,
#else
CollectionDetailedKind.GenericDictionary,
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
GetAddMethod( source, elementType.GetGenericArguments()[ 0 ], elementType.GetGenericArguments()[ 1 ] ),
GetCountGetterMethod( source, elementType ),
getEnumerator,
elementType
);
return true;
}
}
}
if ( source.IsAssignableTo( typeof( IDictionary ) ) )
{
{
result = new CollectionTraits(
CollectionDetailedKind.NonGenericDictionary,
GetAddMethod( source, typeof( object ), typeof( object ) ),
GetCountGetterMethod( source, typeof( object ) ),
getEnumerator,
typeof( DictionaryEntry )
);
return true;
}
}
// Block to limit variable scope
{
var ienumetaorT =
IsIEnumeratorT( getEnumerator.ReturnType )
? getEnumerator.ReturnType
: getEnumerator.ReturnType.GetInterfaces().FirstOrDefault( IsIEnumeratorT );
if ( ienumetaorT != null )
{
var elementType = ienumetaorT.GetGenericArguments()[ 0 ];
{
result = new CollectionTraits(
source.Implements( typeof( IList<> ) )
? CollectionDetailedKind.GenericList
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
: source.Implements( typeof( IReadOnlyList<> ) )
? CollectionDetailedKind.GenericReadOnlyList
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
#if !NETFX_35 && !UNITY
: source.Implements( typeof( ISet<> ) )
? CollectionDetailedKind.GenericSet
#endif // !NETFX_35 && !UNITY
: source.Implements( typeof( ICollection<> ) )
? CollectionDetailedKind.GenericCollection
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
: source.Implements( typeof( IReadOnlyCollection<> ) )
? CollectionDetailedKind.GenericReadOnlyCollection
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
: CollectionDetailedKind.GenericEnumerable,
GetAddMethod( source, elementType ),
GetCountGetterMethod( source, elementType ),
getEnumerator,
elementType
);
return true;
}
}
}
result = default( CollectionTraits );
return false;
}
private static bool TryCreateGenericCollectionTraits( Type source, Type type, out CollectionTraits result )
{
if ( type == typeof( IDictionary<MessagePackObject, MessagePackObject> )
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
|| type == typeof( IReadOnlyDictionary<MessagePackObject, MessagePackObject> )
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
)
{
result = new CollectionTraits(
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
( source == typeof( IDictionary<MessagePackObject, MessagePackObject> ) || source.Implements( typeof( IDictionary<MessagePackObject, MessagePackObject> ) ) )
? CollectionDetailedKind.GenericDictionary
: CollectionDetailedKind.GenericReadOnlyDictionary,
#else
CollectionDetailedKind.GenericDictionary,
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
GetAddMethod( source, typeof( MessagePackObject ), typeof( MessagePackObject ) ),
GetCountGetterMethod( source, typeof( KeyValuePair<MessagePackObject, MessagePackObject> ) ),
FindInterfaceMethod(
source,
typeof( IEnumerable<KeyValuePair<MessagePackObject, MessagePackObject>> ),
"GetEnumerator",
ReflectionAbstractions.EmptyTypes
),
typeof( KeyValuePair<MessagePackObject, MessagePackObject> )
);
return true;
}
if ( type == typeof( IEnumerable<MessagePackObject> ) )
{
var addMethod = GetAddMethod( source, typeof( MessagePackObject ) );
if ( addMethod != null )
{
{
result = new CollectionTraits(
( source == typeof( IList<MessagePackObject> ) || source.Implements( typeof( IList<MessagePackObject> ) ) )
? CollectionDetailedKind.GenericList
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
: ( source == typeof( IReadOnlyList<MessagePackObject> ) || source.Implements( typeof( IReadOnlyList<MessagePackObject> ) ) )
? CollectionDetailedKind.GenericReadOnlyList
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
#if !NETFX_35 && !UNITY
: ( source == typeof( ISet<MessagePackObject> ) || source.Implements( typeof( ISet<MessagePackObject> ) ) )
? CollectionDetailedKind.GenericSet
#endif // !NETFX_35 && !UNITY
: ( source == typeof( ICollection<MessagePackObject> ) ||
source.Implements( typeof( ICollection<MessagePackObject> ) ) )
? CollectionDetailedKind.GenericCollection
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
: ( source == typeof( IReadOnlyCollection<MessagePackObject> ) || source.Implements( typeof( IReadOnlyCollection<MessagePackObject> ) ) )
? CollectionDetailedKind.GenericReadOnlyCollection
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
: CollectionDetailedKind.GenericEnumerable,
addMethod,
GetCountGetterMethod( source, typeof( MessagePackObject ) ),
FindInterfaceMethod(
source,
typeof( IEnumerable<MessagePackObject> ),
"GetEnumerator",
ReflectionAbstractions.EmptyTypes
),
typeof( MessagePackObject )
);
return true;
}
}
}
result = default( CollectionTraits );
return false;
}
private static bool DetermineCollectionInterfaces(
Type type,
ref Type idictionaryT,
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
ref Type ireadOnlyDictionaryT,
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
ref Type ilistT,
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
ref Type ireadOnlyListT,
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
#if !NETFX_35 && !UNITY
ref Type isetT,
#endif // !NETFX_35 && !UNITY
ref Type icollectionT,
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
ref Type ireadOnlyCollectionT,
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
ref Type ienumerableT,
ref Type idictionary,
ref Type ilist,
ref Type icollection,
ref Type ienumerable
)
{
if ( type.GetIsGenericType() )
{
var genericTypeDefinition = type.GetGenericTypeDefinition();
if ( genericTypeDefinition == typeof( IDictionary<,> ) )
{
if ( idictionaryT != null )
{
return false;
}
idictionaryT = type;
}
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
else if ( genericTypeDefinition == typeof( IReadOnlyDictionary<,> ) )
{
if ( ireadOnlyDictionaryT != null )
{
return false;
}
ireadOnlyDictionaryT = type;
}
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
else if ( genericTypeDefinition == typeof( IList<> ) )
{
if ( ilistT != null )
{
return false;
}
ilistT = type;
}
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
else if ( genericTypeDefinition == typeof( IReadOnlyList<> ) )
{
if ( ireadOnlyListT != null )
{
return false;
}
ireadOnlyListT = type;
}
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
#if !NETFX_35 && !UNITY
else if ( genericTypeDefinition == typeof( ISet<> ) )
{
if ( isetT != null )
{
return false;
}
isetT = type;
}
#endif // !NETFX_35 && !UNITY
else if ( genericTypeDefinition == typeof( ICollection<> ) )
{
if ( icollectionT != null )
{
return false;
}
icollectionT = type;
}
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
else if ( genericTypeDefinition == typeof( IReadOnlyCollection<> ) )
{
if ( ireadOnlyCollectionT != null )
{
return false;
}
ireadOnlyCollectionT = type;
}
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
else if ( genericTypeDefinition == typeof( IEnumerable<> ) )
{
if ( ienumerableT != null )
{
return false;
}
ienumerableT = type;
}
}
else
{
if ( type == typeof( IDictionary ) )
{
idictionary = type;
}
else if ( type == typeof( IList ) )
{
ilist = type;
}
else if ( type == typeof( ICollection ) )
{
icollection = type;
}
else if ( type == typeof( IEnumerable ) )
{
ienumerable = type;
}
}
return true;
}
private static MethodInfo FindInterfaceMethod( Type targetType, Type interfaceType, string name, Type[] parameterTypes )
{
if ( targetType.GetIsInterface() )
{
return targetType.FindInterfaces( ( type, _ ) => type == interfaceType, null ).Single().GetMethod( name, parameterTypes );
}
var map = targetType.GetInterfaceMap( interfaceType );
#if !SILVERLIGHT || WINDOWS_PHONE
int index = Array.FindIndex( map.InterfaceMethods, method => method.Name == name && method.GetParameters().Select( p => p.ParameterType ).SequenceEqual( parameterTypes ) );
#else
int index = map.InterfaceMethods.FindIndex( method => method.Name == name && method.GetParameters().Select( p => p.ParameterType ).SequenceEqual( parameterTypes ) );
#endif
if ( index < 0 )
{
#if DEBUG && !UNITY
#if !NETFX_35
Contract.Assert( false, interfaceType + "::" + name + "(" + String.Join<Type>( ", ", parameterTypes ) + ") is not found in " + targetType );
#else
Contract.Assert( false, interfaceType + "::" + name + "(" + String.Join( ", ", parameterTypes.Select( t => t.ToString() ).ToArray() ) + ") is not found in " + targetType );
#endif // !NETFX_35
#endif // DEBUG && !UNITY
// ReSharper disable once HeuristicUnreachableCode
return null;
}
return map.TargetMethods[ index ];
}
private static MethodInfo GetAddMethod( Type targetType, Type argumentType )
{
var argumentTypes = new[] { argumentType };
var result = targetType.GetMethod( "Add", argumentTypes );
if ( result != null )
{
return result;
}
var icollectionT = typeof( ICollection<> ).MakeGenericType( argumentType );
if ( targetType.IsAssignableTo( icollectionT ) )
{
return icollectionT.GetMethod( "Add", argumentTypes );
}
if ( targetType.IsAssignableTo( typeof( IList ) ) )
{
return typeof( IList ).GetMethod( "Add", new[] { typeof( object ) } );
}
return null;
}
private static MethodInfo GetCountGetterMethod( Type targetType, Type elementType )
{
var result = targetType.GetProperty( "Count" );
if ( result != null && result.GetHasPublicGetter() )
{
return result.GetGetMethod();
}
var icollectionT = typeof( ICollection<> ).MakeGenericType( elementType );
if ( targetType.IsAssignableTo( icollectionT ) )
{
return icollectionT.GetProperty( "Count" ).GetGetMethod();
}
#if !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
var ireadOnlyCollectionT = typeof( IReadOnlyCollection<> ).MakeGenericType( elementType );
if ( targetType.IsAssignableTo( ireadOnlyCollectionT ) )
{
return ireadOnlyCollectionT.GetProperty( "Count" ).GetGetMethod();
}
#endif // !NETFX_35 && !UNITY && !NETFX_40 && !( SILVERLIGHT && !WINDOWS_PHONE )
if ( targetType.IsAssignableTo( typeof( ICollection ) ) )
{
return typeof( ICollection ).GetProperty( "Count" ).GetGetMethod();
}
return null;
}
private static MethodInfo GetAddMethod( Type targetType, Type keyType, Type valueType )
{
var argumentTypes = new[] { keyType, valueType };
var result = targetType.GetMethod( "Add", argumentTypes );
if ( result != null )
{
return result;
}
return typeof( IDictionary<,> ).MakeGenericType( argumentTypes ).GetMethod( "Add", argumentTypes );
}
private static bool FilterCollectionType( Type type, object filterCriteria )
{
#if !NETFX_CORE
#if !UNITY
Contract.Assert( type.IsInterface, "type.IsInterface" );
#endif // !UNITY
return type.Assembly.Equals( typeof( Array ).Assembly ) && ( type.Namespace == "System.Collections" || type.Namespace == "System.Collections.Generic" );
#else
var typeInfo = type.GetTypeInfo();
Contract.Assert( typeInfo.IsInterface );
return typeInfo.Assembly.Equals( typeof( Array ).GetTypeInfo().Assembly ) && ( type.Namespace == "System.Collections" || type.Namespace == "System.Collections.Generic" );
#endif // !NETFX_CORE
}
private static bool IsIEnumeratorT( Type @interface )
{
return @interface.GetIsGenericType() && @interface.GetGenericTypeDefinition() == typeof( IEnumerator<> );
}
#if WINDOWS_PHONE
public static IEnumerable<Type> FindInterfaces( this Type source, Func<Type, object, bool> filter, object criterion )
{
foreach ( var @interface in source.GetInterfaces() )
{
if ( filter( @interface, criterion ) )
{
yield return @interface;
}
}
}
#endif
public static bool GetHasPublicGetter( this MemberInfo source )
{
PropertyInfo asProperty;
FieldInfo asField;
if ( ( asProperty = source as PropertyInfo ) != null )
{
#if !NETFX_CORE
return asProperty.GetGetMethod() != null;
#else
return ( asProperty.GetMethod != null && asProperty.GetMethod.IsPublic );
#endif
}
else if ( ( asField = source as FieldInfo ) != null )
{
return asField.IsPublic;
}
else
{
throw new NotSupportedException( source.GetType() + " is not supported." );
}
}
public static bool GetHasPublicSetter( this MemberInfo source )
{
PropertyInfo asProperty;
FieldInfo asField;
if ( ( asProperty = source as PropertyInfo ) != null )
{
#if !NETFX_CORE
return asProperty.GetSetMethod() != null;
#else
return ( asProperty.SetMethod != null && asProperty.SetMethod.IsPublic );
#endif
}
else if ( ( asField = source as FieldInfo ) != null )
{
return asField.IsPublic && !asField.IsInitOnly && !asField.IsLiteral;
}
else
{
throw new NotSupportedException( source.GetType() + " is not supported." );
}
}
public static bool GetIsPublic( this MemberInfo source )
{
PropertyInfo asProperty;
FieldInfo asField;
MethodBase asMethod;
#if !NETFX_CORE
Type asType;
#endif
if ( ( asProperty = source as PropertyInfo ) != null )
{
#if !NETFX_CORE
return asProperty.GetAccessors( true ).Where( a => a.ReturnType != typeof( void ) ).All( a => a.IsPublic );
#else
return
( asProperty.GetMethod == null || asProperty.GetMethod.IsPublic );
#endif
}
else if ( ( asField = source as FieldInfo ) != null )
{
return asField.IsPublic;
}
else if ( ( asMethod = source as MethodBase ) != null )
{
return asMethod.IsPublic;
}
#if !NETFX_CORE
else if ( ( asType = source as Type ) != null )
{
return asType.IsPublic;
}
#endif
else
{
throw new NotSupportedException( source.GetType() + " is not supported." );
}
}
public static bool GetIsVisible( this Type source )
{
#if !NETFX_CORE
return source.IsVisible;
#else
return source.GetTypeInfo().IsVisible;
#endif
}
}
}
| |
// 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.Globalization;
using Xunit;
public static class UInt64Tests
{
[Fact]
public static void TestCtor()
{
UInt64 i = new UInt64();
Assert.True(i == 0);
i = 41;
Assert.True(i == 41);
}
[Fact]
public static void TestMaxValue()
{
UInt64 max = UInt64.MaxValue;
Assert.True(max == (UInt64)0xFFFFFFFFFFFFFFFF);
}
[Fact]
public static void TestMinValue()
{
UInt64 min = UInt64.MinValue;
Assert.True(min == 0);
}
[Fact]
public static void TestCompareToObject()
{
UInt64 i = 234;
IComparable comparable = i;
Assert.Equal(1, comparable.CompareTo(null));
Assert.Equal(0, comparable.CompareTo((UInt64)234));
Assert.True(comparable.CompareTo(UInt64.MinValue) > 0);
Assert.True(comparable.CompareTo((UInt64)0) > 0);
Assert.True(comparable.CompareTo((UInt64)(23)) > 0);
Assert.True(comparable.CompareTo((UInt64)123) > 0);
Assert.True(comparable.CompareTo((UInt64)456) < 0);
Assert.True(comparable.CompareTo(UInt64.MaxValue) < 0);
Assert.Throws<ArgumentException>(() => comparable.CompareTo("a"));
}
[Fact]
public static void TestCompareTo()
{
UInt64 i = 234;
Assert.Equal(0, i.CompareTo((UInt64)234));
Assert.True(i.CompareTo(UInt64.MinValue) > 0);
Assert.True(i.CompareTo((UInt64)0) > 0);
Assert.True(i.CompareTo((UInt64)123) > 0);
Assert.True(i.CompareTo((UInt64)456) < 0);
Assert.True(i.CompareTo(UInt64.MaxValue) < 0);
}
[Fact]
public static void TestEqualsObject()
{
UInt64 i = 789;
object obj1 = (UInt64)789;
Assert.True(i.Equals(obj1));
object obj3 = (UInt64)0;
Assert.True(!i.Equals(obj3));
}
[Fact]
public static void TestEquals()
{
UInt64 i = 911;
Assert.True(i.Equals((UInt64)911));
Assert.True(!i.Equals((UInt64)0));
}
[Fact]
public static void TestGetHashCode()
{
UInt64 i1 = 123;
UInt64 i2 = 654;
Assert.NotEqual(0, i1.GetHashCode());
Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode());
}
[Fact]
public static void TestToString()
{
UInt64 i1 = 6310;
Assert.Equal("6310", i1.ToString());
}
[Fact]
public static void TestToStringFormatProvider()
{
var numberFormat = new System.Globalization.NumberFormatInfo();
UInt64 i1 = 6310;
Assert.Equal("6310", i1.ToString(numberFormat));
}
[Fact]
public static void TestToStringFormat()
{
UInt64 i1 = 6310;
Assert.Equal("6310", i1.ToString("G"));
UInt64 i2 = 8249;
Assert.Equal("8249", i2.ToString("g"));
UInt64 i3 = 2468;
Assert.Equal(string.Format("{0:N}", 2468.00), i3.ToString("N"));
UInt64 i4 = 0x248;
Assert.Equal("248", i4.ToString("x"));
}
[Fact]
public static void TestToStringFormatFormatProvider()
{
var numberFormat = new System.Globalization.NumberFormatInfo();
UInt64 i1 = 6310;
Assert.Equal("6310", i1.ToString("G", numberFormat));
UInt64 i2 = 8249;
Assert.Equal("8249", i2.ToString("g", numberFormat));
numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up
numberFormat.NumberGroupSeparator = "*";
numberFormat.NumberNegativePattern = 0;
UInt64 i3 = 2468;
Assert.Equal("2*468.00", i3.ToString("N", numberFormat));
}
[Fact]
public static void TestParse()
{
Assert.Equal<UInt64>(123, UInt64.Parse("123"));
//TODO: Negative tests once we get better exceptions
}
[Fact]
public static void TestParseNumberStyle()
{
Assert.Equal<UInt64>(0x123, UInt64.Parse("123", NumberStyles.HexNumber));
Assert.Equal<UInt64>(1000, UInt64.Parse((1000).ToString("N0"), NumberStyles.AllowThousands));
//TODO: Negative tests once we get better exceptions
}
[Fact]
public static void TestParseFormatProvider()
{
var nfi = new NumberFormatInfo();
Assert.Equal<UInt64>(123, UInt64.Parse("123", nfi));
//TODO: Negative tests once we get better exceptions
}
[Fact]
public static void TestParseNumberStyleFormatProvider()
{
var nfi = new NumberFormatInfo();
Assert.Equal<UInt64>(0x123, UInt64.Parse("123", NumberStyles.HexNumber, nfi));
nfi.CurrencySymbol = "$";
Assert.Equal<UInt64>(1000, UInt64.Parse("$1,000", NumberStyles.Currency, nfi));
//TODO: Negative tests once we get better exception support
}
[Fact]
public static void TestTryParse()
{
// Defaults NumberStyles.Integer = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign
UInt64 i;
Assert.True(UInt64.TryParse("123", out i)); // Simple
Assert.Equal<UInt64>(123, i);
Assert.False(UInt64.TryParse("-385", out i)); // LeadingSign negative
Assert.True(UInt64.TryParse(" 678 ", out i)); // Leading/Trailing whitespace
Assert.Equal<UInt64>(678, i);
var nfi = new NumberFormatInfo() { CurrencyGroupSeparator = "" };
Assert.False(UInt64.TryParse((1000).ToString("C0", nfi), out i)); // Currency
Assert.False(UInt64.TryParse((1000).ToString("N0"), out i)); // Thousands
Assert.False(UInt64.TryParse("abc", out i)); // Hex digits
Assert.False(UInt64.TryParse((678.90).ToString("F2"), out i)); // Decimal
Assert.False(UInt64.TryParse("(135)", out i)); // Parentheses
Assert.False(UInt64.TryParse("1E23", out i)); // Exponent
}
[Fact]
public static void TestTryParseNumberStyleFormatProvider()
{
UInt64 i;
var nfi = new NumberFormatInfo();
Assert.True(UInt64.TryParse("123", NumberStyles.Any, nfi, out i)); // Simple positive
Assert.Equal<UInt64>(123, i);
Assert.True(UInt64.TryParse("123", NumberStyles.HexNumber, nfi, out i)); // Simple Hex
Assert.Equal<UInt64>(0x123, i);
nfi.CurrencySymbol = "$";
nfi.CurrencyGroupSeparator = ",";
Assert.True(UInt64.TryParse("$1,000", NumberStyles.Currency, nfi, out i)); // Currency/Thousands postive
Assert.Equal<UInt64>(1000, i);
Assert.False(UInt64.TryParse("abc", NumberStyles.None, nfi, out i)); // Hex Number negative
Assert.True(UInt64.TryParse("abc", NumberStyles.HexNumber, nfi, out i)); // Hex Number positive
Assert.Equal<UInt64>(0xabc, i);
nfi.NumberDecimalSeparator = ".";
Assert.False(UInt64.TryParse("678.90", NumberStyles.Integer, nfi, out i)); // Decimal
Assert.False(UInt64.TryParse(" 678 ", NumberStyles.None, nfi, out i)); // Trailing/Leading whitespace negative
Assert.False(UInt64.TryParse("(135)", NumberStyles.AllowParentheses, nfi, out i)); // Parenthese negative
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
static Program()
{
TestList = new Dictionary<string, Action>() {
["MultipleSumAbsoluteDifferences"] = MultipleSumAbsoluteDifferences
};
}
private static void MultipleSumAbsoluteDifferences()
{
var test = new SimpleBinaryOpTest__MultipleSumAbsoluteDifferences();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MultipleSumAbsoluteDifferences
{
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Byte[] _data2 = new Byte[Op2ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<UInt16, Byte, Byte> _dataTable;
static SimpleBinaryOpTest__MultipleSumAbsoluteDifferences()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleBinaryOpTest__MultipleSumAbsoluteDifferences()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt16, Byte, Byte>(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
const byte imm8 = 0;
var result = Sse41.MultipleSumAbsoluteDifferences(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr),
imm8
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, imm8, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
const byte imm8 = 1;
var result = Sse41.MultipleSumAbsoluteDifferences(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)),
imm8
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, imm8, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
const byte imm8 = 2;
var result = Sse41.MultipleSumAbsoluteDifferences(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)),
imm8
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, imm8, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
const byte imm8 = 3;
var result = typeof(Sse41).GetMethod(nameof(Sse41.MultipleSumAbsoluteDifferences), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(Byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr),
imm8
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, imm8, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
const byte imm8 = 4;
var result = typeof(Sse41).GetMethod(nameof(Sse41.MultipleSumAbsoluteDifferences), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(Byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)),
imm8
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, imm8, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
const byte imm8 = 5;
var result = typeof(Sse41).GetMethod(nameof(Sse41.MultipleSumAbsoluteDifferences), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>), typeof(Byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)),
imm8
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, imm8, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
const byte imm8 = 6;
var result = Sse41.MultipleSumAbsoluteDifferences(
_clsVar1,
_clsVar2,
imm8
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, imm8, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
const byte imm8 = 7;
var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse41.MultipleSumAbsoluteDifferences(left, right, imm8);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, imm8, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
const byte imm8 = 8;
var left = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse41.MultipleSumAbsoluteDifferences(left, right, imm8);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, imm8, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
const byte imm8 = 9;
var left = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse41.MultipleSumAbsoluteDifferences(left, right, imm8);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, imm8, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
const byte imm8 = 10;
var test = new SimpleBinaryOpTest__MultipleSumAbsoluteDifferences();
var result = Sse41.MultipleSumAbsoluteDifferences(test._fld1, test._fld2, imm8);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, imm8, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
const byte imm8 = 11;
var result = Sse41.MultipleSumAbsoluteDifferences(_fld1, _fld2, imm8);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, imm8, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Byte> left, Vector128<Byte> right, byte imm8, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, imm8, outArray, method);
}
private void ValidateResult(void* left, void* right, byte imm8, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] inArray2 = new Byte[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>());
ValidateResult(inArray1, inArray2, imm8, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, byte imm8, UInt16[] result, [CallerMemberName] string method = "")
{
var srcOffset = ((imm8 & 0x3) * 32) / 8;
var dstOffset = (((imm8 & 0x4) >> 2) * 32) / 8;
if (result[0] != Math.Abs(left[dstOffset + 0] - right[srcOffset + 0]) +
Math.Abs(left[dstOffset + 1] - right[srcOffset + 1]) +
Math.Abs(left[dstOffset + 2] - right[srcOffset + 2]) +
Math.Abs(left[dstOffset + 3] - right[srcOffset + 3]))
{
Succeeded = false;
}
else if (result[1] != Math.Abs(left[dstOffset + 1] - right[srcOffset + 0]) +
Math.Abs(left[dstOffset + 2] - right[srcOffset + 1]) +
Math.Abs(left[dstOffset + 3] - right[srcOffset + 2]) +
Math.Abs(left[dstOffset + 4] - right[srcOffset + 3]))
{
Succeeded = false;
}
else if (result[2] != Math.Abs(left[dstOffset + 2] - right[srcOffset + 0]) +
Math.Abs(left[dstOffset + 3] - right[srcOffset + 1]) +
Math.Abs(left[dstOffset + 4] - right[srcOffset + 2]) +
Math.Abs(left[dstOffset + 5] - right[srcOffset + 3]))
{
Succeeded = false;
}
else if (result[3] != Math.Abs(left[dstOffset + 3] - right[srcOffset + 0]) +
Math.Abs(left[dstOffset + 4] - right[srcOffset + 1]) +
Math.Abs(left[dstOffset + 5] - right[srcOffset + 2]) +
Math.Abs(left[dstOffset + 6] - right[srcOffset + 3]))
{
Succeeded = false;
}
else if (result[4] != Math.Abs(left[dstOffset + 4] - right[srcOffset + 0]) +
Math.Abs(left[dstOffset + 5] - right[srcOffset + 1]) +
Math.Abs(left[dstOffset + 6] - right[srcOffset + 2]) +
Math.Abs(left[dstOffset + 7] - right[srcOffset + 3]))
{
Succeeded = false;
}
else if (result[5] != Math.Abs(left[dstOffset + 5] - right[srcOffset + 0]) +
Math.Abs(left[dstOffset + 6] - right[srcOffset + 1]) +
Math.Abs(left[dstOffset + 7] - right[srcOffset + 2]) +
Math.Abs(left[dstOffset + 8] - right[srcOffset + 3]))
{
Succeeded = false;
}
else if (result[6] != Math.Abs(left[dstOffset + 6] - right[srcOffset + 0]) +
Math.Abs(left[dstOffset + 7] - right[srcOffset + 1]) +
Math.Abs(left[dstOffset + 8] - right[srcOffset + 2]) +
Math.Abs(left[dstOffset + 9] - right[srcOffset + 3]))
{
Succeeded = false;
}
else if (result[7] != Math.Abs(left[dstOffset + 7] - right[srcOffset + 0]) +
Math.Abs(left[dstOffset + 8] - right[srcOffset + 1]) +
Math.Abs(left[dstOffset + 9] - right[srcOffset + 2]) +
Math.Abs(left[dstOffset + 10] - right[srcOffset + 3]))
{
Succeeded = false;
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.MultipleSumAbsoluteDifferences)}Vector128<UInt16>(Vector128<Byte>, Vector128<Byte>, Byte): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" imm8: ({imm8})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using System.ComponentModel;
namespace gma.System.Windows
{
/// <summary>
/// This class allows you to tap keyboard and mouse and / or to detect their activity even when an
/// application runes in background or does not have any user interface at all. This class raises
/// common .NET events with KeyEventArgs and MouseEventArgs so you can easily retrive any information you need.
/// </summary>
public class UserActivityHook
{
#region Windows structure definitions
/// <summary>
/// The POINT structure defines the x- and y- coordinates of a point.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/rectangl_0tiq.asp
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
private class POINT
{
/// <summary>
/// Specifies the x-coordinate of the point.
/// </summary>
public int x;
/// <summary>
/// Specifies the y-coordinate of the point.
/// </summary>
public int y;
}
/// <summary>
/// The MOUSEHOOKSTRUCT structure contains information about a mouse event passed to a WH_MOUSE hook procedure, MouseProc.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
private class MouseHookStruct
{
/// <summary>
/// Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates.
/// </summary>
public POINT pt;
/// <summary>
/// Handle to the window that will receive the mouse message corresponding to the mouse event.
/// </summary>
public int hwnd;
/// <summary>
/// Specifies the hit-test value. For a list of hit-test values, see the description of the WM_NCHITTEST message.
/// </summary>
public int wHitTestCode;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int dwExtraInfo;
}
/// <summary>
/// The MSLLHOOKSTRUCT structure contains information about a low-level keyboard input event.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private class MouseLLHookStruct
{
/// <summary>
/// Specifies a POINT structure that contains the x- and y-coordinates of the cursor, in screen coordinates.
/// </summary>
public POINT pt;
/// <summary>
/// If the message is WM_MOUSEWHEEL, the high-order word of this member is the wheel delta.
/// The low-order word is reserved. A positive value indicates that the wheel was rotated forward,
/// away from the user; a negative value indicates that the wheel was rotated backward, toward the user.
/// One wheel click is defined as WHEEL_DELTA, which is 120.
///If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP,
/// or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released,
/// and the low-order word is reserved. This value can be one or more of the following values. Otherwise, mouseData is not used.
///XBUTTON1
///The first X button was pressed or released.
///XBUTTON2
///The second X button was pressed or released.
/// </summary>
public int mouseData;
/// <summary>
/// Specifies the event-injected flag. An application can use the following value to test the mouse flags. Value Purpose
///LLMHF_INJECTED Test the event-injected flag.
///0
///Specifies whether the event was injected. The value is 1 if the event was injected; otherwise, it is 0.
///1-15
///Reserved.
/// </summary>
public int flags;
/// <summary>
/// Specifies the time stamp for this message.
/// </summary>
public int time;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int dwExtraInfo;
}
/// <summary>
/// The KBDLLHOOKSTRUCT structure contains information about a low-level keyboard input event.
/// </summary>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookstructures/cwpstruct.asp
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
private class KeyboardHookStruct
{
/// <summary>
/// Specifies a virtual-key code. The code must be a value in the range 1 to 254.
/// </summary>
public int vkCode;
/// <summary>
/// Specifies a hardware scan code for the key.
/// </summary>
public int scanCode;
/// <summary>
/// Specifies the extended-key flag, event-injected flag, context code, and transition-state flag.
/// </summary>
public int flags;
/// <summary>
/// Specifies the time stamp for this message.
/// </summary>
public int time;
/// <summary>
/// Specifies extra information associated with the message.
/// </summary>
public int dwExtraInfo;
}
#endregion
#region Windows function imports
/// <summary>
/// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
/// You would install a hook procedure to monitor the system for certain types of events. These events
/// are associated either with a specific thread or with all threads in the same desktop as the calling thread.
/// </summary>
/// <param name="idHook">
/// [in] Specifies the type of hook procedure to be installed. This parameter can be one of the following values.
/// </param>
/// <param name="lpfn">
/// [in] Pointer to the hook procedure. If the dwThreadId parameter is zero or specifies the identifier of a
/// thread created by a different process, the lpfn parameter must point to a hook procedure in a dynamic-link
/// library (DLL). Otherwise, lpfn can point to a hook procedure in the code associated with the current process.
/// </param>
/// <param name="hMod">
/// [in] Handle to the DLL containing the hook procedure pointed to by the lpfn parameter.
/// The hMod parameter must be set to NULL if the dwThreadId parameter specifies a thread created by
/// the current process and if the hook procedure is within the code associated with the current process.
/// </param>
/// <param name="dwThreadId">
/// [in] Specifies the identifier of the thread with which the hook procedure is to be associated.
/// If this parameter is zero, the hook procedure is associated with all existing threads running in the
/// same desktop as the calling thread.
/// </param>
/// <returns>
/// If the function succeeds, the return value is the handle to the hook procedure.
/// If the function fails, the return value is NULL. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int SetWindowsHookEx(
int idHook,
HookProc lpfn,
IntPtr hMod,
int dwThreadId);
/// <summary>
/// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
/// </summary>
/// <param name="idHook">
/// [in] Handle to the hook to be removed. This parameter is a hook handle obtained by a previous call to SetWindowsHookEx.
/// </param>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall, SetLastError = true)]
private static extern int UnhookWindowsHookEx(int idHook);
/// <summary>
/// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
/// A hook procedure can call this function either before or after processing the hook information.
/// </summary>
/// <param name="idHook">Ignored.</param>
/// <param name="nCode">
/// [in] Specifies the hook code passed to the current hook procedure.
/// The next hook procedure uses this code to determine how to process the hook information.
/// </param>
/// <param name="wParam">
/// [in] Specifies the wParam value passed to the current hook procedure.
/// The meaning of this parameter depends on the type of hook associated with the current hook chain.
/// </param>
/// <param name="lParam">
/// [in] Specifies the lParam value passed to the current hook procedure.
/// The meaning of this parameter depends on the type of hook associated with the current hook chain.
/// </param>
/// <returns>
/// This value is returned by the next hook procedure in the chain.
/// The current hook procedure must also return this value. The meaning of the return value depends on the hook type.
/// For more information, see the descriptions of the individual hook procedures.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/setwindowshookex.asp
/// </remarks>
[DllImport("user32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall)]
private static extern int CallNextHookEx(
int idHook,
int nCode,
int wParam,
IntPtr lParam);
/// <summary>
/// The CallWndProc hook procedure is an application-defined or library-defined callback
/// function used with the SetWindowsHookEx function. The HOOKPROC type defines a pointer
/// to this callback function. CallWndProc is a placeholder for the application-defined
/// or library-defined function name.
/// </summary>
/// <param name="nCode">
/// [in] Specifies whether the hook procedure must process the message.
/// If nCode is HC_ACTION, the hook procedure must process the message.
/// If nCode is less than zero, the hook procedure must pass the message to the
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx.
/// </param>
/// <param name="wParam">
/// [in] Specifies whether the message was sent by the current thread.
/// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
/// </param>
/// <param name="lParam">
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
/// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
/// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
/// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
/// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
/// procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/windowing/hooks/hookreference/hookfunctions/callwndproc.asp
/// </remarks>
private delegate int HookProc(int nCode, int wParam, IntPtr lParam);
/// <summary>
/// The ToAscii function translates the specified virtual-key code and keyboard
/// state to the corresponding character or characters. The function translates the code
/// using the input language and physical keyboard layout identified by the keyboard layout handle.
/// </summary>
/// <param name="uVirtKey">
/// [in] Specifies the virtual-key code to be translated.
/// </param>
/// <param name="uScanCode">
/// [in] Specifies the hardware scan code of the key to be translated.
/// The high-order bit of this value is set if the key is up (not pressed).
/// </param>
/// <param name="lpbKeyState">
/// [in] Pointer to a 256-byte array that contains the current keyboard state.
/// Each element (byte) in the array contains the state of one key.
/// If the high-order bit of a byte is set, the key is down (pressed).
/// The low bit, if set, indicates that the key is toggled on. In this function,
/// only the toggle bit of the CAPS LOCK key is relevant. The toggle state
/// of the NUM LOCK and SCROLL LOCK keys is ignored.
/// </param>
/// <param name="lpwTransKey">
/// [out] Pointer to the buffer that receives the translated character or characters.
/// </param>
/// <param name="fuState">
/// [in] Specifies whether a menu is active. This parameter must be 1 if a menu is active, or 0 otherwise.
/// </param>
/// <returns>
/// If the specified key is a dead key, the return value is negative. Otherwise, it is one of the following values.
/// Value Meaning
/// 0 The specified virtual key has no translation for the current state of the keyboard.
/// 1 One character was copied to the buffer.
/// 2 Two characters were copied to the buffer. This usually happens when a dead-key character
/// (accent or diacritic) stored in the keyboard layout cannot be composed with the specified
/// virtual key to form a single character.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp
/// </remarks>
[DllImport("user32")]
private static extern int ToAscii(
int uVirtKey,
int uScanCode,
byte[] lpbKeyState,
byte[] lpwTransKey,
int fuState);
/// <summary>
/// The GetKeyboardState function copies the status of the 256 virtual keys to the
/// specified buffer.
/// </summary>
/// <param name="pbKeyState">
/// [in] Pointer to a 256-byte array that contains keyboard key states.
/// </param>
/// <returns>
/// If the function succeeds, the return value is nonzero.
/// If the function fails, the return value is zero. To get extended error information, call GetLastError.
/// </returns>
/// <remarks>
/// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/toascii.asp
/// </remarks>
[DllImport("user32")]
private static extern int GetKeyboardState(byte[] pbKeyState);
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
private static extern short GetKeyState(int vKey);
#endregion
#region Windows constants
//values from Winuser.h in Microsoft SDK.
/// <summary>
/// Windows NT/2000/XP: Installs a hook procedure that monitors low-level mouse input events.
/// </summary>
private const int WH_MOUSE_LL = 14;
/// <summary>
/// Windows NT/2000/XP: Installs a hook procedure that monitors low-level keyboard input events.
/// </summary>
private const int WH_KEYBOARD_LL = 13;
/// <summary>
/// Installs a hook procedure that monitors mouse messages. For more information, see the MouseProc hook procedure.
/// </summary>
private const int WH_MOUSE = 7;
/// <summary>
/// Installs a hook procedure that monitors keystroke messages. For more information, see the KeyboardProc hook procedure.
/// </summary>
private const int WH_KEYBOARD = 2;
/// <summary>
/// The WM_MOUSEMOVE message is posted to a window when the cursor moves.
/// </summary>
private const int WM_MOUSEMOVE = 0x200;
/// <summary>
/// The WM_LBUTTONDOWN message is posted when the user presses the left mouse button
/// </summary>
private const int WM_LBUTTONDOWN = 0x201;
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
private const int WM_RBUTTONDOWN = 0x204;
/// <summary>
/// The WM_MBUTTONDOWN message is posted when the user presses the middle mouse button
/// </summary>
private const int WM_MBUTTONDOWN = 0x207;
/// <summary>
/// The WM_LBUTTONUP message is posted when the user releases the left mouse button
/// </summary>
private const int WM_LBUTTONUP = 0x202;
/// <summary>
/// The WM_RBUTTONUP message is posted when the user releases the right mouse button
/// </summary>
private const int WM_RBUTTONUP = 0x205;
/// <summary>
/// The WM_MBUTTONUP message is posted when the user releases the middle mouse button
/// </summary>
private const int WM_MBUTTONUP = 0x208;
/// <summary>
/// The WM_LBUTTONDBLCLK message is posted when the user double-clicks the left mouse button
/// </summary>
private const int WM_LBUTTONDBLCLK = 0x203;
/// <summary>
/// The WM_RBUTTONDBLCLK message is posted when the user double-clicks the right mouse button
/// </summary>
private const int WM_RBUTTONDBLCLK = 0x206;
/// <summary>
/// The WM_RBUTTONDOWN message is posted when the user presses the right mouse button
/// </summary>
private const int WM_MBUTTONDBLCLK = 0x209;
/// <summary>
/// The WM_MOUSEWHEEL message is posted when the user presses the mouse wheel.
/// </summary>
private const int WM_MOUSEWHEEL = 0x020A;
/// <summary>
/// The WM_KEYDOWN message is posted to the window with the keyboard focus when a nonsystem
/// key is pressed. A nonsystem key is a key that is pressed when the ALT key is not pressed.
/// </summary>
private const int WM_KEYDOWN = 0x100;
/// <summary>
/// The WM_KEYUP message is posted to the window with the keyboard focus when a nonsystem
/// key is released. A nonsystem key is a key that is pressed when the ALT key is not pressed,
/// or a keyboard key that is pressed when a window has the keyboard focus.
/// </summary>
private const int WM_KEYUP = 0x101;
/// <summary>
/// The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user
/// presses the F10 key (which activates the menu bar) or holds down the ALT key and then
/// presses another key. It also occurs when no window currently has the keyboard focus;
/// in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that
/// receives the message can distinguish between these two contexts by checking the context
/// code in the lParam parameter.
/// </summary>
private const int WM_SYSKEYDOWN = 0x104;
/// <summary>
/// The WM_SYSKEYUP message is posted to the window with the keyboard focus when the user
/// releases a key that was pressed while the ALT key was held down. It also occurs when no
/// window currently has the keyboard focus; in this case, the WM_SYSKEYUP message is sent
/// to the active window. The window that receives the message can distinguish between
/// these two contexts by checking the context code in the lParam parameter.
/// </summary>
private const int WM_SYSKEYUP = 0x105;
private const byte VK_SHIFT = 0x10;
private const byte VK_CAPITAL = 0x14;
private const byte VK_NUMLOCK = 0x90;
#endregion
/// <summary>
/// Creates an instance of UserActivityHook object and sets mouse and keyboard hooks.
/// </summary>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public UserActivityHook()
{
Start();
}
/// <summary>
/// Creates an instance of UserActivityHook object and installs both or one of mouse and/or keyboard hooks and starts rasing events
/// </summary>
/// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param>
/// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param>
/// <exception cref="Win32Exception">Any windows problem.</exception>
/// <remarks>
/// To create an instance without installing hooks call new UserActivityHook(false, false)
/// </remarks>
public UserActivityHook(bool InstallMouseHook, bool InstallKeyboardHook)
{
Start(InstallMouseHook, InstallKeyboardHook);
}
/// <summary>
/// Destruction.
/// </summary>
~UserActivityHook()
{
//uninstall hooks and do not throw exceptions
Stop(true, true, false);
}
/// <summary>
/// Occurs when the user moves the mouse, presses any mouse button or scrolls the wheel
/// </summary>
public event MouseEventHandler OnMouseActivity;
/// <summary>
/// Occurs when the user presses a key
/// </summary>
public event KeyEventHandler KeyDown;
/// <summary>
/// Occurs when the user presses and releases
/// </summary>
public event KeyPressEventHandler KeyPress;
/// <summary>
/// Occurs when the user releases a key
/// </summary>
public event KeyEventHandler KeyUp;
/// <summary>
/// Stores the handle to the mouse hook procedure.
/// </summary>
private int hMouseHook = 0;
/// <summary>
/// Stores the handle to the keyboard hook procedure.
/// </summary>
private int hKeyboardHook = 0;
/// <summary>
/// Declare MouseHookProcedure as HookProc type.
/// </summary>
private static HookProc MouseHookProcedure;
/// <summary>
/// Declare KeyboardHookProcedure as HookProc type.
/// </summary>
private static HookProc KeyboardHookProcedure;
/// <summary>
/// Installs both mouse and keyboard hooks and starts rasing events
/// </summary>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public void Start()
{
this.Start(true, true);
}
/// <summary>
/// Installs both or one of mouse and/or keyboard hooks and starts rasing events
/// </summary>
/// <param name="InstallMouseHook"><b>true</b> if mouse events must be monitored</param>
/// <param name="InstallKeyboardHook"><b>true</b> if keyboard events must be monitored</param>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public void Start(bool InstallMouseHook, bool InstallKeyboardHook)
{
// install Mouse hook only if it is not installed and must be installed
if (hMouseHook == 0 && InstallMouseHook)
{
// Create an instance of HookProc.
MouseHookProcedure = new HookProc(MouseHookProc);
//install hook
hMouseHook = SetWindowsHookEx(
WH_MOUSE_LL,
MouseHookProcedure,
IntPtr.Zero,
0);
//If SetWindowsHookEx fails.
if (hMouseHook == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
Stop(true, false, false);
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
// install Keyboard hook only if it is not installed and must be installed
if (hKeyboardHook == 0 && InstallKeyboardHook)
{
// Create an instance of HookProc.
KeyboardHookProcedure = new HookProc(KeyboardHookProc);
//install hook
hKeyboardHook = SetWindowsHookEx(
WH_KEYBOARD_LL,
KeyboardHookProcedure,
IntPtr.Zero,
0);
//If SetWindowsHookEx fails.
if (hKeyboardHook == 0)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//do cleanup
Stop(false, true, false);
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
/// <summary>
/// Stops monitoring both mouse and keyboard events and rasing events.
/// </summary>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public void Stop()
{
this.Stop(true, true, true);
}
/// <summary>
/// Stops monitoring both or one of mouse and/or keyboard events and rasing events.
/// </summary>
/// <param name="UninstallMouseHook"><b>true</b> if mouse hook must be uninstalled</param>
/// <param name="UninstallKeyboardHook"><b>true</b> if keyboard hook must be uninstalled</param>
/// <param name="ThrowExceptions"><b>true</b> if exceptions which occured during uninstalling must be thrown</param>
/// <exception cref="Win32Exception">Any windows problem.</exception>
public void Stop(bool UninstallMouseHook, bool UninstallKeyboardHook, bool ThrowExceptions)
{
//if mouse hook set and must be uninstalled
if (hMouseHook != 0 && UninstallMouseHook)
{
//uninstall hook
int retMouse = UnhookWindowsHookEx(hMouseHook);
//reset invalid handle
hMouseHook = 0;
//if failed and exception must be thrown
if (retMouse == 0 && ThrowExceptions)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
//if keyboard hook set and must be uninstalled
if (hKeyboardHook != 0 && UninstallKeyboardHook)
{
//uninstall hook
int retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
//reset invalid handle
hKeyboardHook = 0;
//if failed and exception must be thrown
if (retKeyboard == 0 && ThrowExceptions)
{
//Returns the error code returned by the last unmanaged function called using platform invoke that has the DllImportAttribute.SetLastError flag set.
int errorCode = Marshal.GetLastWin32Error();
//Initializes and throws a new instance of the Win32Exception class with the specified error.
throw new Win32Exception(errorCode);
}
}
}
/// <summary>
/// A callback function which will be called every time a mouse activity detected.
/// </summary>
/// <param name="nCode">
/// [in] Specifies whether the hook procedure must process the message.
/// If nCode is HC_ACTION, the hook procedure must process the message.
/// If nCode is less than zero, the hook procedure must pass the message to the
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx.
/// </param>
/// <param name="wParam">
/// [in] Specifies whether the message was sent by the current thread.
/// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
/// </param>
/// <param name="lParam">
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
/// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
/// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
/// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
/// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
/// procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
private int MouseHookProc(int nCode, int wParam, IntPtr lParam)
{
// if ok and someone listens to our events
if ((nCode >= 0) && (OnMouseActivity != null))
{
//Marshall the data from callback.
MouseLLHookStruct mouseHookStruct = (MouseLLHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseLLHookStruct));
//detect button clicked
MouseButtons button = MouseButtons.None;
short mouseDelta = 0;
switch (wParam)
{
case WM_LBUTTONDOWN:
//case WM_LBUTTONUP:
//case WM_LBUTTONDBLCLK:
button = MouseButtons.Left;
break;
case WM_RBUTTONDOWN:
//case WM_RBUTTONUP:
//case WM_RBUTTONDBLCLK:
button = MouseButtons.Right;
break;
case WM_MOUSEWHEEL:
//If the message is WM_MOUSEWHEEL, the high-order word of mouseData member is the wheel delta.
//One wheel click is defined as WHEEL_DELTA, which is 120.
//(value >> 16) & 0xffff; retrieves the high-order word from the given 32-bit value
mouseDelta = (short)((mouseHookStruct.mouseData >> 16) & 0xffff);
//TODO: X BUTTONS (I havent them so was unable to test)
//If the message is WM_XBUTTONDOWN, WM_XBUTTONUP, WM_XBUTTONDBLCLK, WM_NCXBUTTONDOWN, WM_NCXBUTTONUP,
//or WM_NCXBUTTONDBLCLK, the high-order word specifies which X button was pressed or released,
//and the low-order word is reserved. This value can be one or more of the following values.
//Otherwise, mouseData is not used.
break;
}
//double clicks
int clickCount = 0;
if (button != MouseButtons.None)
if (wParam == WM_LBUTTONDBLCLK || wParam == WM_RBUTTONDBLCLK) clickCount = 2;
else clickCount = 1;
//generate event
MouseEventArgs e = new MouseEventArgs(
button,
clickCount,
mouseHookStruct.pt.x,
mouseHookStruct.pt.y,
mouseDelta);
//raise it
OnMouseActivity(this, e);
}
//call next hook
return CallNextHookEx(hMouseHook, nCode, wParam, lParam);
}
/// <summary>
/// A callback function which will be called every time a keyboard activity detected.
/// </summary>
/// <param name="nCode">
/// [in] Specifies whether the hook procedure must process the message.
/// If nCode is HC_ACTION, the hook procedure must process the message.
/// If nCode is less than zero, the hook procedure must pass the message to the
/// CallNextHookEx function without further processing and must return the
/// value returned by CallNextHookEx.
/// </param>
/// <param name="wParam">
/// [in] Specifies whether the message was sent by the current thread.
/// If the message was sent by the current thread, it is nonzero; otherwise, it is zero.
/// </param>
/// <param name="lParam">
/// [in] Pointer to a CWPSTRUCT structure that contains details about the message.
/// </param>
/// <returns>
/// If nCode is less than zero, the hook procedure must return the value returned by CallNextHookEx.
/// If nCode is greater than or equal to zero, it is highly recommended that you call CallNextHookEx
/// and return the value it returns; otherwise, other applications that have installed WH_CALLWNDPROC
/// hooks will not receive hook notifications and may behave incorrectly as a result. If the hook
/// procedure does not call CallNextHookEx, the return value should be zero.
/// </returns>
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
{
//indicates if any of underlaing events set e.Handled flag
bool handled = false;
//it was ok and someone listens to events
if ((nCode >= 0) && (KeyDown != null || KeyUp != null || KeyPress != null))
{
//read structure KeyboardHookStruct at lParam
KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));
//raise KeyDown
if (KeyDown != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(keyData);
KeyDown(this, e);
handled = handled || e.Handled;
}
// raise KeyPress
if (KeyPress != null && wParam == WM_KEYDOWN)
{
bool isDownShift = ((GetKeyState(VK_SHIFT) & 0x80) == 0x80 ? true : false);
bool isDownCapslock = (GetKeyState(VK_CAPITAL) != 0 ? true : false);
byte[] keyState = new byte[256];
GetKeyboardState(keyState);
byte[] inBuffer = new byte[2];
if (ToAscii(MyKeyboardHookStruct.vkCode,
MyKeyboardHookStruct.scanCode,
keyState,
inBuffer,
MyKeyboardHookStruct.flags) == 1)
{
char key = (char)inBuffer[0];
if ((isDownCapslock ^ isDownShift) && Char.IsLetter(key)) key = Char.ToUpper(key);
KeyPressEventArgs e = new KeyPressEventArgs(key);
KeyPress(this, e);
handled = handled || e.Handled;
}
}
// raise KeyUp
if (KeyUp != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))
{
Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;
KeyEventArgs e = new KeyEventArgs(keyData);
KeyUp(this, e);
handled = handled || e.Handled;
}
}
//if event handled in application do not handoff to other listeners
if (handled)
return 1;
else
return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SquishIt.Framework.Caches;
using SquishIt.Framework.Invalidation;
using SquishIt.Framework.Minifiers;
using SquishIt.Framework.Renderers;
using SquishIt.Framework.Files;
using SquishIt.Framework.Utilities;
namespace SquishIt.Framework.Base
{
/// <summary>
/// Base class for bundle implementations. Configuration methods all return (T)this.
/// </summary>
/// <typeparam name="T">Type of bundle being implemented (Javascript or CSS).</typeparam>
public abstract partial class BundleBase<T> : IRenderable where T : BundleBase<T>
{
static readonly Dictionary<string, string> renderPathCache = new Dictionary<string, string>();
static readonly Dictionary<string, BundleState> bundleStateCache = new Dictionary<string, BundleState>();
static readonly Dictionary<string, BundleState> rawContentBundleStateCache = new Dictionary<string, BundleState>();
protected abstract IMinifier<T> DefaultMinifier { get; }
protected abstract string tagFormat { get; }
protected abstract string Template { get; }
protected abstract string CachePrefix { get; }
protected abstract IEnumerable<string> allowedExtensions { get; }
protected abstract IEnumerable<string> disallowedExtensions { get; }
protected abstract string defaultExtension { get; }
protected string debugExtension { get { return ".squishit.debug" + defaultExtension.ToLowerInvariant(); } }
protected abstract string ProcessFile(string file, string outputFile, Asset originalAsset);
internal BundleState bundleState;
readonly IContentCache bundleCache;
readonly IContentCache rawContentCache;
protected string BaseOutputHref = Configuration.Instance.DefaultOutputBaseHref();
protected IFileWriterFactory fileWriterFactory;
protected IFileReaderFactory fileReaderFactory;
protected IDebugStatusReader debugStatusReader;
protected IDirectoryWrapper directoryWrapper;
protected IHasher hasher;
protected IPathTranslator pathTranslator = Configuration.Instance.DefaultPathTranslator();
IMinifier<T> minifier;
protected IMinifier<T> Minifier
{
get { return minifier ?? DefaultMinifier; }
set { minifier = value; }
}
protected BundleBase(IFileWriterFactory fileWriterFactory, IFileReaderFactory fileReaderFactory, IDebugStatusReader debugStatusReader, IDirectoryWrapper directoryWrapper, IHasher hasher, IContentCache bundleCache, IContentCache rawContentCache)
{
this.fileWriterFactory = fileWriterFactory;
this.fileReaderFactory = fileReaderFactory;
this.debugStatusReader = debugStatusReader;
this.directoryWrapper = directoryWrapper;
this.hasher = hasher;
bundleState = new BundleState
{
DebugPredicate = Configuration.Instance.DefaultDebugPredicate(),
ShouldRenderOnlyIfOutputFileIsMissing = false,
HashKeyName = Configuration.Instance.DefaultHashKeyName(),
CacheInvalidationStrategy = Configuration.Instance.DefaultCacheInvalidationStrategy()
};
this.bundleCache = bundleCache;
this.rawContentCache = rawContentCache;
}
//TODO: should this be public?
internal bool IsDebuggingEnabled()
{
return debugStatusReader.IsDebuggingEnabled(bundleState.DebugPredicate);
}
protected IRenderer GetFileRenderer()
{
return IsDebuggingEnabled() ? new FileRenderer(fileWriterFactory) :
bundleState.ReleaseFileRenderer ??
Configuration.Instance.DefaultReleaseRenderer() ??
new FileRenderer(fileWriterFactory);
}
void AddAsset(Asset asset)
{
bundleState.Assets.Add(asset);
}
/// <summary>
/// Specify that a bundle should be rendered without type="" in the html tag.
/// </summary>
public T WithoutTypeAttribute()
{
bundleState.Typeless = true;
return (T)this;
}
/// <summary>
/// Add a single file to a bundle.
/// </summary>
/// <param name="filePath">Path to file being added</param>
public T Add(string filePath)
{
AddAsset(new Asset { LocalPath = filePath });
return (T)this;
}
/// <summary>
/// Add a single file that has already been minified to a bundle. This will prevent the file from being minified again, a potential cause of bugs in combined file.
/// </summary>
/// <param name="filePath">Path to file being added</param>
public T AddMinified(string filePath)
{
AddAsset(new Asset { LocalPath = filePath, Minify = false });
return (T)this;
}
/// <summary>
/// Add all files in a directory with extensions matching those known to bundle type. Defaults to include subfolders.
/// </summary>
/// <param name="folderPath">Path to directory being added.</param>
/// <param name="recursive">Include subfolders</param>
public T AddDirectory(string folderPath, bool recursive = true)
{
return AddDirectory(folderPath, recursive, true);
}
/// <summary>
/// Add all files in a directory with extensions matching those known to bundle type. Defaults to include subfolders. All files found will be considered pre-minified.
/// </summary>
/// <param name="folderPath">Path to directory.</param>
/// <param name="recursive">Include subfolders</param>
public T AddMinifiedDirectory(string folderPath, bool recursive = true)
{
return AddDirectory(folderPath, recursive, false);
}
T AddDirectory(string folderPath, bool recursive, bool minify)
{
AddAsset(new Asset { LocalPath = folderPath, IsRecursive = recursive, Minify = minify });
return (T)this;
}
/// <summary>
/// Add arbitrary content that is not saved on disk.
/// </summary>
/// <param name="content">Content to include in bundle.</param>
public T AddString(string content)
{
return AddString(content, defaultExtension, true);
}
/// <summary>
/// Add arbitrary content that is not saved on disk with the assumption that it is treated as if found in a given directory. This is useful for adding LESS content that needs to get imports relative to a particular location.
/// </summary>
/// <param name="content">Content to include in bundle.</param>
/// <param name="extension">Extension that would be included in filename if content were saved to disk - this is needed to determine if the content should be preprocessed.</param>
/// <param name="currentDirectory">Folder that file would reside in if content were saved to disk - this is used for processing relative imports within arbitrary content.</param>
public T AddString(string content, string extension, string currentDirectory = null)
{
return AddString(content, extension, true, currentDirectory);
}
/// <summary>
/// Add pre-minified arbitrary content (not saved on disk).
/// </summary>
/// <param name="content">Minified content to include in bundle.</param>
public T AddMinifiedString(string content)
{
return AddString(content, defaultExtension, false);
}
/// <summary>
/// Add pre-minified arbitrary content (not saved on disk) with the assumption that it is treated as if found in a given directory. This is useful for adding LESS content that needs to get imports relative to a particular location.
/// </summary>
/// <param name="content">Minified content to include in bundle.</param>
/// <param name="extension">Extension that would be included in filename if content were saved to disk - this is needed to determine if the content should be preprocessed.</param>
/// <param name="currentDirectory">Folder that file would reside in if content were saved to disk - this is used for processing relative imports within arbitrary content.</param>
public T AddMinifiedString(string content, string extension)
{
return AddString(content, extension, false);
}
T AddString(string content, string extension, bool minify, string currentDirectory = null)
{
if (bundleState.Assets.All(ac => ac.Content != content))
bundleState.Assets.Add(new Asset { Content = content, Extension = extension, Minify = minify, ArbitraryWorkingDirectory = currentDirectory });
return (T)this;
}
/// <summary>
/// Add arbitrary content (not saved on disk) using string.Format to inject values.
/// </summary>
/// <param name="format">Content to include in bundle.</param>
/// <param name="values">Values to be injected using string.Format.</param>
public T AddString(string format, object[] values)
{
return AddString(format, defaultExtension, values);
}
/// <summary>
/// Add arbitrary content (not saved on disk) using string.Format to inject values.
/// </summary>
/// <param name="format">Content to include in bundle.</param>
/// <param name="extension">Extension that would be included in filename if content were saved to disk - this is needed to determine if the content should be preprocessed.</param>
/// <param name="values">Values to be injected using string.Format.</param>
public T AddString(string format, string extension, object[] values)
{
var content = string.Format(format, values);
return AddString(content, extension);
}
/// <summary>
/// Add a remote asset to bundle.
/// </summary>
/// <param name="localPath">Path to treat asset as if it comes from.</param>
/// <param name="remotePath">URL to remote asset.</param>
public T AddRemote(string localPath, string remotePath)
{
return AddRemote(localPath, remotePath, false);
}
/// <summary>
/// Add a remote asset to bundle.
/// </summary>
/// <param name="localPath">Path to treat asset as if it comes from.</param>
/// <param name="remotePath">URL to remote asset.</param>
/// <param name="downloadRemote">Fetch remote content to include in bundle.</param>
public T AddRemote(string localPath, string remotePath, bool downloadRemote)
{
var asset = new Asset
{
LocalPath = localPath,
RemotePath = remotePath,
DownloadRemote = downloadRemote
};
AddAsset(asset);
return (T)this;
}
/// <summary>
/// Add dynamic (app-generated) content - the generated proxy file SignalR serves to clients is a good example.
/// </summary>
/// <param name="siteRelativePath">Site-relative path to content (eg "signalr/hubs").</param>
public T AddDynamic(string siteRelativePath)
{
var absolutePath = pathTranslator.BuildAbsolutePath(siteRelativePath);
return AddRemote(siteRelativePath, absolutePath, true);
}
/// <summary>
/// Add embedded resource in root namespace.
/// </summary>
/// <param name="localPath">Path to treat asset as if it comes from.</param>
/// <param name="embeddedResourcePath">Path to resource embedded in root namespace (eg "WebForms.js").</param>
public T AddRootEmbeddedResource(string localPath, string embeddedResourcePath)
{
AddAsset(new Asset { LocalPath = localPath, RemotePath = embeddedResourcePath, Order = 0, IsEmbeddedResource = true, IsEmbeddedInRootNamespace = true });
return (T)this;
}
/// <summary>
/// Add embedded resource.
/// </summary>
/// <param name="localPath">Path to treat asset as if it comes from.</param>
/// <param name="embeddedResourcePath">Path to embedded resource (eg "SquishIt.Tests://EmbeddedResource.Embedded.css").</param>
public T AddEmbeddedResource(string localPath, string embeddedResourcePath)
{
AddAsset(new Asset { LocalPath = localPath, RemotePath = embeddedResourcePath, Order = 0, IsEmbeddedResource = true });
return (T)this;
}
/// <summary>
/// Configure bundle to bypass writing to disk if the output file already exists.
/// </summary>
public T RenderOnlyIfOutputFileMissing()
{
bundleState.ShouldRenderOnlyIfOutputFileIsMissing = true;
return (T)this;
}
/// <summary>
/// Configure bundle to always render in debug mode (assets served separately and unminified).
/// </summary>
public T ForceDebug()
{
debugStatusReader.ForceDebug();
bundleState.ForceDebug = true;
return (T)this;
}
/// <summary>
/// Configure bundle to render in debug mode (assets served separately and unminified) if a precondition is met.
/// </summary>
public T ForceDebugIf(Func<bool> predicate)
{
bundleState.DebugPredicate = predicate;
return (T)this;
}
/// <summary>
/// Configure bundle to always render in release mode (assets combined and minified).
/// </summary>
public T ForceRelease()
{
debugStatusReader.ForceRelease();
bundleState.ForceRelease = true;
return (T)this;
}
/// <summary>
/// Configure bundle to prefix paths with given base URL - this is useful for cdn scenarios.
/// </summary>
/// <param name="href">Base path to CDN (eg "http://static.myapp.com").</param>
public T WithOutputBaseHref(string href)
{
BaseOutputHref = href;
return (T)this;
}
/// <summary>
/// Configure bundle to use a non-standard file renderer. This is useful if you want combined files uploaded to a static server or CDN.
/// </summary>
/// <param name="renderer">Implementation of <see cref="IRenderer">IRenderer</see> to be used when creating combined file.</param>
public T WithReleaseFileRenderer(IRenderer renderer)
{
bundleState.ReleaseFileRenderer = renderer;
return (T)this;
}
/// <summary>
/// Configure bundle to use a non-standard cache invalidation strategy.
/// </summary>
/// <param name="strategy">Implementation of <see cref="ICacheInvalidationStrategy">ICacheInvalidationStrategy</see> to be used when generating content tag (eg <see cref="HashAsVirtualDirectoryCacheInvalidationStrategy">HashAsVirtualDirectoryCacheInvalidationStrategy</see>)</param>
public T WithCacheInvalidationStrategy(ICacheInvalidationStrategy strategy)
{
bundleState.CacheInvalidationStrategy = strategy;
return (T)this;
}
void AddAttributes(Dictionary<string, string> attributes, bool merge = true)
{
if (merge)
{
foreach (var attribute in attributes)
{
bundleState.Attributes[attribute.Key] = attribute.Value;
}
}
else
{
bundleState.Attributes = attributes;
}
}
/// <summary>
/// Include a given HTML attribute in rendered tag.
/// </summary>
/// <param name="name">Attribute name.</param>
/// <param name="value">Attribute value.</param>
public T WithAttribute(string name, string value)
{
AddAttributes(new Dictionary<string, string> { { name, value } });
return (T)this;
}
/// <summary>
/// Include a given HTML attribute in rendered tag.
/// </summary>
/// <param name="attributes">Attribute name/value pairs.</param>
/// <param name="merge">Merge with attributes already added (false will overwrite).</param>
public T WithAttributes(Dictionary<string, string> attributes, bool merge = true)
{
AddAttributes(attributes, merge: merge);
return (T)this;
}
/// <summary>
/// Configure bundle to use a type other than the default minifier for given bundle type.
/// </summary>
/// <typeparam name="TMin">Type of <see cref="IMinifier">IMinifier</see> to use.</typeparam>
public T WithMinifier<TMin>() where TMin : IMinifier<T>
{
Minifier = MinifierFactory.Get<T, TMin>();
return (T)this;
}
/// <summary>
/// Configure bundle to use a minifier instance.
/// </summary>
/// <typeparam name="TMin">Instance of <see cref="IMinifier">IMinifier</see> to use.</typeparam>
public T WithMinifier<TMin>(TMin minifier) where TMin : IMinifier<T>
{
Minifier = minifier;
return (T)this;
}
string FillTemplate(BundleState bundleState, string path)
{
return string.Format(Template, GetAdditionalAttributes(bundleState), path);
}
/// <summary>
/// Configure bundle to use a specific name for cache-breaking parameter (only used with querystring invalidation).
/// </summary>
/// <param name="hashQueryStringKeyName">Name of parameter to be added to content URLs.</param>
public T HashKeyNamed(string hashQueryStringKeyName)
{
bundleState.HashKeyName = hashQueryStringKeyName;
return (T)this;
}
/// <summary>
/// Configure bundle to bypass cache invalidation.
/// </summary>
public T WithoutRevisionHash()
{
return HashKeyNamed(string.Empty);
}
/// <summary>
/// Configure bundle to use provided preprocessor instance.
/// </summary>
/// <param name="instance"><see cref="IPreprocessor">IPreprocessor</see> to use when rendering bundle.</param>
/// <returns></returns>
public T WithPreprocessor(IPreprocessor instance)
{
bundleState.AddPreprocessor(instance);
return (T)this;
}
protected abstract void AggregateContent(List<Asset> assets, StringBuilder sb, string outputFile);
BundleState GetCachedBundleState(string name)
{
var bundle = bundleStateCache[CachePrefix + name];
if (bundle.ForceDebug)
{
debugStatusReader.ForceDebug();
}
if (bundle.ForceRelease)
{
debugStatusReader.ForceRelease();
}
return bundle;
}
/// <summary>
/// Render bundle to a file.
/// </summary>
/// <param name="renderTo">Path to combined file.</param>
/// <returns>HTML tag.</returns>
public string Render(string renderTo)
{
string key = renderTo;
return Render(renderTo, key, GetFileRenderer());
}
/// <summary>
/// Render tag for a cached bundle.
/// </summary>
/// <param name="name">Name of cached bundle.</param>
/// <returns>HTML tag.</returns>
public string RenderCachedAssetTag(string name)
{
bundleState = GetCachedBundleState(name);
return Render(null, name, new CacheRenderer(CachePrefix, name));
}
/// <summary>
/// Render bundle into the cache with a given name.
/// </summary>
/// <param name="name">Name of bundle in cache.</param>
/// <param name="renderToFilePath">File system path that cached bundle would be rendered to (for import processing).</param>
public void AsNamed(string name, string renderToFilePath)
{
Render(renderToFilePath, name, GetFileRenderer());
bundleState.Path = renderToFilePath;
bundleStateCache[CachePrefix + name] = bundleState;
}
/// <summary>
/// Render bundle into cache and return tag.
/// </summary>
/// <param name="name">Name of bundle in cache.</param>
/// <param name="renderToFilePath">File system path that cached bundle would be rendered to (for import processing).</param>
/// <returns>HTML tag.</returns>
public string AsCached(string name, string renderToFilePath)
{
string result = Render(renderToFilePath, name, new CacheRenderer(CachePrefix, name));
bundleState.Path = renderToFilePath;
bundleStateCache[CachePrefix + name] = bundleState;
return result;
}
/// <summary>
/// Render bundle with a given name.
/// </summary>
/// <param name="name">Name for bundle.</param>
/// <returns>HTML tag.</returns>
public string RenderNamed(string name)
{
bundleState = GetCachedBundleState(name);
if (!bundleState.DebugPredicate.SafeExecute())
{
// Revisit https://github.com/jetheredge/SquishIt/pull/155 and https://github.com/jetheredge/SquishIt/issues/183
//hopefully we can find a better way to satisfy both of these requirements
var fullName = (BaseOutputHref ?? "") + CachePrefix + name;
var content = bundleCache.GetContent(fullName);
if (content == null)
{
AsNamed(name, bundleState.Path);
return bundleCache.GetContent(CachePrefix + name);
}
return content;
}
return RenderDebug(bundleState.Path, name, GetFileRenderer());
}
/// <summary>
/// Render bundle from cache with a given name.
/// </summary>
/// <param name="name">Name for cached bundle.</param>
/// <returns>HTML tag.</returns>
public string RenderCached(string name)
{
bundleState = GetCachedBundleState(name);
var content = CacheRenderer.Get(CachePrefix, name);
if (content == null)
{
AsCached(name, bundleState.Path);
return CacheRenderer.Get(CachePrefix, name);
}
return content;
}
public void ClearCache()
{
bundleCache.ClearTestingCache();
}
/// <summary>
/// Retrieve number of assets included in bundle.
/// </summary>
public int AssetCount
{
get
{
return bundleState == null ? 0
: bundleState.Assets == null ? 0
: bundleState.Assets.Count;
}
}
/// <summary>
/// Render 'raw' content directly without building tags or writing to files (and save in cache by name)
/// </summary>
/// <returns>String representation of content, minified if needed.</returns>
public string RenderRawContent(string bundleName)
{
var cacheKey = CachePrefix + "_raw_" + bundleName;
string content;
if (rawContentCache.ContainsKey(cacheKey))
{
rawContentCache.Remove(cacheKey);
}
if (rawContentBundleStateCache.ContainsKey(cacheKey))
{
rawContentBundleStateCache.Remove(cacheKey);
}
content = GetMinifiedContent(bundleState.Assets, string.Empty);
rawContentCache.Add(cacheKey, content, bundleState.DependentFiles, IsDebuggingEnabled());
rawContentBundleStateCache.Add(cacheKey, bundleState);
return content;
}
/// <summary>
/// Render cached 'raw' bundle content.
/// </summary>
/// <param name="bundleName">String representation of content according to cache.</param>
/// <returns></returns>
public string RenderCachedRawContent(string bundleName)
{
var cacheKey = CachePrefix + "_raw_" + bundleName;
var output = rawContentCache.GetContent(cacheKey);
if (output == null)
{
bundleState = rawContentBundleStateCache[cacheKey];
if (bundleState == null)
{
throw new InvalidOperationException(string.Format("No cached bundle state named {0} was found.", bundleName));
}
output = RenderRawContent(bundleName);
}
return output;
}
}
}
| |
namespace BooCompiler.Tests
{
using NUnit.Framework;
[TestFixture]
public class GeneratorsIntegrationTestFixture : AbstractCompilerTestCase
{
[Test]
public void generator_calling_external_super_with_arguments_2()
{
RunCompilerTestCase(@"generator-calling-external-super-with-arguments-2.boo");
}
[Test]
public void generator_calling_external_super_with_arguments()
{
RunCompilerTestCase(@"generator-calling-external-super-with-arguments.boo");
}
[Test]
public void generator_calling_super_with_arguments_2()
{
RunCompilerTestCase(@"generator-calling-super-with-arguments-2.boo");
}
[Test]
public void generator_calling_super_with_arguments()
{
RunCompilerTestCase(@"generator-calling-super-with-arguments.boo");
}
[Test]
public void generator_calling_super()
{
RunCompilerTestCase(@"generator-calling-super.boo");
}
[Test]
public void generator_of_static_class_is_transient()
{
RunCompilerTestCase(@"generator-of-static-class-is-transient.boo");
}
[Test]
public void generator_of_transient_class_is_transient()
{
RunCompilerTestCase(@"generator-of-transient-class-is-transient.boo");
}
[Test]
public void generators_1()
{
RunCompilerTestCase(@"generators-1.boo");
}
[Test]
public void generators_10()
{
RunCompilerTestCase(@"generators-10.boo");
}
[Test]
public void generators_11()
{
RunCompilerTestCase(@"generators-11.boo");
}
[Test]
public void generators_12()
{
RunCompilerTestCase(@"generators-12.boo");
}
[Test]
public void generators_13()
{
RunCompilerTestCase(@"generators-13.boo");
}
[Test]
public void generators_14()
{
RunCompilerTestCase(@"generators-14.boo");
}
[Test]
public void generators_15()
{
RunCompilerTestCase(@"generators-15.boo");
}
[Test]
public void generators_16()
{
RunCompilerTestCase(@"generators-16.boo");
}
[Test]
public void generators_17()
{
RunCompilerTestCase(@"generators-17.boo");
}
[Test]
public void generators_18()
{
RunCompilerTestCase(@"generators-18.boo");
}
[Test]
public void generators_19()
{
RunCompilerTestCase(@"generators-19.boo");
}
[Test]
public void generators_2()
{
RunCompilerTestCase(@"generators-2.boo");
}
[Test]
public void generators_20()
{
RunCompilerTestCase(@"generators-20.boo");
}
[Test]
public void generators_21()
{
RunCompilerTestCase(@"generators-21.boo");
}
[Test]
public void generators_3()
{
RunCompilerTestCase(@"generators-3.boo");
}
[Test]
public void generators_4()
{
RunCompilerTestCase(@"generators-4.boo");
}
[Test]
public void generators_5()
{
RunCompilerTestCase(@"generators-5.boo");
}
[Test]
public void generators_6()
{
RunCompilerTestCase(@"generators-6.boo");
}
[Test]
public void generators_7()
{
RunCompilerTestCase(@"generators-7.boo");
}
[Test]
public void generators_8()
{
RunCompilerTestCase(@"generators-8.boo");
}
[Test]
public void generators_9()
{
RunCompilerTestCase(@"generators-9.boo");
}
[Ignore("BOO-759 - generic generator methods are not supported")][Test]
public void generic_generator_1()
{
RunCompilerTestCase(@"generic-generator-1.boo");
}
[Test]
public void label_issue_1()
{
RunCompilerTestCase(@"label-issue-1.boo");
}
[Test]
public void list_generators_1()
{
RunCompilerTestCase(@"list-generators-1.boo");
}
[Test]
public void list_generators_2()
{
RunCompilerTestCase(@"list-generators-2.boo");
}
[Test]
public void list_generators_3()
{
RunCompilerTestCase(@"list-generators-3.boo");
}
[Test]
public void list_generators_4()
{
RunCompilerTestCase(@"list-generators-4.boo");
}
[Test]
public void list_generators_5()
{
RunCompilerTestCase(@"list-generators-5.boo");
}
[Test]
public void to_string()
{
RunCompilerTestCase(@"to-string.boo");
}
[Test]
public void yield_1()
{
RunCompilerTestCase(@"yield-1.boo");
}
[Test]
public void yield_10()
{
RunCompilerTestCase(@"yield-10.boo");
}
[Test]
public void yield_11()
{
RunCompilerTestCase(@"yield-11.boo");
}
[Test]
public void yield_12()
{
RunCompilerTestCase(@"yield-12.boo");
}
[Test]
public void yield_13()
{
RunCompilerTestCase(@"yield-13.boo");
}
[Test]
public void yield_14()
{
RunCompilerTestCase(@"yield-14.boo");
}
[Test]
public void yield_15()
{
RunCompilerTestCase(@"yield-15.boo");
}
[Test]
public void yield_16()
{
RunCompilerTestCase(@"yield-16.boo");
}
[Test]
public void yield_17()
{
RunCompilerTestCase(@"yield-17.boo");
}
[Test]
public void yield_2()
{
RunCompilerTestCase(@"yield-2.boo");
}
[Test]
public void yield_3()
{
RunCompilerTestCase(@"yield-3.boo");
}
[Test]
public void yield_4()
{
RunCompilerTestCase(@"yield-4.boo");
}
[Test]
public void yield_5()
{
RunCompilerTestCase(@"yield-5.boo");
}
[Test]
public void yield_6()
{
RunCompilerTestCase(@"yield-6.boo");
}
[Test]
public void yield_7()
{
RunCompilerTestCase(@"yield-7.boo");
}
[Test]
public void yield_8()
{
RunCompilerTestCase(@"yield-8.boo");
}
[Test]
public void yield_9()
{
RunCompilerTestCase(@"yield-9.boo");
}
[Test]
public void yield_null_as_IEnumerator()
{
RunCompilerTestCase(@"yield-null-as-IEnumerator.boo");
}
[Test]
public void yield_null()
{
RunCompilerTestCase(@"yield-null.boo");
}
override protected string GetRelativeTestCasesPath()
{
return "integration/generators";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Eto
{
/// <summary>
/// Delegate to handle styling a widget
/// </summary>
/// <remarks>
/// This allows you to add additional logic or set properties on the widget based on the styles set on the widget.
/// </remarks>
/// <typeparam name="TWidget">Type of widget to style</typeparam>
/// <param name="widget">Widget instance that is being styled</param>
public delegate void StyleWidgetHandler<TWidget>(TWidget widget)
where TWidget: Widget;
/// <summary>
/// Delegate to handle styling a widget handler
/// </summary>
/// <remarks>
/// This allows you to add additional logic or set properties on the widget and platform-specific control(s)
/// based on the styles set on the widget.
/// </remarks>
/// <param name="handler">Handler instance that is being styled</param>
/// <typeparam name="THandler">Type of the handler to style</typeparam>
public delegate void StyleHandler<THandler>(THandler handler)
where THandler: Widget.IHandler;
/// <summary>
/// Style manager for widgets
/// </summary>
/// <remarks>
/// Styles allow you to attach custom platform-specific logic to a widget.
/// In your platform-specific assembly, use Style.Add<H>(string, StyleHandler<H>)
/// to add the style logic with the same id.
///
/// Typically, your styles will be added in your platform-specific executable,
/// before your application is run.
/// </remarks>
/// <example>
/// Style the widget, with no direct access to platform-specifics
/// <code><![CDATA[
/// Style.Add<Form>("mainForm", widget => {
/// widget.Title = "Hello!";
/// });
/// ]]></code>
///
/// Style based on a platform-specific handler (this is for Mac OS X):
/// <code><![CDATA[
/// Style.Add<Eto.Mac.Forms.FormHandler>("mainForm", handler => {
/// handler.Control.CollectionBehavior |= NSWindowCollectionBehavior.FullScreenPrimary;
/// });
/// Style.Add<Eto.Mac.Forms.ApplicationHandler>("application", handler => {
/// handler.EnableFullScreen ();
/// });
///
/// // create the UI (typically this is in your UI library, not in the platform-specific assembly)
/// var app = new Application {
/// Style = "application"; // will apply the style here
/// };
///
/// app.Initialized += delegate {
/// app.MainForm = new Form { Style = "mainForm" }; // apply the mainForm style
/// app.MainForm.Show ();
/// };
///
/// ]]></code>
/// </example>
public static class Style
{
static readonly Dictionary<object, IList<Action<Widget>>> styleMap = new Dictionary<object, IList<Action<Widget>>>();
static readonly Dictionary<object, IList<Action<Widget>>> cascadingStyleMap = new Dictionary<object, IList<Action<Widget>>>();
#region Events
/// <summary>
/// Event to handle when a widget has being styled
/// </summary>
public static event Action<Widget> StyleWidget;
internal static void OnStyleWidget(Widget widget)
{
if (widget != null && !string.IsNullOrEmpty(widget.Style))
{
var styles = widget.Style.Split(' ');
for (int i = 0; i < styles.Length; i++)
{
var style = styles[i];
var styleHandlers = GetStyleList(style);
if (styleHandlers != null)
{
for (int j = 0; j < styleHandlers.Count; j++)
{
var styleHandler = styleHandlers[j];
styleHandler(widget);
}
}
}
}
if (StyleWidget != null)
StyleWidget(widget);
}
internal static void OnStyleWidgetDefaults(Widget widget)
{
if (widget == null)
return;
var styleHandlers = GetCascadingStyleList(widget.GetType());
if (styleHandlers == null)
return;
for (int i = 0; i < styleHandlers.Count; i++)
{
var styleHandler = styleHandlers[i];
styleHandler(widget);
}
}
internal static void OnStyleWidgetDefaults(Widget.IHandler handler)
{
if (handler == null)
return;
var widget = handler.Widget;
if (widget == null)
return;
var styleHandlers = GetCascadingStyleList(handler.GetType());
if (styleHandlers == null)
return;
for (int i = 0; i < styleHandlers.Count; i++)
{
var styleHandler = styleHandlers[i];
styleHandler(widget);
}
}
#endregion
/// <summary>
/// Adds a style for a widget
/// </summary>
/// <remarks>
/// Styling a widget allows you to access the widget, but not the platform-specific controls (in a type-safe way).
///
/// Typically, you'd use Style.Add<H>(string, StyleHandler<H>) instead, which will add a style based on the widget handler, which
/// will give you direct and type safe access to platform-specifics of the widget.
/// </remarks>
/// <typeparam name="TWidget">Type of the widget to style</typeparam>
/// <param name="style">Identifier of the style</param>
/// <param name="handler">Delegate with your logic to style the widget</param>
public static void Add<TWidget>(string style, StyleWidgetHandler<TWidget> handler)
where TWidget: Widget
{
var list = CreateStyleList((object)style ?? typeof(TWidget));
list.Add(widget =>
{
var control = widget as TWidget;
if (control != null)
handler(control);
});
cascadingStyleMap.Clear();
}
/// <summary>
/// Adds a style for a widget handler
/// </summary>
/// <remarks>
/// Styling a widget handler allows you to access both the widget and the platform-specifics for the widget.
///
/// To use this, you would have to add a reference to one of the Eto.*.dll's so that you can utilize
/// the platform handler directly. Typically this would be called before your application is run.
/// </remarks>
/// <typeparam name="THandler">Type of the handler that should be styled</typeparam>
/// <param name="style">Identifier for the style</param>
/// <param name="styleHandler">Delegate with your logic to style the widget and/or platform control</param>
public static void Add<THandler>(string style, StyleHandler<THandler> styleHandler)
where THandler: class, Widget.IHandler
{
var list = CreateStyleList((object)style ?? typeof(THandler));
list.Add(widget =>
{
var handler = widget.Handler as THandler;
if (handler != null)
styleHandler(handler);
});
cascadingStyleMap.Clear();
}
static IList<Action<Widget>> CreateStyleList(object style)
{
IList<Action<Widget>> styleHandlers;
if (!styleMap.TryGetValue(style, out styleHandlers))
{
styleHandlers = new List<Action<Widget>>();
styleMap[style] = styleHandlers;
}
return styleHandlers;
}
static IList<Action<Widget>> GetStyleList(object style)
{
IList<Action<Widget>> styleHandlers;
return styleMap.TryGetValue(style, out styleHandlers) ? styleHandlers : null;
}
static IList<Action<Widget>> GetCascadingStyleList(Type type)
{
// get a cached list of cascading styles so we don't have to traverse each time
IList<Action<Widget>> childHandlers;
if (cascadingStyleMap.TryGetValue(type, out childHandlers))
{
return childHandlers;
}
// don't have a cascading style set, so build one
// styles are applied in order from superclass styles down to subclass styles.
IEnumerable<Action<Widget>> styleHandlers = Enumerable.Empty<Action<Widget>>();
Type currentType = type;
do
{
IList<Action<Widget>> typeStyles;
if (styleMap.TryGetValue(currentType, out typeStyles) && typeStyles != null)
styleHandlers = typeStyles.Concat(styleHandlers);
}
while ((currentType = currentType.GetBaseType()) != null);
// create a cached list, but if its empty don't store it
childHandlers = styleHandlers.ToList();
if (childHandlers.Count == 0)
childHandlers = null;
cascadingStyleMap.Add(type, childHandlers);
return childHandlers;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface ICountryRegionOriginalData : ISchemaBaseOriginalData
{
int Code { get; }
string Name { get; }
}
public partial class CountryRegion : OGM<CountryRegion, CountryRegion.CountryRegionData, System.String>, ISchemaBase, INeo4jBase, ICountryRegionOriginalData
{
#region Initialize
static CountryRegion()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
#region LoadByCode
RegisterQuery(nameof(LoadByCode), (query, alias) => query.
Where(alias.Code == Parameter.New<string>(Param0)));
#endregion
AdditionalGeneratedStoredQueries();
}
public static CountryRegion LoadByCode(string code)
{
return FromQuery(nameof(LoadByCode), new Parameter(Param0, code)).FirstOrDefault();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, CountryRegion> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.CountryRegionAlias, IWhereQuery> query)
{
q.CountryRegionAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.CountryRegion.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"CountryRegion => Code : {this.Code}, Name : {this.Name}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new CountryRegionData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.Code == null)
throw new PersistenceException(string.Format("Cannot save CountryRegion with key '{0}' because the Code cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.Name == null)
throw new PersistenceException(string.Format("Cannot save CountryRegion with key '{0}' because the Name cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save CountryRegion with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class CountryRegionData : Data<System.String>
{
public CountryRegionData()
{
}
public CountryRegionData(CountryRegionData data)
{
Code = data.Code;
Name = data.Name;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "CountryRegion";
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("Code", Conversion<int, long>.Convert(Code));
dictionary.Add("Name", Name);
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("Code", out value))
Code = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("Name", out value))
Name = (string)value;
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface ICountryRegion
public int Code { get; set; }
public string Name { get; set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface ICountryRegion
public int Code { get { LazyGet(); return InnerData.Code; } set { if (LazySet(Members.Code, InnerData.Code, value)) InnerData.Code = value; } }
public string Name { get { LazyGet(); return InnerData.Name; } set { if (LazySet(Members.Name, InnerData.Name, value)) InnerData.Name = value; } }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static CountryRegionMembers members = null;
public static CountryRegionMembers Members
{
get
{
if (members == null)
{
lock (typeof(CountryRegion))
{
if (members == null)
members = new CountryRegionMembers();
}
}
return members;
}
}
public class CountryRegionMembers
{
internal CountryRegionMembers() { }
#region Members for interface ICountryRegion
public Property Code { get; } = Datastore.AdventureWorks.Model.Entities["CountryRegion"].Properties["Code"];
public Property Name { get; } = Datastore.AdventureWorks.Model.Entities["CountryRegion"].Properties["Name"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static CountryRegionFullTextMembers fullTextMembers = null;
public static CountryRegionFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(CountryRegion))
{
if (fullTextMembers == null)
fullTextMembers = new CountryRegionFullTextMembers();
}
}
return fullTextMembers;
}
}
public class CountryRegionFullTextMembers
{
internal CountryRegionFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(CountryRegion))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["CountryRegion"];
}
}
return entity;
}
private static CountryRegionEvents events = null;
public static CountryRegionEvents Events
{
get
{
if (events == null)
{
lock (typeof(CountryRegion))
{
if (events == null)
events = new CountryRegionEvents();
}
}
return events;
}
}
public class CountryRegionEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<CountryRegion, EntityEventArgs> onNew;
public event EventHandler<CountryRegion, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<CountryRegion, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((CountryRegion)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<CountryRegion, EntityEventArgs> onDelete;
public event EventHandler<CountryRegion, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<CountryRegion, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((CountryRegion)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<CountryRegion, EntityEventArgs> onSave;
public event EventHandler<CountryRegion, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<CountryRegion, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((CountryRegion)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnCode
private static bool onCodeIsRegistered = false;
private static EventHandler<CountryRegion, PropertyEventArgs> onCode;
public static event EventHandler<CountryRegion, PropertyEventArgs> OnCode
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onCodeIsRegistered)
{
Members.Code.Events.OnChange -= onCodeProxy;
Members.Code.Events.OnChange += onCodeProxy;
onCodeIsRegistered = true;
}
onCode += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onCode -= value;
if (onCode == null && onCodeIsRegistered)
{
Members.Code.Events.OnChange -= onCodeProxy;
onCodeIsRegistered = false;
}
}
}
}
private static void onCodeProxy(object sender, PropertyEventArgs args)
{
EventHandler<CountryRegion, PropertyEventArgs> handler = onCode;
if ((object)handler != null)
handler.Invoke((CountryRegion)sender, args);
}
#endregion
#region OnName
private static bool onNameIsRegistered = false;
private static EventHandler<CountryRegion, PropertyEventArgs> onName;
public static event EventHandler<CountryRegion, PropertyEventArgs> OnName
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onNameIsRegistered)
{
Members.Name.Events.OnChange -= onNameProxy;
Members.Name.Events.OnChange += onNameProxy;
onNameIsRegistered = true;
}
onName += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onName -= value;
if (onName == null && onNameIsRegistered)
{
Members.Name.Events.OnChange -= onNameProxy;
onNameIsRegistered = false;
}
}
}
}
private static void onNameProxy(object sender, PropertyEventArgs args)
{
EventHandler<CountryRegion, PropertyEventArgs> handler = onName;
if ((object)handler != null)
handler.Invoke((CountryRegion)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<CountryRegion, PropertyEventArgs> onModifiedDate;
public static event EventHandler<CountryRegion, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<CountryRegion, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((CountryRegion)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<CountryRegion, PropertyEventArgs> onUid;
public static event EventHandler<CountryRegion, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<CountryRegion, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((CountryRegion)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region ICountryRegionOriginalData
public ICountryRegionOriginalData OriginalVersion { get { return this; } }
#region Members for interface ICountryRegion
int ICountryRegionOriginalData.Code { get { return OriginalData.Code; } }
string ICountryRegionOriginalData.Name { get { return OriginalData.Name; } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
#region Copyright & License
//
// Copyright 2001-2005 The Apache Software Foundation
//
// 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
// .NET Compact Framework 1.0 has no support for WindowsIdentity
#if !NETCF
// MONO 1.0 has no support for Win32 Logon APIs
#if !MONO
// SSCLI 1.0 has no support for Win32 Logon APIs
#if !SSCLI
// We don't want framework or platform specific code in the CLI version of log4net
#if !CLI_1_0
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using log4net.Core;
namespace log4net.Util
{
/// <summary>
/// Impersonate a Windows Account
/// </summary>
/// <remarks>
/// <para>
/// This <see cref="SecurityContext"/> impersonates a Windows account.
/// </para>
/// <para>
/// How the impersonation is done depends on the value of <see cref="Impersonate"/>.
/// This allows the context to either impersonate a set of user credentials specified
/// using username, domain name and password or to revert to the process credentials.
/// </para>
/// </remarks>
public class WindowsSecurityContext : SecurityContext, IOptionHandler
{
/// <summary>
/// The impersonation modes for the <see cref="WindowsSecurityContext"/>
/// </summary>
/// <remarks>
/// <para>
/// See the <see cref="WindowsSecurityContext.Credentials"/> property for
/// details.
/// </para>
/// </remarks>
public enum ImpersonationMode
{
/// <summary>
/// Impersonate a user using the credentials supplied
/// </summary>
User,
/// <summary>
/// Revert this the thread to the credentials of the process
/// </summary>
Process
}
#region Member Variables
private ImpersonationMode m_impersonationMode = ImpersonationMode.User;
private string m_userName;
private string m_domainName = Environment.MachineName;
private string m_password;
private WindowsIdentity m_identity;
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>
/// <para>
/// Default constructor
/// </para>
/// </remarks>
public WindowsSecurityContext()
{
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the impersonation mode for this security context
/// </summary>
/// <value>
/// The impersonation mode for this security context
/// </value>
/// <remarks>
/// <para>
/// Impersonate either a user with user credentials or
/// revert this thread to the credentials of the process.
/// The value is one of the <see cref="ImpersonationMode"/>
/// enum.
/// </para>
/// <para>
/// The default value is <see cref="ImpersonationMode.User"/>
/// </para>
/// <para>
/// When the mode is set to <see cref="ImpersonationMode.User"/>
/// the user's credentials are established using the
/// <see cref="UserName"/>, <see cref="DomainName"/> and <see cref="Password"/>
/// values.
/// </para>
/// <para>
/// When the mode is set to <see cref="ImpersonationMode.Process"/>
/// no other properties need to be set. If the calling thread is
/// impersonating then it will be reverted back to the process credentials.
/// </para>
/// </remarks>
public ImpersonationMode Credentials
{
get { return m_impersonationMode; }
set { m_impersonationMode = value; }
}
/// <summary>
/// Gets or sets the Windows username for this security context
/// </summary>
/// <value>
/// The Windows username for this security context
/// </value>
/// <remarks>
/// <para>
/// This property must be set if <see cref="Credentials"/>
/// is set to <see cref="ImpersonationMode.User"/> (the default setting).
/// </para>
/// </remarks>
public string UserName
{
get { return m_userName; }
set { m_userName = value; }
}
/// <summary>
/// Gets or sets the Windows domain name for this security context
/// </summary>
/// <value>
/// The Windows domain name for this security context
/// </value>
/// <remarks>
/// <para>
/// The default value for <see cref="DomainName"/> is the local machine name
/// taken from the <see cref="Environment.MachineName"/> property.
/// </para>
/// <para>
/// This property must be set if <see cref="Credentials"/>
/// is set to <see cref="ImpersonationMode.User"/> (the default setting).
/// </para>
/// </remarks>
public string DomainName
{
get { return m_domainName; }
set { m_domainName = value; }
}
/// <summary>
/// Sets the password for the Windows account specified by the <see cref="UserName"/> and <see cref="DomainName"/> properties.
/// </summary>
/// <value>
/// The password for the Windows account specified by the <see cref="UserName"/> and <see cref="DomainName"/> properties.
/// </value>
/// <remarks>
/// <para>
/// This property must be set if <see cref="Credentials"/>
/// is set to <see cref="ImpersonationMode.User"/> (the default setting).
/// </para>
/// </remarks>
public string Password
{
set { m_password = value; }
}
#endregion
#region IOptionHandler Members
/// <summary>
/// Initialize the SecurityContext based on the options set.
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// <para>
/// The security context will try to Logon the specified user account and
/// capture a primary token for impersonation.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">The required <see cref="UserName" />,
/// <see cref="DomainName" /> or <see cref="Password" /> properties were not specified.</exception>
public void ActivateOptions()
{
if (m_impersonationMode == ImpersonationMode.User)
{
if (m_userName == null) throw new ArgumentNullException("m_userName");
if (m_domainName == null) throw new ArgumentNullException("m_domainName");
if (m_password == null) throw new ArgumentNullException("m_password");
m_identity = LogonUser(m_userName, m_domainName, m_password);
}
}
#endregion
/// <summary>
/// Impersonate the Windows account specified by the <see cref="UserName"/> and <see cref="DomainName"/> properties.
/// </summary>
/// <param name="state">caller provided state</param>
/// <returns>
/// An <see cref="IDisposable"/> instance that will revoke the impersonation of this SecurityContext
/// </returns>
/// <remarks>
/// <para>
/// Depending on the <see cref="Credentials"/> property either
/// impersonate a user using credentials supplied or revert
/// to the process credentials.
/// </para>
/// </remarks>
public override IDisposable Impersonate(object state)
{
if (m_impersonationMode == ImpersonationMode.User)
{
if (m_identity != null)
{
return new DisposableImpersonationContext(m_identity.Impersonate());
}
}
else if (m_impersonationMode == ImpersonationMode.Process)
{
// Impersonate(0) will revert to the process credentials
return new DisposableImpersonationContext(WindowsIdentity.Impersonate(IntPtr.Zero));
}
return null;
}
/// <summary>
/// Create a <see cref="WindowsIdentity"/> given the userName, domainName and password.
/// </summary>
/// <param name="userName">the user name</param>
/// <param name="domainName">the domain name</param>
/// <param name="password">the password</param>
/// <returns>the <see cref="WindowsIdentity"/> for the account specified</returns>
/// <remarks>
/// <para>
/// Uses the Windows API call LogonUser to get a principal token for the account. This
/// token is used to initialize the WindowsIdentity.
/// </para>
/// </remarks>
private static WindowsIdentity LogonUser(string userName, string domainName, string password)
{
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
// Call LogonUser to obtain a handle to an access token.
IntPtr tokenHandle = IntPtr.Zero;
if(!LogonUser(userName, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle))
{
NativeError error = NativeError.GetLastError();
throw new Exception("Failed to LogonUser ["+userName+"] in Domain ["+domainName+"]. Error: "+ error.ToString());
}
const int SecurityImpersonation = 2;
IntPtr dupeTokenHandle = IntPtr.Zero;
if(!DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle))
{
NativeError error = NativeError.GetLastError();
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
throw new Exception("Failed to DuplicateToken after LogonUser. Error: " + error.ToString());
}
WindowsIdentity identity = new WindowsIdentity(dupeTokenHandle);
// Free the tokens.
if (dupeTokenHandle != IntPtr.Zero)
{
CloseHandle(dupeTokenHandle);
}
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
return identity;
}
#region Native Method Stubs
[DllImport("advapi32.dll", SetLastError=true)]
private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
private extern static bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
private extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
#endregion
#region DisposableImpersonationContext class
/// <summary>
/// Adds <see cref="IDisposable"/> to <see cref="WindowsImpersonationContext"/>
/// </summary>
/// <remarks>
/// <para>
/// Helper class to expose the <see cref="WindowsImpersonationContext"/>
/// through the <see cref="IDisposable"/> interface.
/// </para>
/// </remarks>
private sealed class DisposableImpersonationContext : IDisposable
{
private readonly WindowsImpersonationContext m_impersonationContext;
/// <summary>
/// Constructor
/// </summary>
/// <param name="impersonationContext">the impersonation context being wrapped</param>
/// <remarks>
/// <para>
/// Constructor
/// </para>
/// </remarks>
public DisposableImpersonationContext(WindowsImpersonationContext impersonationContext)
{
m_impersonationContext = impersonationContext;
}
/// <summary>
/// Revert the impersonation
/// </summary>
/// <remarks>
/// <para>
/// Revert the impersonation
/// </para>
/// </remarks>
public void Dispose()
{
m_impersonationContext.Undo();
}
}
#endregion
}
}
#endif // !CLI_1_0
#endif // !SSCLI
#endif // !MONO
#endif // !NETCF
| |
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Microsoft.Win32.SafeHandles;
public class Tests {
public class MyHandle : SafeHandle {
public MyHandle () : base (IntPtr.Zero, true)
{
}
public MyHandle (IntPtr x) : base (x, true)
{
}
public override bool IsInvalid {
get {
return false;
}
}
protected override bool ReleaseHandle ()
{
return true;
}
}
//
// No default public constructor here, this is so we can test
// that proper exceptions are thrown
//
public class MyHandleNoCtor : SafeHandle {
public MyHandleNoCtor (IntPtr handle) : base (handle, true)
{
}
public override bool IsInvalid {
get {
return false;
}
}
protected override bool ReleaseHandle ()
{
return true;
}
}
[DllImport ("libtest")]
public static extern void mono_safe_handle_ref (ref MyHandle handle);
[DllImport ("libtest", EntryPoint="mono_safe_handle_ref")]
public static extern void mono_safe_handle_ref2 (ref MyHandleNoCtor handle);
public static int test_0_safehandle_ref_noctor ()
{
MyHandleNoCtor m = new MyHandleNoCtor ((IntPtr) 0xdead);
try {
mono_safe_handle_ref2 (ref m);
} catch (MissingMethodException e){
Console.WriteLine ("Good: got exception requried");
return 0;
}
return 1;
}
public static int test_0_safehandle_ref ()
{
MyHandle m = new MyHandle ((IntPtr) 0xdead);
mono_safe_handle_ref (ref m);
if (m.DangerousGetHandle () != (IntPtr) 0x800d){
Console.WriteLine ("test_0_safehandle_ref: fail; Expected 0x800d, got: {0:x}", m.DangerousGetHandle ());
return 1;
}
Console.WriteLine ("test_0_safehandle_ref: pass");
return 0;
}
[DllImport ("libtest")]
public static extern int mono_xr (SafeHandle sh);
public static int test_0_marshal_safehandle_argument ()
{
SafeHandle s = new SafeFileHandle ((IntPtr) 0xeadcafe, true);
if (mono_xr (s) != (0xeadcafe + 1234))
return 1;
return 0;
}
public static int test_0_marshal_safehandle_argument_null ()
{
try {
mono_xr (null);
} catch (ArgumentNullException){
return 0;
}
return 1;
}
[StructLayout (LayoutKind.Sequential)]
public struct StringOnStruct {
public string a;
}
[StructLayout (LayoutKind.Sequential)]
public struct StructTest {
public int a;
public SafeHandle handle1;
public SafeHandle handle2;
public int b;
}
[StructLayout (LayoutKind.Sequential)]
public struct StructTest1 {
public SafeHandle a;
}
[DllImport ("libtest")]
public static extern int mono_safe_handle_struct_ref (ref StructTest test);
[DllImport ("libtest")]
public static extern int mono_safe_handle_struct (StructTest test);
[DllImport ("libtest")]
public static extern int mono_safe_handle_struct_simple (StructTest1 test);
[DllImport ("libtest", EntryPoint="mono_safe_handle_return")]
public static extern SafeHandle mono_safe_handle_return_1 ();
[DllImport ("libtest", EntryPoint="mono_safe_handle_return")]
public static extern MyHandle mono_safe_handle_return ();
[DllImport ("libtest", EntryPoint="mono_safe_handle_return")]
public static extern MyHandleNoCtor mono_safe_handle_return_2 ();
static StructTest x = new StructTest ();
public static int test_0_safehandle_return_noctor ()
{
try {
MyHandleNoCtor m = mono_safe_handle_return_2 ();
} catch (MissingMethodException e){
Console.WriteLine ("GOOD: got exception required: " + e);
return 0;
}
Console.WriteLine ("Failed, expected an exception because there is no paramterless ctor");
return 1;
}
public static int test_0_safehandle_return_exc ()
{
try {
SafeHandle x = mono_safe_handle_return_1 ();
} catch (MarshalDirectiveException){
Console.WriteLine ("GOOD: got exception required");
return 0;
}
Console.WriteLine ("Error: should have generated an exception, since SafeHandle is abstract");
return 1;
}
public static int test_0_safehandle_return ()
{
SafeHandle x = mono_safe_handle_return ();
Console.WriteLine ("Got the following handle: {0}", x.DangerousGetHandle ());
return x.DangerousGetHandle () == (IntPtr) 0x1000f00d ? 0 : 1;
}
public static int test_0_marshal_safehandle_field ()
{
x.a = 1234;
x.b = 8743;
x.handle1 = new SafeFileHandle ((IntPtr) 0x7080feed, false);
x.handle2 = new SafeFileHandle ((IntPtr) 0x1234abcd, false);
if (mono_safe_handle_struct (x) != 0xf00f)
return 1;
return 0;
}
public static int test_0_marshal_safehandle_field_ref ()
{
x.a = 1234;
x.b = 8743;
x.handle1 = new SafeFileHandle ((IntPtr) 0x7080feed, false);
x.handle2 = new SafeFileHandle ((IntPtr) 0x1234abcd, false);
if (mono_safe_handle_struct_ref (ref x) != 0xf00d)
return 1;
return 0;
}
public static int test_0_simple ()
{
StructTest1 s = new StructTest1 ();
s.a = new SafeFileHandle ((IntPtr)1234, false);
return mono_safe_handle_struct_simple (s) == 2468 ? 0 : 1;
}
public static int test_0_struct_empty ()
{
StructTest1 s = new StructTest1 ();
try {
mono_safe_handle_struct_simple (s);
} catch (ArgumentNullException){
return 0;
}
return 1;
}
public static int test_0_sf_dispose ()
{
SafeFileHandle sf = new SafeFileHandle ((IntPtr) 0x0d00d, false);
sf.Dispose ();
try {
mono_xr (sf);
} catch (ObjectDisposedException){
return 0;
}
return 1;
}
static int Error (string msg)
{
Console.WriteLine ("Error: " + msg);
return 1;
}
static int Main ()
{
return TestDriver.RunTests (typeof (Tests));
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Timers;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Grid.Framework;
using Timer=System.Timers.Timer;
namespace OpenSim.Grid.MessagingServer.Modules
{
public class MessageService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private MessageServerConfig m_cfg;
private UserDataBaseService m_userDataBaseService;
private IGridServiceCore m_messageCore;
private IInterServiceUserService m_userServerModule;
private IMessageRegionLookup m_regionModule;
// a dictionary of all current presences this server knows about
private Dictionary<UUID, UserPresenceData> m_presences = new Dictionary<UUID,UserPresenceData>();
public MessageService(MessageServerConfig cfg, IGridServiceCore messageCore, UserDataBaseService userDataBaseService)
{
m_cfg = cfg;
m_messageCore = messageCore;
m_userDataBaseService = userDataBaseService;
//???
UserConfig uc = new UserConfig();
uc.DatabaseConnect = cfg.DatabaseConnect;
uc.DatabaseProvider = cfg.DatabaseProvider;
}
public void Initialise()
{
}
public void PostInitialise()
{
IInterServiceUserService messageUserServer;
if (m_messageCore.TryGet<IInterServiceUserService>(out messageUserServer))
{
m_userServerModule = messageUserServer;
}
IMessageRegionLookup messageRegion;
if (m_messageCore.TryGet<IMessageRegionLookup>(out messageRegion))
{
m_regionModule = messageRegion;
}
}
public void RegisterHandlers()
{
//have these in separate method as some servers restart the http server and reregister all the handlers.
}
#region FriendList Methods
/// <summary>
/// Process Friendlist subscriptions for a user
/// The login method calls this for a User
/// </summary>
/// <param name="userpresence">The Agent we're processing the friendlist subscriptions for</param>
private void ProcessFriendListSubscriptions(UserPresenceData userpresence)
{
lock (m_presences)
{
m_presences[userpresence.agentData.AgentID] = userpresence;
}
Dictionary<UUID, FriendListItem> uFriendList = userpresence.friendData;
foreach (KeyValuePair<UUID, FriendListItem> pair in uFriendList)
{
UserPresenceData friendup = null;
lock (m_presences)
{
m_presences.TryGetValue(pair.Key, out friendup);
}
if (friendup != null)
{
SubscribeToPresenceUpdates(userpresence, friendup, pair.Value);
}
}
}
/// <summary>
/// Enqueues a presence update, sending info about user 'talkingAbout' to user 'receiver'.
/// </summary>
/// <param name="talkingAbout">We are sending presence information about this user.</param>
/// <param name="receiver">We are sending the presence update to this user</param>
private void enqueuePresenceUpdate(UserPresenceData talkingAbout, UserPresenceData receiver)
{
UserAgentData p2Handle = m_userDataBaseService.GetUserAgentData(receiver.agentData.AgentID);
if (p2Handle != null)
{
if (receiver.lookupUserRegionYN)
{
receiver.regionData.regionHandle = p2Handle.Handle;
}
else
{
receiver.lookupUserRegionYN = true; // TODO Huh?
}
PresenceInformer friendlistupdater = new PresenceInformer();
friendlistupdater.presence1 = talkingAbout;
friendlistupdater.presence2 = receiver;
friendlistupdater.OnGetRegionData += m_regionModule.GetRegionInfo;
friendlistupdater.OnDone += PresenceUpdateDone;
Util.FireAndForget(friendlistupdater.go);
}
else
{
m_log.WarnFormat("no data found for user {0}", receiver.agentData.AgentID);
// Skip because we can't find any data on the user
}
}
/// <summary>
/// Does the necessary work to subscribe one agent to another's presence notifications
/// Gets called by ProcessFriendListSubscriptions. You shouldn't call this directly
/// unless you know what you're doing
/// </summary>
/// <param name="userpresence">P1</param>
/// <param name="friendpresence">P2</param>
/// <param name="uFriendListItem"></param>
private void SubscribeToPresenceUpdates(UserPresenceData userpresence,
UserPresenceData friendpresence,
FriendListItem uFriendListItem)
{
// Can the friend see me online?
if ((uFriendListItem.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0)
{
// tell user to update friend about user's presence changes
if (!userpresence.subscriptionData.Contains(friendpresence.agentData.AgentID))
{
userpresence.subscriptionData.Add(friendpresence.agentData.AgentID);
}
// send an update about user's presence to the friend
enqueuePresenceUpdate(userpresence, friendpresence);
}
// Can I see the friend online?
if ((uFriendListItem.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0)
{
// tell friend to update user about friend's presence changes
if (!friendpresence.subscriptionData.Contains(userpresence.agentData.AgentID))
{
friendpresence.subscriptionData.Add(userpresence.agentData.AgentID);
}
// send an update about friend's presence to user.
enqueuePresenceUpdate(friendpresence, userpresence);
}
}
/// <summary>
/// Logoff Processor. Call this to clean up agent presence data and send logoff presence notifications
/// </summary>
/// <param name="AgentID"></param>
private void ProcessLogOff(UUID AgentID)
{
m_log.Info("[LOGOFF]: Processing Logoff");
UserPresenceData userPresence = null;
lock (m_presences)
{
m_presences.TryGetValue(AgentID, out userPresence);
}
if (userPresence != null) // found the user
{
List<UUID> AgentsNeedingNotification = userPresence.subscriptionData;
userPresence.OnlineYN = false;
for (int i = 0; i < AgentsNeedingNotification.Count; i++)
{
UserPresenceData friendPresence = null;
lock (m_presences)
{
m_presences.TryGetValue(AgentsNeedingNotification[i], out friendPresence);
}
// This might need to be enumerated and checked before we try to remove it.
if (friendPresence != null)
{
lock (friendPresence)
{
// no updates for this user anymore
friendPresence.subscriptionData.Remove(AgentID);
// set user's entry in the friend's list to offline (if it exists)
if (friendPresence.friendData.ContainsKey(AgentID))
{
friendPresence.friendData[AgentID].onlinestatus = false;
}
}
enqueuePresenceUpdate(userPresence, friendPresence);
}
}
}
}
#endregion
private void PresenceUpdateDone(PresenceInformer obj)
{
obj.OnGetRegionData -= m_regionModule.GetRegionInfo;
obj.OnDone -= PresenceUpdateDone;
}
#region UserServer Comms
/// <summary>
/// Returns a list of FriendsListItems that describe the friends and permissions in the friend
/// relationship for UUID friendslistowner. For faster lookup, we index by friend's UUID.
/// </summary>
/// <param name="friendlistowner">The agent that we're retreiving the friends Data for.</param>
private Dictionary<UUID, FriendListItem> GetUserFriendList(UUID friendlistowner)
{
Dictionary<UUID, FriendListItem> buddies = new Dictionary<UUID,FriendListItem>();
try
{
Hashtable param = new Hashtable();
param["ownerID"] = friendlistowner.ToString();
IList parameters = new ArrayList();
parameters.Add(param);
XmlRpcRequest req = new XmlRpcRequest("get_user_friend_list", parameters);
XmlRpcResponse resp = req.Send(m_cfg.UserServerURL, 3000);
Hashtable respData = (Hashtable)resp.Value;
if (respData.Contains("avcount"))
{
buddies = ConvertXMLRPCDataToFriendListItemList(respData);
}
}
catch (WebException e)
{
m_log.Warn("Error when trying to fetch Avatar's friends list: " +
e.Message);
// Return Empty list (no friends)
}
return buddies;
}
/// <summary>
/// Converts XMLRPC Friend List to FriendListItem Object
/// </summary>
/// <param name="data">XMLRPC response data Hashtable</param>
/// <returns></returns>
public Dictionary<UUID, FriendListItem> ConvertXMLRPCDataToFriendListItemList(Hashtable data)
{
Dictionary<UUID, FriendListItem> buddies = new Dictionary<UUID,FriendListItem>();
int buddycount = Convert.ToInt32((string)data["avcount"]);
for (int i = 0; i < buddycount; i++)
{
FriendListItem buddylistitem = new FriendListItem();
buddylistitem.FriendListOwner = new UUID((string)data["ownerID" + i.ToString()]);
buddylistitem.Friend = new UUID((string)data["friendID" + i.ToString()]);
buddylistitem.FriendListOwnerPerms = (uint)Convert.ToInt32((string)data["ownerPerms" + i.ToString()]);
buddylistitem.FriendPerms = (uint)Convert.ToInt32((string)data["friendPerms" + i.ToString()]);
buddies.Add(buddylistitem.Friend, buddylistitem);
}
return buddies;
}
/// <summary>
/// UserServer sends an expect_user method
/// this handles the method and provisions the
/// necessary info for presence to work
/// </summary>
/// <param name="request">UserServer Data</param>
/// <returns></returns>
public XmlRpcResponse UserLoggedOn(XmlRpcRequest request, IPEndPoint remoteClient)
{
try
{
Hashtable requestData = (Hashtable)request.Params[0];
AgentCircuitData agentData = new AgentCircuitData();
agentData.SessionID = new UUID((string)requestData["sessionid"]);
agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]);
agentData.firstname = (string)requestData["firstname"];
agentData.lastname = (string)requestData["lastname"];
agentData.AgentID = new UUID((string)requestData["agentid"]);
agentData.circuitcode = Convert.ToUInt32(requestData["circuit_code"]);
agentData.CapsPath = (string)requestData["caps_path"];
if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
{
agentData.child = true;
}
else
{
agentData.startpos =
new Vector3(Convert.ToSingle(requestData["positionx"]),
Convert.ToSingle(requestData["positiony"]),
Convert.ToSingle(requestData["positionz"]));
agentData.child = false;
}
ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
m_log.InfoFormat("[LOGON]: User {0} {1} logged into region {2} as {3} agent, building indexes for user",
agentData.firstname, agentData.lastname, regionHandle, agentData.child ? "child" : "root");
UserPresenceData up = new UserPresenceData();
up.agentData = agentData;
up.friendData = GetUserFriendList(agentData.AgentID);
up.regionData = m_regionModule.GetRegionInfo(regionHandle);
up.OnlineYN = true;
up.lookupUserRegionYN = false;
ProcessFriendListSubscriptions(up);
}
catch (Exception e)
{
m_log.WarnFormat("[LOGIN]: Exception on UserLoggedOn: {0}", e);
}
return new XmlRpcResponse();
}
/// <summary>
/// The UserServer got a Logoff message
/// Cleanup time for that user. Send out presence notifications
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse UserLoggedOff(XmlRpcRequest request, IPEndPoint remoteClient)
{
try
{
m_log.Info("[USERLOGOFF]: User logged off called");
Hashtable requestData = (Hashtable)request.Params[0];
UUID AgentID = new UUID((string)requestData["agentid"]);
ProcessLogOff(AgentID);
}
catch (Exception e)
{
m_log.WarnFormat("[USERLOGOFF]: Exception on UserLoggedOff: {0}", e);
}
return new XmlRpcResponse();
}
#endregion
public XmlRpcResponse GetPresenceInfoBulk(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable paramHash = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
// TODO check access (recv_key/send_key)
IList list = (IList)paramHash["uuids"];
// convert into List<UUID>
List<UUID> uuids = new List<UUID>();
for (int i = 0; i < list.Count; ++i)
{
UUID uuid;
if (UUID.TryParse((string)list[i], out uuid))
{
uuids.Add(uuid);
}
}
try {
Dictionary<UUID, FriendRegionInfo> infos = m_userDataBaseService.GetFriendRegionInfos(uuids);
m_log.DebugFormat("[FRIEND]: Got {0} region entries back.", infos.Count);
int count = 0;
foreach (KeyValuePair<UUID, FriendRegionInfo> pair in infos)
{
result["uuid_" + count] = pair.Key.ToString();
result["isOnline_" + count] = pair.Value.isOnline;
result["regionHandle_" + count] = pair.Value.regionHandle.ToString(); // XML-RPC doesn't know ulongs
++count;
}
result["count"] = count;
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
catch(Exception e) {
m_log.Error("Got exception:", e);
throw e;
}
}
public XmlRpcResponse AgentLocation(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
result["success"] = "FALSE";
if (m_userServerModule.SendToUserServer(requestData, "agent_location"))
result["success"] = "TRUE";
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
public XmlRpcResponse AgentLeaving(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
result["success"] = "FALSE";
if (m_userServerModule.SendToUserServer(requestData, "agent_leaving"))
result["success"] = "TRUE";
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
public XmlRpcResponse ProcessRegionShutdown(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
result["success"] = "FALSE";
UUID regionID;
if (UUID.TryParse((string)requestData["regionid"], out regionID))
{
m_log.DebugFormat("[PRESENCE] Processing region restart for {0}", regionID);
result["success"] = "TRUE";
foreach (UserPresenceData up in m_presences.Values)
{
if (up.regionData.UUID == regionID)
{
if (up.OnlineYN)
{
m_log.DebugFormat("[PRESENCE] Logging off {0} because the region they were in has gone", up.agentData.AgentID);
ProcessLogOff(up.agentData.AgentID);
}
}
}
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
}
}
| |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Data;
public class MenuHandler
{
public const String FC_BLUE = "Blue";
public const String FC_RED = "Red";
public const String FC_GREEN = "Green";
public const String FC_YELLOW = "Yellow";
public const String FC_WHITE = "White";
public HeightmapInflater Inflater;
public MultiplayerManager Multiplayer;
public Camera MainCamera;
bool camOrgReadyToChange = true; // True is camera is to be homed
Vector3 camOrgPos; // Camera's initial position
Quaternion camOrgRot; // Camera's initial rotation
public ControllerHandler ControlHandler;
public List<GameObject> Flags;
public List<GameObject> Grids;
public List<GameObject> DataPoints;
public List<GameObject> AxisLabels;
public List<GameObject> AxisGrids;
public bool GridsVisible;
public Variables Vars;
public FlagHandler flaghandler;
public System.Random R;
public MenuHandler (HeightmapInflater Inflater, Camera MainCamera, NetworkView nView)
{
this.Inflater = Inflater;
this.MainCamera = MainCamera;
this.Multiplayer = new MultiplayerManager(this, nView);
this.R = new System.Random();
this.ControlHandler = new ControllerHandler(ControllerHandler.ControllerType.Keyboard, MainCamera);
Flags = new List<GameObject>();
Grids = new List<GameObject>();
DataPoints = new List<GameObject>();
AxisLabels = new List<GameObject>();
AxisGrids = new List<GameObject>();
GridsVisible = true;
SaveCamHome(MainCamera.transform.position, MainCamera.transform.rotation);
flaghandler = new FlagHandler();
InitGUI();
}
public enum State {StateInitial=0,StateMultiplayer=1,StateSingleplayer=2,StateHelp=3};
private MenuHandler.State CurrentState;
public MenuInitial StateInitial;
public MenuHelp StateHelp;
public MenuSinglePlayer StateSingleplayer;
public MenuTabsSingleplayer TabsSingle;
public MenuTabsMultiplayer TabsMulti;
public MenuTabs Tabs;
public MenuHandler.State GetState(){return this.CurrentState;}
public void SetState(MenuHandler.State state){
this.CurrentState = state;
}
// Initialises the GUI
private void InitGUI(){
StateInitial = new MenuInitial(this);
StateHelp = new MenuHelp(this);
StateSingleplayer = new MenuSinglePlayer(this);
TabsSingle = new MenuTabsSingleplayer(this);
TabsMulti = new MenuTabsMultiplayer(this);
Tabs = TabsSingle;
SetState(MenuHandler.State.StateHelp);
}
public void InitMultiplayer(){
Tabs = TabsMulti;
//Destroy all TabsSingle objects
TabsSingle.RemoveAxisGrids();
TabsSingle.RemoveAxisGridLabels();
TabsSingle.RemoveDataPoints();
TabsSingle = new MenuTabsSingleplayer(this);
}
public void InitSingleplayer(){
Tabs = TabsSingle;
//Destroy all TabsMulti objects
TabsMulti = new MenuTabsMultiplayer(this);
}
public void OnGUI(){
switch (CurrentState) {
case State.StateInitial:
StateInitial.OnGUI();
break;
case State.StateHelp:
StateHelp.OnGUI();
break;
case State.StateSingleplayer:
StateSingleplayer.OnGUI();
Tabs.OnGUI();
break;
case State.StateMultiplayer:
StateSingleplayer.OnGUI();
Tabs.OnGUI();
break;
}
if(ShowingMessage){
GUIStyle style = new GUIStyle();
style.fontSize = 18;
double TimeSinceMessageStart = DateTime.Now.Subtract(MessageStart).TotalSeconds;
if(TimeSinceMessageStart < MessageFadeTime){
style.normal.textColor = Color.red;
GUI.Label(new Rect(Screen.width/2f - style.CalcSize(new GUIContent(Message)).x/2f,
Screen.height/4f - style.CalcSize(new GUIContent(Message)).y/2f,
style.CalcSize(new GUIContent(Message)).x,
style.CalcSize(new GUIContent(Message)).y),
Message,
style);
}else if(TimeSinceMessageStart < MessageFadeTime + MessageStopTime){
float alpha = (float)(1.0d - ((TimeSinceMessageStart - MessageFadeTime)/MessageStopTime));
style.normal.textColor = new Color(1.0f,0.0f,0.0f,alpha);
GUI.Label(new Rect(Screen.width/2f - style.CalcSize(new GUIContent(Message)).x/2f,
Screen.height/4f - style.CalcSize(new GUIContent(Message)).y/2f,
style.CalcSize(new GUIContent(Message)).x,
style.CalcSize(new GUIContent(Message)).y),
Message,
style);
}else{
ShowingMessage = false;
}
}
}
public void Update(){
// Detecting keyboard actions
ControlHandler.Update();
if(GetState() == State.StateSingleplayer || GetState() == State.StateMultiplayer){
Tabs.Update();
if(GetState() == State.StateMultiplayer && Network.peerType == NetworkPeerType.Client)
Multiplayer.Update();
}
for(int i=0; i<AxisLabels.Count; i++){
AxisLabels[i].transform.rotation = MainCamera.transform.rotation;
}
for(int i=0; i<Flags.Count; i++){
Flags[i].transform.LookAt(new Vector3(MainCamera.transform.position.x,
Flags[i].transform.position.y,
MainCamera.transform.position.z));
Flags[i].transform.rotation *= Quaternion.Euler(new Vector3(0,180,0));
}
}
bool ShowingMessage = false;
string Message;
DateTime MessageStart;
double MessageFadeTime = 1.5d;
double MessageStopTime = 1.5d;
public void ShowMessage(string message){
ShowingMessage = true;
Message = message;
MessageStart = DateTime.Now;
}
public GameObject CreateFlag(String annotation, Vector3 worldPos){
GameObject temp = (GameObject)Main.Instantiate(Inflater.Flag, worldPos + Vector3.down * 1.0F,
Quaternion.identity);
((FlagData)temp.GetComponent(typeof(FlagData))).SetID(R.Next(1,25000));
Flags.Add(temp);
UpdateFlags();
return temp;
}
public void CreateFlag(int ID, Vector3 WorldPosition, Vector3 DataPosition, string Annotation, string Col, int Tex){
GameObject temp = (GameObject)Main.Instantiate(Inflater.Flag, WorldPosition + Vector3.down * 1.0F,
Quaternion.identity);
Flags.Add(temp);
}
public GameObject CreateGrid(String name, int orientation){
switch(orientation){
case 0:
return CreateGrid(name, GridData.Orientation.UP_Y);
case 1:
return CreateGrid(name, GridData.Orientation.UP_X);
case 2:
return CreateGrid(name, GridData.Orientation.UP_Z);
default:
return CreateGrid(name, GridData.Orientation.UP_Y);
}
}
public GameObject CreateGrid(String name, GridData.Orientation orientation){
DataHandler dH = Inflater.dH;
GameObject temp = (GameObject) Main.Instantiate (Inflater.GridObject, new Vector3(), Quaternion.identity);
float[][] dataBounds = new float[][]{
new float[]{Inflater.Vars.MIN_X, Inflater.Vars.MAX_X},
new float[]{(float)dH.GetMinY(), (float)dH.GetMaxY()},
new float[]{Inflater.Vars.MIN_Z, Inflater.Vars.MAX_Z}
};
float[][] worldBounds = new float[][]{
new float[]{0, Inflater.theterrain.terrainData.size.x},
new float[]{0, Inflater.theterrain.terrainData.size.y},
new float[]{0, Inflater.theterrain.terrainData.size.z}
};
((GridData)temp.GetComponent(typeof(GridData))).Init(R.Next(1,25000), "", dataBounds, worldBounds, false, orientation);
Grids.Add(temp);
return temp;
}
public void HideGrids(){
for(int i=0; i<Grids.Count; i++){
Grids[i].renderer.enabled = false;
}
GridsVisible = false;
}
public void UnhideGrids(){
for(int i=0; i<Grids.Count; i++){
Grids[i].renderer.enabled = true;
}
GridsVisible = true;
}
public void DeleteAllFlags(){
if(Network.peerType == NetworkPeerType.Client){
for(int i=0; i<Flags.Count; i++){
Multiplayer.CallDeleteFlag(Flags[i].GetComponent<FlagData>().GetID());
Main.Destroy(Flags[i]);
}
Flags.Clear();
Tabs.DeleteAllFlags();
}else{
for(int i=0; i<Flags.Count; i++){
Main.Destroy(Flags[i]);
}
Tabs.DeleteAllFlags();
Flags.Clear();
}
}
public void DeleteAllGrids(){
if(Network.peerType == NetworkPeerType.Client){
for(int i=0; i<Grids.Count; i++){
Multiplayer.CallDeleteGrid(Grids[i].GetComponent<GridData>().GetID());
Main.Destroy (Grids[i]);
}
Grids.Clear();
Tabs.DeleteAllGrids();
}else{
for(int i=0; i<Grids.Count; i++){
Main.Destroy(Grids[i]);
}
Tabs.DeleteAllGrids();
Grids.Clear();
}
}
public void UpdateFlags(){
for(int i=0; i<Flags.Count; i++){
GameObject temp = Flags[i];
if(Inflater.TerrainVisible){
Vector3 newPos = new Vector3(temp.transform.position.x, Inflater.theterrain.SampleHeight(temp.transform.position) - 1f, temp.transform.position.z);
temp.transform.position = newPos;
temp.GetComponent<FlagData>().SetWorldPos(newPos);
}else{
Vector3 newPos = new Vector3(temp.transform.position.x, Inflater.Map.SampleHeight(temp.transform.position) - 1f, temp.transform.position.z);
temp.transform.position = new Vector3(temp.transform.position.x, Inflater.Map.SampleHeight(temp.transform.position) - 1f, temp.transform.position.z);
temp.GetComponent<FlagData>().SetWorldPos(newPos);
}
}
}
public void UpdateGrids(){
DataHandler dH = Inflater.dH;
float[][] dataBounds = new float[][]{
new float[]{Inflater.Vars.MIN_X, Inflater.Vars.MAX_X},
new float[]{(float)dH.GetMinY(), (float)dH.GetMaxY()},
new float[]{Inflater.Vars.MIN_Z, Inflater.Vars.MAX_Z}
};
float[][] worldBounds = new float[][]{
new float[]{0, Inflater.theterrain.terrainData.size.x},
new float[]{0, Inflater.theterrain.terrainData.size.y},
new float[]{0, Inflater.theterrain.terrainData.size.z}
};
for(int i=0; i<Grids.Count; i++){
GameObject GridObject = Grids[i];
GridData temp = (GridData)GridObject.GetComponent(typeof(GridData));
temp.Init(temp.GetID(), temp.GetName(), dataBounds, worldBounds, temp.IsSelected(), temp.GetOrientation(), true);
}
}
private static Texture2D _staticRectTexture;
private static GUIStyle _staticRectStyle;
// Note that this function is only meant to be called from OnGUI() functions.
public static void GUIDrawRect( Rect position, Color color )
{
if(_staticRectTexture == null)
{
_staticRectTexture = new Texture2D(1, 1);
}
if(_staticRectStyle == null)
{
_staticRectStyle = new GUIStyle();
}
_staticRectTexture.SetPixel(0, 0, color);
_staticRectTexture.Apply();
_staticRectStyle.normal.background = _staticRectTexture;
GUI.Box(position, GUIContent.none, _staticRectStyle);
}
// Remembers that camera is to be placed home the next time terrain is generated
public void ReadyCamHome() {
camOrgReadyToChange = true;
}
// Places the camera into its original home position
public void SaveCamHome(Vector3 camPos, Quaternion camRot) {
// Change the mpuose position to its home
this.camOrgPos = camPos;
this.camOrgRot = camRot;
camOrgReadyToChange = false;
}
/// <summary>
/// Places the camera into its original home position
/// </summary>
public void MoveCamHome() {
if (camOrgReadyToChange) {
// Change the mpuose position to its home
this.MainCamera.transform.position = this.camOrgPos;
this.MainCamera.transform.rotation = this.camOrgRot;
}
camOrgReadyToChange = false;
}
public void SetFlagImage(int choice, FlagHandler fh)
{
Texture tex = new Texture();
tex = (Texture2D)Resources.Load(fh.FLAG_PATH[choice] + "/" + fh.FLAG_IMAGE[choice]);
Flags[Flags.Count-1].transform.Find("Cube").renderer.material.mainTexture = tex;
}
public void SetFlagColour(Color c, String colorName)
{
Flags[Flags.Count-1].transform.Find("Cube").renderer.material.SetColor("_Color", c);
Flags[Flags.Count-1].GetComponent<FlagData>().SetFlagColorString(colorName);
}
/// <summary>
/// Used to transmit the message of terrain generation from
/// <see cref="Main"/> to <see cref="MenuSinglePlayer"/>.
/// </summary>
public void GenerateGranular(string DataSource, string TerrainType, string Filename, string Preset, bool regen, float scale, float colorScale){
StateSingleplayer.GenerateGranular(DataSource, TerrainType, Filename, Preset, regen, scale, colorScale);
}
/// <summary>
/// Used to transmit the message of terrain generation from
/// <see cref="Main"/> to <see cref="MenuSinglePlayer"/>.
/// </summary>
public void GenerateSmooth(string DataSource, string TerrainType, string Filename, string Preset, bool regen, float scale, float colorScale){
StateSingleplayer.GenerateSmooth(DataSource, TerrainType, Filename, Preset, regen, scale, colorScale);
}
/// <summary>
/// Used to transmit the message of terrain generation from
/// <see cref="Main"/> to <see cref="MenuSinglePlayer"/>.
/// </summary>
public void GenerateCylindrical(string DataSource, string TerrainType, string Filename, string Preset, bool regen, float scale, float colorScale){
StateSingleplayer.GenerateCylindrical(DataSource, TerrainType, Filename, Preset, regen, scale, colorScale);
}
}
| |
/*
* Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode
*
* 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 DateData = org.javarosa.core.model.data.DateData;
using DateTimeData = org.javarosa.core.model.data.DateTimeData;
using IAnswerData = org.javarosa.core.model.data.IAnswerData;
using StringData = org.javarosa.core.model.data.StringData;
using TreeElement = org.javarosa.core.model.instance.TreeElement;
using PropertyManager = org.javarosa.core.services.PropertyManager;
using Map = org.javarosa.core.util.Map;
using PropertyUtils = org.javarosa.core.util.PropertyUtils;
using System.Collections.Generic;
namespace org.javarosa.core.model.utils
{
/// <summary> The Question Preloader is responsible for maintaining a set of handlers which are capable
/// of parsing 'preload' elements, and their parameters, and returning IAnswerData objects.
///
/// </summary>
/// <author> Clayton Sims
///
/// </author>
public class QuestionPreloader
{
//UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'AnonymousClassIPreloadHandler' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'"
private class AnonymousClassIPreloadHandler : IPreloadHandler
{
public AnonymousClassIPreloadHandler(QuestionPreloader enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(QuestionPreloader enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private QuestionPreloader enclosingInstance;
public QuestionPreloader Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public virtual System.String preloadHandled()
{
return "date";
}
public virtual IAnswerData handlePreload(System.String preloadParams)
{
return Enclosing_Instance.preloadDate(preloadParams);
}
public virtual bool handlePostProcess(TreeElement node, System.String params_Renamed)
{
//do nothing
return false;
}
}
//UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'AnonymousClassIPreloadHandler1' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'"
private class AnonymousClassIPreloadHandler1 : IPreloadHandler
{
public AnonymousClassIPreloadHandler1(QuestionPreloader enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(QuestionPreloader enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private QuestionPreloader enclosingInstance;
public QuestionPreloader Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public virtual System.String preloadHandled()
{
return "property";
}
public virtual IAnswerData handlePreload(System.String preloadParams)
{
return Enclosing_Instance.preloadProperty(preloadParams);
}
public virtual bool handlePostProcess(TreeElement node, System.String params_Renamed)
{
Enclosing_Instance.saveProperty(params_Renamed, node);
return false;
}
}
//UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'AnonymousClassIPreloadHandler2' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'"
private class AnonymousClassIPreloadHandler2 : IPreloadHandler
{
public AnonymousClassIPreloadHandler2(QuestionPreloader enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(QuestionPreloader enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private QuestionPreloader enclosingInstance;
public QuestionPreloader Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public virtual System.String preloadHandled()
{
return "timestamp";
}
public virtual IAnswerData handlePreload(System.String preloadParams)
{
return ("start".Equals(preloadParams) ? Enclosing_Instance.Timestamp : null);
}
public virtual bool handlePostProcess(TreeElement node, System.String params_Renamed)
{
if ("end".Equals(params_Renamed))
{
node.setAnswer(Enclosing_Instance.Timestamp);
return true;
}
else
{
return false;
}
}
}
//UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'AnonymousClassIPreloadHandler3' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'"
private class AnonymousClassIPreloadHandler3 : IPreloadHandler
{
public AnonymousClassIPreloadHandler3(QuestionPreloader enclosingInstance)
{
InitBlock(enclosingInstance);
}
private void InitBlock(QuestionPreloader enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private QuestionPreloader enclosingInstance;
public QuestionPreloader Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public virtual System.String preloadHandled()
{
return "uid";
}
public virtual IAnswerData handlePreload(System.String preloadParams)
{
return new StringData(PropertyUtils.genGUID(25));
}
public virtual bool handlePostProcess(TreeElement node, System.String params_Renamed)
{
return false;
}
}
private DateTimeData Timestamp
{
get
{
System.DateTime tempAux = System.DateTime.Now;
//UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'"
return new DateTimeData(ref tempAux);
}
}
/* String -> IPreloadHandler */
private Map preloadHandlers;
/// <summary> Creates a new Preloader with default handlers</summary>
public QuestionPreloader()
{
preloadHandlers = new Map();
initPreloadHandlers();
}
/// <summary> Initializes the default preload handlers</summary>
private void initPreloadHandlers()
{
IPreloadHandler date = new AnonymousClassIPreloadHandler(this);
IPreloadHandler property = new AnonymousClassIPreloadHandler1(this);
IPreloadHandler timestamp = new AnonymousClassIPreloadHandler2(this);
IPreloadHandler uid = new AnonymousClassIPreloadHandler3(this);
/*
//TODO: Finish this up.
IPreloadHandler meta = new IPreloadHandler() {
public String preloadHandled() {
return "meta";
}
public IAnswerData handlePreload(String preloadParams) {
//TODO: Ideally, we want to handle this preloader by taking in the
//existing structure. Resultantly, we don't want to mess with this.
//We should be enforcing that we don't.
return null;
}
public boolean handlePostProcess(TreeElement node, String params) {
Vector kids = node.getChildren();
Enumeration en = kids.elements();
while(en.hasMoreElements()) {
TreeElement kid = (TreeElement)en.nextElement();
if(kid.getName().equals("uid")) {
kid.setValue(new StringData(PropertyUtils.genGUID(25)));
}
}
return true;
}
};
*/
addPreloadHandler(date);
addPreloadHandler(property);
addPreloadHandler(timestamp);
addPreloadHandler(uid);
}
/// <summary> Adds a new preload handler to this preloader.
///
/// </summary>
/// <param name="handler">an IPreloadHandler that can handle a preload type
/// </param>
public virtual void addPreloadHandler(IPreloadHandler handler)
{
preloadHandlers.put(handler.preloadHandled(), handler);
}
/// <summary> Returns the IAnswerData preload value for the given preload type and parameters
///
/// </summary>
/// <param name="preloadType">The type of the preload to be returned
/// </param>
/// <param name="preloadParams">Parameters for the preload handler
/// </param>
/// <returns> An IAnswerData corresponding to a pre-loaded value for the given
/// Arguments. null if no preload could successfully be derived due to either
/// the lack of a handler, or to invalid parameters
/// </returns>
public virtual IAnswerData getQuestionPreload(System.String preloadType, System.String preloadParams)
{
IPreloadHandler handler = (IPreloadHandler)preloadHandlers.get(preloadType);
if (handler != null)
{
return handler.handlePreload(preloadParams);
}
else
{
System.Console.Error.WriteLine("Do not know how to handle preloader [" + preloadType + "]");
return null;
}
}
public virtual bool questionPostProcess(TreeElement node, System.String preloadType, System.String params_Renamed)
{
IPreloadHandler handler = (IPreloadHandler)preloadHandlers.get(preloadType);
if (handler != null)
{
return handler.handlePostProcess(node, params_Renamed);
}
else
{
System.Console.Error.WriteLine("Do not know how to handle preloader [" + preloadType + "]");
return false;
}
}
/// <summary> Preloads a DateData object for the preload type 'date'
///
/// </summary>
/// <param name="preloadParams">The parameters determining the date
/// </param>
/// <returns> A preload date value if the parameters can be parsed,
/// null otherwise
/// </returns>
private IAnswerData preloadDate(System.String preloadParams)
{
//UPGRADE_TODO: The 'System.DateTime' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'"
System.DateTime d = new DateTime();
if (preloadParams.Equals("today"))
{
d = System.DateTime.Now;
}
else if (preloadParams.Substring(0, (11) - (0)).Equals("prevperiod-"))
{
List<String> v = DateUtils.split(preloadParams.Substring(11), "-", false);
System.String[] params_Renamed = new System.String[v.Count];
for (int i = 0; i < params_Renamed.Length; i++)
params_Renamed[i] = ((System.String)v[i]);
try
{
System.String type = params_Renamed[0];
System.String start = params_Renamed[1];
bool beginning;
if (params_Renamed[2].Equals("head"))
beginning = true;
else if (params_Renamed[2].Equals("tail"))
beginning = false;
else
throw new System.SystemException();
bool includeToday;
if (params_Renamed.Length >= 4)
{
if (params_Renamed[3].Equals("x"))
includeToday = true;
else if (params_Renamed[3].Equals(""))
includeToday = false;
else
throw new System.SystemException();
}
else
{
includeToday = false;
}
int nAgo;
if (params_Renamed.Length >= 5)
{
nAgo = System.Int32.Parse(params_Renamed[4]);
}
else
{
nAgo = 1;
}
System.DateTime tempAux = System.DateTime.Now;
//UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'"
d = DateUtils.getPastPeriodDate(ref tempAux, type, start, beginning, includeToday, nAgo);
}
catch (System.Exception e)
{
throw new System.ArgumentException("invalid preload params for preload mode 'date'");
}
}
//UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'"
DateData data = new DateData(ref d);
return data;
}
/// <summary> Preloads a StringData object for the preload type 'property'
///
/// </summary>
/// <param name="preloadParams">The parameters determining the property to be retrieved
/// </param>
/// <returns> A preload property value if the parameters can be parsed,
/// null otherwise
/// </returns>
private IAnswerData preloadProperty(System.String preloadParams)
{
System.String propname = preloadParams;
System.String propval = PropertyManager._().getSingularProperty(propname);
StringData data = null;
if (propval != null && propval.Length > 0)
{
data = new StringData(propval);
}
return data;
}
private void saveProperty(System.String propName, TreeElement node)
{
IAnswerData answer = node.getValue();
System.String value_Renamed = (answer == null ? null : answer.DisplayText);
if (propName != null && propName.Length > 0 && value_Renamed != null && value_Renamed.Length > 0)
PropertyManager._().setProperty(propName, value_Renamed);
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Provider;
using System.Net;
using System.Text;
using DiscUtils.Ntfs;
namespace DiscUtils.PowerShell.VirtualDiskProvider
{
[CmdletProvider("VirtualDisk", ProviderCapabilities.Credentials)]
public sealed class Provider : NavigationCmdletProvider, IContentCmdletProvider
{
#region Drive manipulation
protected override PSDriveInfo NewDrive(PSDriveInfo drive)
{
NewDriveParameters dynParams = DynamicParameters as NewDriveParameters;
if (drive == null)
{
WriteError(new ErrorRecord(
new ArgumentNullException("drive"),
"NullDrive",
ErrorCategory.InvalidArgument,
null));
return null;
}
if (string.IsNullOrEmpty(drive.Root))
{
WriteError(new ErrorRecord(
new ArgumentException("drive"),
"NoRoot",
ErrorCategory.InvalidArgument,
drive));
return null;
}
string[] mountPaths = Utilities.NormalizePath(drive.Root).Split('!');
if (mountPaths.Length < 1 || mountPaths.Length > 2)
{
WriteError(new ErrorRecord(
new ArgumentException("drive"),
"InvalidRoot",
ErrorCategory.InvalidArgument,
drive));
//return null;
}
string diskPath = mountPaths[0];
string relPath = mountPaths.Length > 1 ? mountPaths[1] : "";
string user = null;
string password = null;
if (drive.Credential != null && drive.Credential.UserName != null)
{
NetworkCredential netCred = drive.Credential.GetNetworkCredential();
user = netCred.UserName;
password = netCred.Password;
}
try
{
string fullPath = Utilities.DenormalizePath(diskPath);
var resolvedPath = SessionState.Path.GetResolvedPSPathFromPSPath(fullPath)[0];
if (resolvedPath.Provider.Name == "FileSystem")
{
fullPath = resolvedPath.ProviderPath;
}
FileAccess access = dynParams.ReadWrite.IsPresent ? FileAccess.ReadWrite : FileAccess.Read;
VirtualDisk disk = VirtualDisk.OpenDisk(fullPath, dynParams.DiskType, access, user, password);
return new VirtualDiskPSDriveInfo(drive, MakePath(Utilities.NormalizePath(fullPath) + "!", relPath), disk);
}
catch (IOException ioe)
{
WriteError(new ErrorRecord(
ioe,
"DiskAccess",
ErrorCategory.ResourceUnavailable,
drive.Root));
return null;
}
}
protected override object NewDriveDynamicParameters()
{
return new NewDriveParameters();
}
protected override PSDriveInfo RemoveDrive(PSDriveInfo drive)
{
if (drive == null)
{
WriteError(new ErrorRecord(
new ArgumentNullException("drive"),
"NullDrive",
ErrorCategory.InvalidArgument,
null));
return null;
}
VirtualDiskPSDriveInfo vdDrive = drive as VirtualDiskPSDriveInfo;
if (vdDrive == null)
{
WriteError(new ErrorRecord(
new ArgumentException("invalid type of drive"),
"BadDrive",
ErrorCategory.InvalidArgument,
null));
return null;
}
vdDrive.Disk.Dispose();
return vdDrive;
}
#endregion
#region Item methods
protected override void GetItem(string path)
{
GetItemParameters dynParams = DynamicParameters as GetItemParameters;
bool readOnly = !(dynParams != null && dynParams.ReadWrite.IsPresent);
Object obj = FindItemByPath(Utilities.NormalizePath(path), false, readOnly);
if (obj != null)
{
WriteItemObject(obj, path.Trim('\\'), true);
}
}
protected override object GetItemDynamicParameters(string path)
{
return new GetItemParameters();
}
protected override void SetItem(string path, object value)
{
throw new NotImplementedException();
}
protected override bool ItemExists(string path)
{
bool result = FindItemByPath(Utilities.NormalizePath(path), false, true) != null;
return result;
}
protected override bool IsValidPath(string path)
{
return !string.IsNullOrEmpty(path);
}
#endregion
#region Container methods
protected override void GetChildItems(string path, bool recurse)
{
GetChildren(Utilities.NormalizePath(path), recurse, false);
}
protected override void GetChildNames(string path, ReturnContainers returnContainers)
{
// TODO: returnContainers
GetChildren(Utilities.NormalizePath(path), false, true);
}
protected override bool HasChildItems(string path)
{
object obj = FindItemByPath(Utilities.NormalizePath(path), true, true);
if (obj is DiscFileInfo)
{
return false;
}
else if (obj is DiscDirectoryInfo)
{
return ((DiscDirectoryInfo)obj).GetFileSystemInfos().Length > 0;
}
else
{
return true;
}
}
protected override void RemoveItem(string path, bool recurse)
{
object obj = FindItemByPath(Utilities.NormalizePath(path), false, false);
if (obj is DiscDirectoryInfo)
{
((DiscDirectoryInfo)obj).Delete(true);
}
else if (obj is DiscFileInfo)
{
((DiscFileInfo)obj).Delete();
}
else
{
WriteError(new ErrorRecord(
new InvalidOperationException("Cannot delete items of this type: " + (obj != null ? obj.GetType() : null)),
"UnknownObjectTypeToRemove",
ErrorCategory.InvalidOperation,
obj));
}
}
protected override void NewItem(string path, string itemTypeName, object newItemValue)
{
string parentPath = GetParentPath(path, null);
if (string.IsNullOrEmpty(itemTypeName))
{
WriteError(new ErrorRecord(
new InvalidOperationException("No type specified. Specify \"file\" or \"directory\" as the type."),
"NoTypeForNewItem",
ErrorCategory.InvalidArgument,
itemTypeName));
return;
}
string itemTypeUpper = itemTypeName.ToUpperInvariant();
object obj = FindItemByPath(Utilities.NormalizePath(parentPath), true, false);
if (obj is DiscDirectoryInfo)
{
DiscDirectoryInfo dirInfo = (DiscDirectoryInfo)obj;
if (itemTypeUpper == "FILE")
{
using (dirInfo.FileSystem.OpenFile(Path.Combine(dirInfo.FullName, GetChildName(path)), FileMode.Create)) { }
}
else if (itemTypeUpper == "DIRECTORY")
{
dirInfo.FileSystem.CreateDirectory(Path.Combine(dirInfo.FullName, GetChildName(path)));
}
else if (itemTypeUpper == "HARDLINK")
{
NtfsFileSystem ntfs = dirInfo.FileSystem as NtfsFileSystem;
if(ntfs != null)
{
NewHardLinkDynamicParameters hlParams = (NewHardLinkDynamicParameters)DynamicParameters;
var srcItems = SessionState.InvokeProvider.Item.Get(hlParams.SourcePath);
if (srcItems.Count != 1)
{
WriteError(new ErrorRecord(
new InvalidOperationException("The type is unknown for this provider. Only \"file\" and \"directory\" can be specified."),
"UnknownTypeForNewItem",
ErrorCategory.InvalidArgument,
itemTypeName));
return;
}
DiscFileSystemInfo srcFsi = srcItems[0].BaseObject as DiscFileSystemInfo;
ntfs.CreateHardLink(srcFsi.FullName, Path.Combine(dirInfo.FullName, GetChildName(path)));
}
}
else
{
WriteError(new ErrorRecord(
new InvalidOperationException("The type is unknown for this provider. Only \"file\" and \"directory\" can be specified."),
"UnknownTypeForNewItem",
ErrorCategory.InvalidArgument,
itemTypeName));
return;
}
}
else
{
WriteError(new ErrorRecord(
new InvalidOperationException("Cannot create items in an object of this type: " + (obj != null ? obj.GetType() : null)),
"UnknownObjectTypeForNewItemParent",
ErrorCategory.InvalidOperation,
obj));
return;
}
}
protected override object NewItemDynamicParameters(string path, string itemTypeName, object newItemValue)
{
if (string.IsNullOrEmpty(itemTypeName))
{
return null;
}
string itemTypeUpper = itemTypeName.ToUpperInvariant();
if (itemTypeUpper == "HARDLINK")
{
return new NewHardLinkDynamicParameters();
}
return null;
}
protected override void RenameItem(string path, string newName)
{
object obj = FindItemByPath(Utilities.NormalizePath(path), true, false);
DiscFileSystemInfo fsiObj = obj as DiscFileSystemInfo;
if (fsiObj == null)
{
WriteError(new ErrorRecord(
new InvalidOperationException("Cannot move items to this location"),
"BadParentForNewItem",
ErrorCategory.InvalidArgument,
newName));
return;
}
string newFullName = Path.Combine(Path.GetDirectoryName(fsiObj.FullName.TrimEnd('\\')), newName);
if (obj is DiscDirectoryInfo)
{
DiscDirectoryInfo dirObj = (DiscDirectoryInfo)obj;
dirObj.MoveTo(newFullName);
}
else
{
DiscFileInfo fileObj = (DiscFileInfo)obj;
fileObj.MoveTo(newFullName);
}
}
protected override void CopyItem(string path, string copyPath, bool recurse)
{
DiscDirectoryInfo destDir;
string destFileName = null;
object destObj = FindItemByPath(Utilities.NormalizePath(copyPath), true, false);
destDir = destObj as DiscDirectoryInfo;
if (destDir != null)
{
destFileName = GetChildName(path);
}
else if (destObj == null || destObj is DiscFileInfo)
{
destObj = FindItemByPath(Utilities.NormalizePath(GetParentPath(copyPath, null)), true, false);
destDir = destObj as DiscDirectoryInfo;
destFileName = GetChildName(copyPath);
}
if (destDir == null)
{
WriteError(new ErrorRecord(
new InvalidOperationException("Cannot copy items to this location"),
"BadParentForNewItem",
ErrorCategory.InvalidArgument,
copyPath));
return;
}
object srcDirObj = FindItemByPath(Utilities.NormalizePath(GetParentPath(path, null)), true, true);
DiscDirectoryInfo srcDir = srcDirObj as DiscDirectoryInfo;
string srcFileName = GetChildName(path);
if (srcDir == null)
{
WriteError(new ErrorRecord(
new InvalidOperationException("Cannot copy items from this location"),
"BadParentForNewItem",
ErrorCategory.InvalidArgument,
copyPath));
return;
}
DoCopy(srcDir, srcFileName, destDir, destFileName, recurse);
}
#endregion
#region Navigation methods
protected override bool IsItemContainer(string path)
{
object obj = FindItemByPath(Utilities.NormalizePath(path), false, true);
bool result = false;
if (obj is VirtualDisk)
{
result = true;
}
else if (obj is LogicalVolumeInfo)
{
result = true;
}
else if (obj is DiscDirectoryInfo)
{
result = true;
}
return result;
}
protected override string MakePath(string parent, string child)
{
return Utilities.NormalizePath(base.MakePath(Utilities.DenormalizePath(parent), Utilities.DenormalizePath(child)));
}
#endregion
#region IContentCmdletProvider Members
public void ClearContent(string path)
{
object destObj = FindItemByPath(Utilities.NormalizePath(path), true, false);
if (destObj is DiscFileInfo)
{
using (Stream s = ((DiscFileInfo)destObj).Open(FileMode.Open, FileAccess.ReadWrite))
{
s.SetLength(0);
}
}
else
{
WriteError(new ErrorRecord(
new IOException("Cannot write to this item"),
"BadContentDestination",
ErrorCategory.InvalidOperation,
destObj));
}
}
public object ClearContentDynamicParameters(string path)
{
return null;
}
public IContentReader GetContentReader(string path)
{
object destObj = FindItemByPath(Utilities.NormalizePath(path), true, false);
if (destObj is DiscFileInfo)
{
return new FileContentReaderWriter(
this,
((DiscFileInfo)destObj).Open(FileMode.Open, FileAccess.Read),
DynamicParameters as ContentParameters);
}
else
{
WriteError(new ErrorRecord(
new IOException("Cannot read from this item"),
"BadContentSource",
ErrorCategory.InvalidOperation,
destObj));
return null;
}
}
public object GetContentReaderDynamicParameters(string path)
{
return new ContentParameters();
}
public IContentWriter GetContentWriter(string path)
{
object destObj = FindItemByPath(Utilities.NormalizePath(path), true, false);
if (destObj is DiscFileInfo)
{
return new FileContentReaderWriter(
this,
((DiscFileInfo)destObj).Open(FileMode.Open, FileAccess.ReadWrite),
DynamicParameters as ContentParameters);
}
else
{
WriteError(new ErrorRecord(
new IOException("Cannot write to this item"),
"BadContentDestination",
ErrorCategory.InvalidOperation,
destObj));
return null;
}
}
public object GetContentWriterDynamicParameters(string path)
{
return new ContentParameters();
}
#endregion
#region Type Extensions
public static string Mode(PSObject instance)
{
if (instance == null)
{
return "";
}
DiscFileSystemInfo fsi = instance.BaseObject as DiscFileSystemInfo;
if (fsi == null)
{
return "";
}
StringBuilder result = new StringBuilder(5);
result.Append(((fsi.Attributes & FileAttributes.Directory) != 0) ? "d" : "-");
result.Append(((fsi.Attributes & FileAttributes.Archive) != 0) ? "a" : "-");
result.Append(((fsi.Attributes & FileAttributes.ReadOnly) != 0) ? "r" : "-");
result.Append(((fsi.Attributes & FileAttributes.Hidden) != 0) ? "h" : "-");
result.Append(((fsi.Attributes & FileAttributes.System) != 0) ? "s" : "-");
return result.ToString();
}
#endregion
private VirtualDiskPSDriveInfo DriveInfo
{
get { return PSDriveInfo as VirtualDiskPSDriveInfo; }
}
private VirtualDisk Disk
{
get
{
VirtualDiskPSDriveInfo driveInfo = DriveInfo;
return (driveInfo != null) ? driveInfo.Disk : null;
}
}
private object FindItemByPath(string path, bool preferFs, bool readOnly)
{
FileAccess fileAccess = readOnly ? FileAccess.Read : FileAccess.ReadWrite;
string diskPath;
string relPath;
int mountSepIdx = path.IndexOf('!');
if (mountSepIdx < 0)
{
diskPath = path;
relPath = "";
}
else
{
diskPath = path.Substring(0, mountSepIdx);
relPath = path.Substring(mountSepIdx + 1);
}
VirtualDisk disk = Disk;
if( disk == null )
{
OnDemandVirtualDisk odvd = new OnDemandVirtualDisk(Utilities.DenormalizePath(diskPath), fileAccess);
if (odvd.IsValid)
{
disk = odvd;
ShowSlowDiskWarning();
}
else
{
return null;
}
}
List<string> pathElems = new List<string>(relPath.Split(new string[] { @"\" }, StringSplitOptions.RemoveEmptyEntries));
if (pathElems.Count == 0)
{
return disk;
}
VolumeInfo volInfo = null;
VolumeManager volMgr = DriveInfo != null ? DriveInfo.VolumeManager : new VolumeManager(disk);
LogicalVolumeInfo[] volumes = volMgr.GetLogicalVolumes();
string volNumStr = pathElems[0].StartsWith("Volume", StringComparison.OrdinalIgnoreCase) ? pathElems[0].Substring(6) : null;
int volNum;
if (int.TryParse(volNumStr, out volNum) || volNum < 0 || volNum >= volumes.Length)
{
volInfo = volumes[volNum];
}
else
{
volInfo = volMgr.GetVolume(Utilities.DenormalizePath(pathElems[0]));
}
pathElems.RemoveAt(0);
if (volInfo == null || (pathElems.Count == 0 && !preferFs))
{
return volInfo;
}
bool disposeFs;
DiscFileSystem fs = GetFileSystem(volInfo, out disposeFs);
try
{
if (fs == null)
{
return null;
}
// Special marker in the path - disambiguates the root folder from the volume
// containing it. By this point it's done it's job (we didn't return volInfo),
// so we just remove it.
if (pathElems.Count > 0 && pathElems[0] == "$Root")
{
pathElems.RemoveAt(0);
}
string fsPath = string.Join(@"\", pathElems.ToArray());
if (fs.DirectoryExists(fsPath))
{
return fs.GetDirectoryInfo(fsPath);
}
else if (fs.FileExists(fsPath))
{
return fs.GetFileInfo(fsPath);
}
}
finally
{
if (disposeFs && fs != null)
{
fs.Dispose();
}
}
return null;
}
private void ShowSlowDiskWarning()
{
const string varName = "DiscUtils_HideSlowDiskWarning";
PSVariable psVar = this.SessionState.PSVariable.Get(varName);
if (psVar != null && psVar.Value != null)
{
bool warningHidden;
string valStr = psVar.Value.ToString();
if (bool.TryParse(valStr, out warningHidden) && warningHidden)
{
return;
}
}
WriteWarning("Slow disk access. Mount the disk using New-PSDrive to improve performance. This message will not show again.");
this.SessionState.PSVariable.Set(varName, true.ToString());
}
private DiscFileSystem GetFileSystem(VolumeInfo volInfo, out bool dispose)
{
if (DriveInfo != null)
{
dispose = false;
return DriveInfo.GetFileSystem(volInfo);
}
else
{
// TODO: proper file system detection
if (volInfo.BiosType == 7)
{
dispose = true;
return new NtfsFileSystem(volInfo.Open());
}
}
dispose = false;
return null;
}
private void GetChildren(string path, bool recurse, bool namesOnly)
{
if (string.IsNullOrEmpty(path))
{
return;
}
object obj = FindItemByPath(path, false, true);
if (obj is VirtualDisk)
{
VirtualDisk vd = (VirtualDisk)obj;
EnumerateDisk(vd, path, recurse, namesOnly);
}
else if (obj is LogicalVolumeInfo)
{
LogicalVolumeInfo lvi = (LogicalVolumeInfo)obj;
bool dispose;
DiscFileSystem fs = GetFileSystem(lvi, out dispose);
try
{
if (fs != null)
{
EnumerateDirectory(fs.Root, path, recurse, namesOnly);
}
}
finally
{
if (dispose && fs != null)
{
fs.Dispose();
}
}
}
else if (obj is DiscDirectoryInfo)
{
DiscDirectoryInfo ddi = (DiscDirectoryInfo)obj;
EnumerateDirectory(ddi, path, recurse, namesOnly);
}
else
{
WriteError(new ErrorRecord(
new InvalidOperationException("Unrecognized object type: " + (obj != null ? obj.GetType() : null)),
"UnknownObjectType",
ErrorCategory.ParserError,
obj));
}
}
private void EnumerateDisk(VirtualDisk vd, string path, bool recurse, bool namesOnly)
{
if (!path.TrimEnd('\\').EndsWith("!"))
{
path += "!";
}
VolumeManager volMgr = DriveInfo != null ? DriveInfo.VolumeManager : new VolumeManager(vd);
LogicalVolumeInfo[] volumes = volMgr.GetLogicalVolumes();
for (int i = 0; i < volumes.Length; ++i)
{
string name = "Volume" + i;
string volPath = MakePath(path, name);// new PathInfo(PathInfo.Parse(path, true).MountParts, "" + i).ToString();
WriteItemObject(namesOnly ? name : (object)volumes[i], volPath, true);
if (recurse)
{
GetChildren(volPath, recurse, namesOnly);
}
}
}
private void EnumerateDirectory(DiscDirectoryInfo parent, string basePath, bool recurse, bool namesOnly)
{
foreach (var dir in parent.GetDirectories())
{
WriteItemObject(namesOnly ? dir.Name : (object)dir, MakePath(basePath, dir.Name), true);
if (recurse)
{
EnumerateDirectory(dir, MakePath(basePath, dir.Name), recurse, namesOnly);
}
}
foreach (var file in parent.GetFiles())
{
WriteItemObject(namesOnly ? file.Name : (object)file, MakePath(basePath, file.Name), false);
}
}
private void DoCopy(DiscDirectoryInfo srcDir, string srcFileName, DiscDirectoryInfo destDir, string destFileName, bool recurse)
{
string srcPath = Path.Combine(srcDir.FullName, srcFileName);
string destPath = Path.Combine(destDir.FullName, destFileName);
if ((srcDir.FileSystem.GetAttributes(srcPath) & FileAttributes.Directory) == 0)
{
DoCopyFile(srcDir.FileSystem, srcPath, destDir.FileSystem, destPath);
}
else
{
DoCopyDirectory(srcDir.FileSystem, srcPath, destDir.FileSystem, destPath);
if (recurse)
{
DoRecursiveCopy(srcDir.FileSystem, srcPath, destDir.FileSystem, destPath);
}
}
}
private void DoRecursiveCopy(DiscFileSystem srcFs, string srcPath, DiscFileSystem destFs, string destPath)
{
foreach (var dir in srcFs.GetDirectories(srcPath))
{
string srcDirPath = Path.Combine(srcPath, dir);
string destDirPath = Path.Combine(destPath, dir);
DoCopyDirectory(srcFs, srcDirPath, destFs, destDirPath);
DoRecursiveCopy(srcFs, srcDirPath, destFs, destDirPath);
}
foreach (var file in srcFs.GetFiles(srcPath))
{
string srcFilePath = Path.Combine(srcPath, file);
string destFilePath = Path.Combine(destPath, file);
DoCopyFile(srcFs, srcFilePath, destFs, destFilePath);
}
}
private void DoCopyDirectory(DiscFileSystem srcFs, string srcPath, DiscFileSystem destFs, string destPath)
{
IWindowsFileSystem destWindowsFs = destFs as IWindowsFileSystem;
IWindowsFileSystem srcWindowsFs = srcFs as IWindowsFileSystem;
destFs.CreateDirectory(destPath);
if (srcWindowsFs != null && destWindowsFs != null)
{
if ((srcWindowsFs.GetAttributes(srcPath) & FileAttributes.ReparsePoint) != 0)
{
destWindowsFs.SetReparsePoint(destPath, srcWindowsFs.GetReparsePoint(srcPath));
}
destWindowsFs.SetSecurity(destPath, srcWindowsFs.GetSecurity(srcPath));
}
destFs.SetAttributes(destPath, srcFs.GetAttributes(srcPath));
}
private void DoCopyFile(DiscFileSystem srcFs, string srcPath, DiscFileSystem destFs, string destPath)
{
IWindowsFileSystem destWindowsFs = destFs as IWindowsFileSystem;
IWindowsFileSystem srcWindowsFs = srcFs as IWindowsFileSystem;
using (Stream src = srcFs.OpenFile(srcPath, FileMode.Open, FileAccess.Read))
using (Stream dest = destFs.OpenFile(destPath, FileMode.Create, FileAccess.ReadWrite))
{
dest.SetLength(src.Length);
byte[] buffer = new byte[1024 * 1024];
int numRead = src.Read(buffer, 0, buffer.Length);
while (numRead > 0)
{
dest.Write(buffer, 0, numRead);
numRead = src.Read(buffer, 0, buffer.Length);
}
}
if (srcWindowsFs != null && destWindowsFs != null)
{
if ((srcWindowsFs.GetAttributes(srcPath) & FileAttributes.ReparsePoint) != 0)
{
destWindowsFs.SetReparsePoint(destPath, srcWindowsFs.GetReparsePoint(srcPath));
}
var sd = srcWindowsFs.GetSecurity(srcPath);
if(sd != null)
{
destWindowsFs.SetSecurity(destPath, sd);
}
}
destFs.SetAttributes(destPath, srcFs.GetAttributes(srcPath));
destFs.SetCreationTimeUtc(destPath, srcFs.GetCreationTimeUtc(srcPath));
}
}
}
| |
using System.Collections.Generic;
namespace AjaxControlToolkit {
public abstract class HtmlEditorExtenderButton {
public abstract string CommandName { get; }
public virtual string Tooltip { get { return CommandName; } }
// Get list of elements associated to the button
public abstract Dictionary<string, string[]> ElementWhiteList { get; }
// Get list of Attribute and its values associated to the button
public abstract Dictionary<string, string[]> AttributeWhiteList { get; }
}
#region button classes
// Bold class represents to bold tag
public class Bold : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Bold"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("b", new string[] { "style" });
elementWhiteList.Add("strong", new string[] { "style" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("style", new string[] { });
return attributeWhiteList;
}
}
}
public class Italic : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Italic"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("i", new string[] { "style" });
elementWhiteList.Add("em", new string[] { "style" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("style", new string[] { });
return attributeWhiteList;
}
}
}
public class Underline : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Underline"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("u", new string[] { "style" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("style", new string[] { });
return attributeWhiteList;
}
}
}
public class StrikeThrough : HtmlEditorExtenderButton {
public override string CommandName {
get { return "StrikeThrough"; }
}
public override string Tooltip {
get { return "Strike Through"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("strike", new string[] { "style" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("style", new string[] { });
return attributeWhiteList;
}
}
}
public class Subscript : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Subscript"; }
}
public override string Tooltip {
get { return "Sub Script"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("sub", new string[] { });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class Superscript : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Superscript"; }
}
public override string Tooltip {
get { return "Super Script"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("sup", new string[] { });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class JustifyLeft : HtmlEditorExtenderButton {
public override string CommandName {
get { return "JustifyLeft"; }
}
public override string Tooltip {
get { return "Justify Left"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("p", new string[] { "align" });
elementWhiteList.Add("div", new string[] { "style", "align" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("style", new string[] { "text-align" });
attributeWhiteList.Add("align", new string[] { "left" });
return attributeWhiteList;
}
}
}
public class JustifyRight : HtmlEditorExtenderButton {
public override string CommandName {
get { return "JustifyRight"; }
}
public override string Tooltip {
get { return "Justify Right"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("p", new string[] { "align" });
elementWhiteList.Add("div", new string[] { "style", "align" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("style", new string[] { "text-align" });
attributeWhiteList.Add("align", new string[] { "right" });
return attributeWhiteList;
}
}
}
public class JustifyCenter : HtmlEditorExtenderButton {
public override string CommandName {
get { return "JustifyCenter"; }
}
public override string Tooltip {
get { return "Justify Center"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("p", new string[] { "align" });
elementWhiteList.Add("div", new string[] { "style", "align" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("style", new string[] { "text-align" });
attributeWhiteList.Add("align", new string[] { "center" });
return attributeWhiteList;
}
}
}
public class JustifyFull : HtmlEditorExtenderButton {
public override string CommandName {
get { return "JustifyFull"; }
}
public override string Tooltip {
get { return "Justify Full"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("p", new string[] { "align" });
elementWhiteList.Add("div", new string[] { "style", "align" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("style", new string[] { "text-align" });
attributeWhiteList.Add("align", new string[] { "justify" });
return attributeWhiteList;
}
}
}
public class InsertOrderedList : HtmlEditorExtenderButton {
public override string CommandName {
get { return "insertOrderedList"; }
}
public override string Tooltip {
get { return "Insert Ordered List"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("ol", new string[] { });
elementWhiteList.Add("li", new string[] { });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class InsertUnorderedList : HtmlEditorExtenderButton {
public override string CommandName {
get { return "insertUnorderedList"; }
}
public override string Tooltip {
get { return "Insert Unordered List"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("ul", new string[] { });
elementWhiteList.Add("li", new string[] { });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class Undo : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Undo"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class Redo : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Redo"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class CreateLink : HtmlEditorExtenderButton {
public override string CommandName {
get { return "createLink"; }
}
public override string Tooltip {
get { return "Create Link"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("a", new string[] { "href" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("href", new string[] { });
return null;
}
}
}
public class Delete : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Delete"; }
}
public override string Tooltip {
get { return "Delete"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class SelectAll : HtmlEditorExtenderButton {
public override string CommandName {
get { return "SelectAll"; }
}
public override string Tooltip {
get { return "Select All"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class UnSelect : HtmlEditorExtenderButton {
public override string CommandName {
get { return "UnSelect"; }
}
public override string Tooltip {
get { return "UnSelect"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class UnLink : HtmlEditorExtenderButton {
public override string CommandName {
get { return "UnLink"; }
}
public override string Tooltip {
get { return "UnLink"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class BackgroundColorSelector : HtmlEditorExtenderButton {
public override string CommandName {
get { return "BackColor"; }
}
public override string Tooltip {
get { return "Back Color"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("font", new string[] { "style" });
elementWhiteList.Add("span", new string[] { "style" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("style", new string[] { "background-color" });
return attributeWhiteList;
}
}
}
public class Copy : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Copy"; }
}
public override string Tooltip {
get { return "Copy"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class Cut : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Cut"; }
}
public override string Tooltip {
get { return "Cut"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class Paste : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Paste"; }
}
public override string Tooltip {
get { return "Paste"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class CleanWord : HtmlEditorExtenderButton {
public override string CommandName {
get { return "CleanWord"; }
}
public override string Tooltip {
get { return "Clean Word HTML"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class FontNameSelector : HtmlEditorExtenderButton {
public override string CommandName {
get { return "FontName"; }
}
public override string Tooltip {
get { return "Font Name"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("font", new string[] { "face" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("face", new string[] { });
return attributeWhiteList;
}
}
}
public class FontSizeSelector : HtmlEditorExtenderButton {
public override string CommandName {
get { return "FontSize"; }
}
public override string Tooltip {
get { return "Font Size"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("font", new string[] { "size" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("size", new string[] { });
return attributeWhiteList;
}
}
}
public class ForeColorSelector : HtmlEditorExtenderButton {
public override string CommandName {
get { return "ForeColor"; }
}
public override string Tooltip {
get { return "Fore Color"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("font", new string[] { "color" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("color", new string[] { });
return attributeWhiteList;
}
}
}
public class Indent : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Indent"; }
}
public override string Tooltip {
get { return "Indent"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("blockquote", new string[] { "style", "dir" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("style", new string[] { "margin-right", "margin", "padding", "border" });
attributeWhiteList.Add("dir", new string[] { "ltr", "rtl", "auto" });
return attributeWhiteList;
}
}
}
public class InsertHorizontalRule : HtmlEditorExtenderButton {
public override string CommandName {
get { return "InsertHorizontalRule"; }
}
public override string Tooltip {
get { return "Insert Horizontal Rule"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("hr", new string[] { "size", "width" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("size", new string[] { });
attributeWhiteList.Add("width", new string[] { });
return attributeWhiteList;
}
}
}
public class Outdent : HtmlEditorExtenderButton {
public override string CommandName {
get { return "Outdent"; }
}
public override string Tooltip {
get { return "Outdent"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class RemoveFormat : HtmlEditorExtenderButton {
public override string CommandName {
get { return "RemoveFormat"; }
}
public override string Tooltip {
get { return "Remove Format"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class HorizontalSeparator : HtmlEditorExtenderButton {
public override string CommandName {
get { return "HorizontalSeparator"; }
}
public override string Tooltip {
get { return "Separator"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get { return null; }
}
public override Dictionary<string, string[]> AttributeWhiteList {
get { return null; }
}
}
public class InsertImage : HtmlEditorExtenderButton {
public override string CommandName {
get { return "InsertImage"; }
}
public override string Tooltip {
get { return "Insert Image"; }
}
public override Dictionary<string, string[]> ElementWhiteList {
get {
var elementWhiteList = new Dictionary<string, string[]>();
elementWhiteList.Add("img", new string[] { "src" });
return elementWhiteList;
}
}
public override Dictionary<string, string[]> AttributeWhiteList {
get {
var attributeWhiteList = new Dictionary<string, string[]>();
attributeWhiteList.Add("src", new string[] { });
return attributeWhiteList;
}
}
public string AjaxFileUploadHandlerPath { get; set; }
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Afnor.Silverlight.Toolkit.Collections;
using Afnor.Silverlight.Toolkit.ViewServices;
using EspaceClient.BackOffice.Domaine.Criterias;
using EspaceClient.BackOffice.Domaine.Results;
using EspaceClient.BackOffice.Silverlight.Business.Depots;
using EspaceClient.BackOffice.Silverlight.Business.Interfaces;
using EspaceClient.BackOffice.Silverlight.Business.Loader;
using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Modularity;
using EspaceClient.BackOffice.Silverlight.ViewModels.Helper.Resource;
using EspaceClient.BackOffice.Silverlight.ViewModels.Messages;
using EspaceClient.BackOffice.Silverlight.ViewModels.ModelBuilders.GestionContenu.Resource;
using EspaceClient.FrontOffice.Domaine;
using nRoute.Components;
using nRoute.Components.Composition;
using nRoute.Components.Messaging;
using OGDC.Silverlight.Toolkit.Services.Services;
namespace EspaceClient.BackOffice.Silverlight.ViewModels.GestionContenu.Resource.Tabs
{
/// <summary>
/// ViewModel de la vue <see cref="SearchView"/>
/// </summary>
public class SearchViewModel : TabBase
{
private readonly IResourceWrapper _resourceWrapper;
private readonly IDepotRessource _depotResource;
private readonly ILoaderReferentiel _referentiel;
private readonly INavigatableChildWindowService _childWindowService;
private readonly IModelBuilderDetails _builderDetails;
protected ChannelObserver<UpdateListMessage> ObserverUpdateListMessage { get; private set; }
private IEnumerable<TypeRessourceDto> _typeRessources;
private ObservableCollection<RessourceResult> _searchResult;
private SearchResourceCriteriasDto _criteres;
private RessourceResult _selectedResource;
private bool _isLoading;
private ICommand _searchCommand;
private ICommand _resetCommand;
private ICommand _doubleClickCommand;
[ResolveConstructor]
public SearchViewModel(IResourceWrapper resourceWrapper, IDepotRessource depotResource, IMessenging messengingService, IApplicationContext applicationContext, ILoaderReferentiel referentiel, IModelBuilderDetails builderDetails, INavigatableChildWindowService childWindowService)
: base(applicationContext, messengingService)
{
_resourceWrapper = resourceWrapper;
_depotResource = depotResource;
_referentiel = referentiel;
_childWindowService = childWindowService;
_builderDetails = builderDetails;
InitializeCommands();
InitializeUI();
InitializeMessenging();
}
public ObservableCollection<RessourceResult> SearchResult
{
get
{
return _searchResult;
}
set
{
if (_searchResult != value)
{
_searchResult = value;
NotifyPropertyChanged(() => SearchResult);
}
}
}
public SearchResourceCriteriasDto Criteres
{
get
{
return _criteres;
}
set
{
_criteres = value;
NotifyPropertyChanged(() => Criteres);
}
}
public RessourceResult SelectedResource
{
get { return _selectedResource; }
set
{
if (_selectedResource != value)
{
_selectedResource = value;
NotifyPropertyChanged(() => SelectedResource);
}
}
}
public IEnumerable<TypeRessourceDto> TypeRessources
{
get
{
return _typeRessources;
}
set
{
if (_typeRessources != value)
{
_typeRessources = value;
NotifyPropertyChanged(() => TypeRessources);
}
}
}
public bool IsLoading
{
get
{
return _isLoading;
}
set
{
if (_isLoading != value)
{
_isLoading = value;
NotifyPropertyChanged(() => IsLoading);
}
}
}
#region Commands
/// <summary>
/// Command de recherche des utilisateurs
/// </summary>
public ICommand SearchCommand
{
get { return _searchCommand; }
}
public ICommand DoubleClickCommand
{
get
{
return _doubleClickCommand;
}
}
public ICommand ResetCommand
{
get { return _resetCommand; }
}
#endregion
private void InitializeMessenging()
{
ObserverUpdateListMessage = _messengingService.CreateObserver<UpdateListMessage>(msg =>
{
if (msg.Type == TypeUpdateList.RechercheResource)
{
if (SearchCommand.CanExecute(this))
SearchCommand.Execute(this);
}
});
ObserverUpdateListMessage.Subscribe(ThreadOption.UIThread);
}
private void DisposeMessenging()
{
ObserverUpdateListMessage.Unsubscribe();
}
private void InitializeCommands()
{
_searchCommand = new ActionCommand(OnSearch);
_doubleClickCommand = new ActionCommand<RessourceResult>(OnDoubleClickCommand);
_resetCommand = new ActionCommand(OnReset);
}
private void InitializeUI()
{
OnReset();
SearchResult = new ObservableCollection<RessourceResult>();
IsLoading = false;
TypeRessources = _referentiel.Referentiel.TypeRessources.WithEmptyItem(() => new TypeRessourceDto() { ID = -1, Libelle = " " });
}
private void OnReset()
{
Criteres = new SearchResourceCriteriasDto()
{
ResourceName = String.Empty,
TypeResource = -1,
};
}
private void OnSearch()
{
if (IsLoading)
return;
_depotResource.GetResourcesByCriterias(Criteres, r =>
{
foreach (var u in r)
SearchResult.Add(u);
IsLoading = false;
}, error => _messengingService.Publish(new ErrorMessage(error)));
SearchResult.Clear();
IsLoading = true;
}
private void OnDoubleClickCommand(RessourceResult selectedResource)
{
if (selectedResource != null)
{
ResourceHelper.AddResourceTab(selectedResource.ID, _applicationContext, _resourceWrapper, _childWindowService, _messengingService, _depotResource, _builderDetails);
}
}
public override void OnRefreshTab<EntityType>(long id, Action<EntityType> callback)
{
throw new NotImplementedException();
}
protected override void OnRefreshTabCompleted(Action callback)
{
throw new NotImplementedException();
}
}
}
| |
// 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.ComponentModel.Design;
using System.Diagnostics;
using System.Reflection;
namespace System.ComponentModel
{
/// <internalonly/>
/// <summary>
/// <para>
/// ReflectEventDescriptor defines an event. Events are the main way that a user can get
/// run-time notifications from a component.
/// The ReflectEventDescriptor class takes a component class that the event lives on,
/// the event name, the type of the event handling delegate, and various
/// attributes for the event.
/// Every event has a structure through which it passes it's information. The base
/// structure, Event, is empty, and there is a default instance, Event.EMPTY, which
/// is usually passed. When addOnXXX is invoked, it needs a pointer to a method
/// that takes a source object (the object that fired the event) and a structure
/// particular to that event. It also needs a pointer to the instance of the
/// object the method should be invoked on. These two things are what composes a
/// delegate. An event handler is
/// a delegate, and the compiler recognizes a special delegate syntax that makes
/// using delegates easy.
/// For example, to listen to the click event on a button in class Foo, the
/// following code will suffice:
/// </para>
/// <code>
/// class Foo {
/// Button button1 = new Button();
/// void button1_click(Object sender, Event e) {
/// // do something on button1 click.
/// }
/// public Foo() {
/// button1.addOnClick(button1_click);
/// }
/// }
/// </code>
/// For an event named XXX, a YYYEvent structure, and a YYYEventHandler delegate,
/// a component writer is required to implement two methods of the following
/// form:
/// <code>
/// public void addOnXXX(YYYEventHandler handler);
/// public void removeOnXXX(YYYEventHandler handler);
/// </code>
/// YYYEventHandler should be an event handler declared as
/// <code>
/// public multicast delegate void YYYEventHandler(Object sender, YYYEvent e);
/// </code>
/// Note that this event was declared as a multicast delegate. This allows multiple
/// listeners on an event. This is not a requirement.
/// Various attributes can be passed to the ReflectEventDescriptor, as are described in
/// Attribute.
/// ReflectEventDescriptors can be obtained by a user programmatically through the
/// ComponentManager.
/// </summary>
internal sealed class ReflectEventDescriptor : EventDescriptor
{
private static readonly Type[] s_argsNone = new Type[0];
private static readonly object s_noDefault = new object();
private Type _type; // the delegate type for the event
private readonly Type _componentClass; // the class of the component this info is for
private MethodInfo _addMethod; // the method to use when adding an event
private MethodInfo _removeMethod; // the method to use when removing an event
private EventInfo _realEvent; // actual event info... may be null
private bool _filledMethods = false; // did we already call FillMethods() once?
/// <summary>
/// This is the main constructor for an ReflectEventDescriptor.
/// </summary>
public ReflectEventDescriptor(Type componentClass, string name, Type type, Attribute[] attributes)
: base(name, attributes)
{
if (componentClass == null)
{
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, nameof(componentClass)));
}
if (type == null || !(typeof(Delegate)).IsAssignableFrom(type))
{
throw new ArgumentException(SR.Format(SR.ErrorInvalidEventType, name));
}
Debug.Assert(type.GetTypeInfo().IsSubclassOf(typeof(Delegate)), "Not a valid ReflectEvent: " + componentClass.FullName + "." + name + " " + type.FullName);
_componentClass = componentClass;
_type = type;
}
public ReflectEventDescriptor(Type componentClass, EventInfo eventInfo)
: base(eventInfo.Name, new Attribute[0])
{
if (componentClass == null)
{
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, nameof(componentClass)));
}
_componentClass = componentClass;
_realEvent = eventInfo;
}
/// <summary>
/// This constructor takes an existing ReflectEventDescriptor and modifies it by merging in the
/// passed-in attributes.
/// </summary>
public ReflectEventDescriptor(Type componentType, EventDescriptor oldReflectEventDescriptor, Attribute[] attributes)
: base(oldReflectEventDescriptor, attributes)
{
_componentClass = componentType;
_type = oldReflectEventDescriptor.EventType;
ReflectEventDescriptor desc = oldReflectEventDescriptor as ReflectEventDescriptor;
if (desc != null)
{
_addMethod = desc._addMethod;
_removeMethod = desc._removeMethod;
_filledMethods = true;
}
}
/// <summary>
/// Retrieves the type of the component this EventDescriptor is bound to.
/// </summary>
public override Type ComponentType
{
get
{
return _componentClass;
}
}
/// <summary>
/// Retrieves the type of the delegate for this event.
/// </summary>
public override Type EventType
{
get
{
FillMethods();
return _type;
}
}
/// <summary>
/// Indicates whether the delegate type for this event is a multicast delegate.
/// </summary>
public override bool IsMulticast
{
get
{
return (typeof(MulticastDelegate)).IsAssignableFrom(EventType);
}
}
/// <summary>
/// This adds the delegate value as a listener to when this event is fired
/// by the component, invoking the addOnXXX method.
/// </summary>
public override void AddEventHandler(object component, Delegate value)
{
FillMethods();
if (component != null)
{
ISite site = GetSite(component);
#if FEATURE_ICOMPONENTCHANGESERVICE
IComponentChangeService changeService = null;
// Announce that we are about to change this component
//
if (site != null)
{
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
}
if (changeService != null)
{
#if FEATURE_CHECKOUTEXCEPTION
try {
changeService.OnComponentChanging(component, this);
}
catch (CheckoutException coEx) {
if (coEx == CheckoutException.Canceled) {
return;
}
throw coEx;
}
#else
changeService.OnComponentChanging(component, this);
#endif // FEATURE_CHECKOUTEXCEPTION
}
#endif // FEATURE_ICOMPONENTCHANGESERVICE
bool shadowed = false;
if (site != null && site.DesignMode)
{
// Events are final, so just check the class
if (EventType != value.GetType())
{
throw new ArgumentException(SR.Format(SR.ErrorInvalidEventHandler, Name));
}
IDictionaryService dict = (IDictionaryService)site.GetService(typeof(IDictionaryService));
if (dict != null)
{
Delegate eventdesc = (Delegate)dict.GetValue(this);
eventdesc = Delegate.Combine(eventdesc, value);
dict.SetValue(this, eventdesc);
shadowed = true;
}
}
if (!shadowed)
{
_addMethod.Invoke(component, new[] { value });
}
#if FEATURE_ICOMPONENTCHANGESERVICE
// Now notify the change service that the change was successful.
//
if (changeService != null)
{
changeService.OnComponentChanged(component, this, null, value);
}
#endif
}
}
// <doc>
// <desc>
// Adds in custom attributes found on either the AddOn or RemoveOn method...
// </desc>
// </doc>
//
protected override void FillAttributes(IList attributes)
{
//
// The order that we fill in attributes is critical. The list of attributes will be
// filtered so that matching attributes at the end of the list replace earlier matches
// (last one in wins). Therefore, the two categories of attributes we add must be
// added as follows:
//
// 1. Attributes of the event, from base class to most derived. This way
// derived class attributes replace base class attributes.
//
// 2. Attributes from our base MemberDescriptor. While this seems opposite of what
// we want, MemberDescriptor only has attributes if someone passed in a new
// set in the constructor. Therefore, these attributes always
// supercede existing values.
//
FillMethods();
Debug.Assert(_componentClass != null, "Must have a component class for FilterAttributes");
if (_realEvent != null)
{
FillEventInfoAttribute(_realEvent, attributes);
}
else
{
Debug.Assert(_removeMethod != null, "Null remove method for " + Name);
FillSingleMethodAttribute(_removeMethod, attributes);
Debug.Assert(_addMethod != null, "Null remove method for " + Name);
FillSingleMethodAttribute(_addMethod, attributes);
}
// Include the base attributes. These override all attributes on the actual
// property, so we want to add them last.
//
base.FillAttributes(attributes);
}
private void FillEventInfoAttribute(EventInfo realEventInfo, IList attributes)
{
string eventName = realEventInfo.Name;
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly;
#if FEATURE_MEMBERINFO_REFLECTEDTYPE
Type currentReflectType = realEventInfo.ReflectedType;
#else
Type currentReflectType = _componentClass;
#endif
Debug.Assert(currentReflectType != null, "currentReflectType cannot be null");
int depth = 0;
// First, calculate the depth of the object hierarchy. We do this so we can do a single
// object create for an array of attributes.
//
while (currentReflectType != typeof(object))
{
depth++;
currentReflectType = currentReflectType.GetTypeInfo().BaseType;
}
if (depth > 0)
{
// Now build up an array in reverse order
//
#if FEATURE_MEMBERINFO_REFLECTEDTYPE
currentReflectType = realEventInfo.ReflectedType;
#else
currentReflectType = _componentClass;
#endif
Attribute[][] attributeStack = new Attribute[depth][];
while (currentReflectType != typeof(object))
{
// Fill in our member info so we can get at the custom attributes.
//
MemberInfo memberInfo = currentReflectType.GetEvent(eventName, bindingFlags);
// Get custom attributes for the member info.
//
if (memberInfo != null)
{
attributeStack[--depth] = ReflectTypeDescriptionProvider.ReflectGetAttributes(memberInfo);
}
// Ready for the next loop iteration.
//
currentReflectType = currentReflectType.GetTypeInfo().BaseType;
}
// Now trawl the attribute stack so that we add attributes
// from base class to most derived.
//
foreach (Attribute[] attributeArray in attributeStack)
{
if (attributeArray != null)
{
foreach (Attribute attr in attributeArray)
{
attributes.Add(attr);
}
}
}
}
}
/// <summary>
/// This fills the get and set method fields of the event info. It is shared
/// by the various constructors.
/// </summary>
private void FillMethods()
{
if (_filledMethods) return;
if (_realEvent != null)
{
_addMethod = _realEvent.GetAddMethod();
_removeMethod = _realEvent.GetRemoveMethod();
EventInfo defined = null;
if (_addMethod == null || _removeMethod == null)
{
Type start = _componentClass.GetTypeInfo().BaseType;
while (start != null && start != typeof(object))
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
EventInfo test = start.GetEvent(_realEvent.Name, bindingFlags);
if (test.GetAddMethod() != null)
{
defined = test;
break;
}
}
}
if (defined != null)
{
_addMethod = defined.GetAddMethod();
_removeMethod = defined.GetRemoveMethod();
_type = defined.EventHandlerType;
}
else
{
_type = _realEvent.EventHandlerType;
}
}
else
{
// first, try to get the eventInfo...
//
_realEvent = _componentClass.GetEvent(Name);
if (_realEvent != null)
{
// if we got one, just recurse and return.
//
FillMethods();
return;
}
Type[] argsType = new Type[] { _type };
_addMethod = FindMethod(_componentClass, "AddOn" + Name, argsType, typeof(void));
_removeMethod = FindMethod(_componentClass, "RemoveOn" + Name, argsType, typeof(void));
if (_addMethod == null || _removeMethod == null)
{
Debug.Fail("Missing event accessors for " + _componentClass.FullName + "." + Name);
throw new ArgumentException(SR.Format(SR.ErrorMissingEventAccessors, Name));
}
}
_filledMethods = true;
}
private void FillSingleMethodAttribute(MethodInfo realMethodInfo, IList attributes)
{
string methodName = realMethodInfo.Name;
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly;
#if FEATURE_MEMBERINFO_REFLECTEDTYPE
Type currentReflectType = realEventInfo.ReflectedType;
#else
Type currentReflectType = _componentClass;
#endif
Debug.Assert(currentReflectType != null, "currentReflectType cannot be null");
// First, calculate the depth of the object hierarchy. We do this so we can do a single
// object create for an array of attributes.
//
int depth = 0;
while (currentReflectType != null && currentReflectType != typeof(object))
{
depth++;
currentReflectType = currentReflectType.GetTypeInfo().BaseType;
}
if (depth > 0)
{
// Now build up an array in reverse order
//
#if FEATURE_MEMBERINFO_REFLECTEDTYPE
currentReflectType = realEventInfo.ReflectedType;
#else
currentReflectType = _componentClass;
#endif
Attribute[][] attributeStack = new Attribute[depth][];
while (currentReflectType != null && currentReflectType != typeof(object))
{
// Fill in our member info so we can get at the custom attributes.
//
MemberInfo memberInfo = currentReflectType.GetMethod(methodName, bindingFlags);
// Get custom attributes for the member info.
//
if (memberInfo != null)
{
attributeStack[--depth] = ReflectTypeDescriptionProvider.ReflectGetAttributes(memberInfo);
}
// Ready for the next loop iteration.
//
currentReflectType = currentReflectType.GetTypeInfo().BaseType;
}
// Now trawl the attribute stack so that we add attributes
// from base class to most derived.
//
foreach (Attribute[] attributeArray in attributeStack)
{
if (attributeArray != null)
{
foreach (Attribute attr in attributeArray)
{
attributes.Add(attr);
}
}
}
}
}
/// <summary>
/// This will remove the delegate value from the event chain so that
/// it no longer gets events from this component.
/// </summary>
public override void RemoveEventHandler(object component, Delegate value)
{
FillMethods();
if (component != null)
{
ISite site = GetSite(component);
#if FEATURE_ICOMPONENTCHANGESERVICE
IComponentChangeService changeService = null;
// Announce that we are about to change this component
//
if (site != null)
{
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
}
if (changeService != null)
{
#if FEATURE_CHECKOUTEXCEPTION
try {
changeService.OnComponentChanging(component, this);
}
catch (CheckoutException coEx) {
if (coEx == CheckoutException.Canceled) {
return;
}
throw coEx;
}
#else
changeService.OnComponentChanging(component, this);
#endif // FEATURE_CHECKOUTEXCEPTION
}
#endif // FEATURE_ICOMPONENTCHANGESERVICE
bool shadowed = false;
if (site != null && site.DesignMode)
{
IDictionaryService dict = (IDictionaryService)site.GetService(typeof(IDictionaryService));
if (dict != null)
{
Delegate del = (Delegate)dict.GetValue(this);
del = Delegate.Remove(del, value);
dict.SetValue(this, del);
shadowed = true;
}
}
if (!shadowed)
{
_removeMethod.Invoke(component, new[] { value });
}
#if FEATURE_ICOMPONENTCHANGESERVICE
// Now notify the change service that the change was successful.
//
if (changeService != null)
{
changeService.OnComponentChanged(component, this, null, value);
}
#endif
}
}
}
}
| |
// 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;
_codeElementTable.CleanUpDeadObjects();
needMoreTime = _codeElementTable.NeedsCleanUp;
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;
}
if (!TryGetDocument(out var 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_CodeModel(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;
}
if (!provider.ProjectCodeModel.TryGetCachedFileCodeModel(this.Workspace.GetFilePath(GetDocumentId()), out var fileCodeModelHandle))
{
return needMoreTime;
}
var extensibility = (EnvDTE80.IVsExtensibility2)this.State.ServiceProvider.GetService(typeof(EnvDTE.IVsExtensibility));
foreach (var codeModelEvent in eventQueue)
{
GetElementsForCodeModelEvent(codeModelEvent, out var element, out var 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.GetOrCreateCodeElement<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.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode);
}
}
else if (this.CodeModelService.IsAttributeNode(codeModelEvent.Node))
{
if (codeModelEvent.ParentNode != null)
{
return this.GetOrCreateCodeElement<EnvDTE.CodeElement>(codeModelEvent.ParentNode);
}
else
{
return this;
}
}
else if (codeModelEvent.Type == CodeModelEventType.Remove)
{
if (codeModelEvent.ParentNode != null &&
codeModelEvent.ParentNode.Parent != null)
{
return this.GetOrCreateCodeElement<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;
}
CodeModelService.GetAttributeNameAndOrdinal(parentNode, node, out var name, out var 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 testOrdinal = 0;
foreach (EnvDTE.CodeElement element in elementsToSearch)
{
if (element.Kind != EnvDTE.vsCMElement.vsCMElementAttribute)
{
continue;
}
if (element.Name == name)
{
if (ordinal == testOrdinal)
{
return element;
}
testOrdinal++;
}
}
}
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;
}
CodeModelService.GetAttributeArgumentParentAndIndex(codeModelEvent.Node, out var attributeNode, out var 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;
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: api@infopluscommerce.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
/// ParcelShipment
/// </summary>
[DataContract]
public partial class ParcelShipment : IEquatable<ParcelShipment>
{
/// <summary>
/// Initializes a new instance of the <see cref="ParcelShipment" /> class.
/// </summary>
[JsonConstructorAttribute]
protected ParcelShipment() { }
/// <summary>
/// Initializes a new instance of the <see cref="ParcelShipment" /> class.
/// </summary>
/// <param name="Id">Id.</param>
/// <param name="WarehouseId">WarehouseId (required).</param>
/// <param name="CartonNo">CartonNo.</param>
/// <param name="NumberOfCartons">NumberOfCartons.</param>
/// <param name="Shipped">Shipped (default to false).</param>
/// <param name="CarrierServiceId">CarrierServiceId.</param>
/// <param name="Dim1In">Dim1In.</param>
/// <param name="Dim2In">Dim2In.</param>
/// <param name="Dim3In">Dim3In.</param>
/// <param name="EstimatedZone">EstimatedZone.</param>
public ParcelShipment(int? Id = null, int? WarehouseId = null, int? CartonNo = null, int? NumberOfCartons = null, bool? Shipped = null, int? CarrierServiceId = null, double? Dim1In = null, double? Dim2In = null, double? Dim3In = null, string EstimatedZone = null)
{
// to ensure "WarehouseId" is required (not null)
if (WarehouseId == null)
{
throw new InvalidDataException("WarehouseId is a required property for ParcelShipment and cannot be null");
}
else
{
this.WarehouseId = WarehouseId;
}
this.Id = Id;
this.CartonNo = CartonNo;
this.NumberOfCartons = NumberOfCartons;
// use default value if no "Shipped" provided
if (Shipped == null)
{
this.Shipped = false;
}
else
{
this.Shipped = Shipped;
}
this.CarrierServiceId = CarrierServiceId;
this.Dim1In = Dim1In;
this.Dim2In = Dim2In;
this.Dim3In = Dim3In;
this.EstimatedZone = EstimatedZone;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private set; }
/// <summary>
/// Gets or Sets ShipDate
/// </summary>
[DataMember(Name="shipDate", EmitDefaultValue=false)]
public DateTime? ShipDate { get; private set; }
/// <summary>
/// Gets or Sets DeliveredDate
/// </summary>
[DataMember(Name="deliveredDate", EmitDefaultValue=false)]
public DateTime? DeliveredDate { get; private set; }
/// <summary>
/// Gets or Sets TrackingNo
/// </summary>
[DataMember(Name="trackingNo", EmitDefaultValue=false)]
public string TrackingNo { get; private set; }
/// <summary>
/// Gets or Sets WarehouseId
/// </summary>
[DataMember(Name="warehouseId", EmitDefaultValue=false)]
public int? WarehouseId { get; set; }
/// <summary>
/// Gets or Sets LobId
/// </summary>
[DataMember(Name="lobId", EmitDefaultValue=false)]
public int? LobId { get; private set; }
/// <summary>
/// Gets or Sets OrderNo
/// </summary>
[DataMember(Name="orderNo", EmitDefaultValue=false)]
public double? OrderNo { get; private set; }
/// <summary>
/// Gets or Sets CartonNo
/// </summary>
[DataMember(Name="cartonNo", EmitDefaultValue=false)]
public int? CartonNo { get; set; }
/// <summary>
/// Gets or Sets NumberOfCartons
/// </summary>
[DataMember(Name="numberOfCartons", EmitDefaultValue=false)]
public int? NumberOfCartons { get; set; }
/// <summary>
/// Gets or Sets Status
/// </summary>
[DataMember(Name="status", EmitDefaultValue=false)]
public string Status { get; private set; }
/// <summary>
/// Gets or Sets Shipped
/// </summary>
[DataMember(Name="shipped", EmitDefaultValue=false)]
public bool? Shipped { get; set; }
/// <summary>
/// Gets or Sets CarrierServiceId
/// </summary>
[DataMember(Name="carrierServiceId", EmitDefaultValue=false)]
public int? CarrierServiceId { get; set; }
/// <summary>
/// Gets or Sets Dim1In
/// </summary>
[DataMember(Name="dim1In", EmitDefaultValue=false)]
public double? Dim1In { get; set; }
/// <summary>
/// Gets or Sets Dim2In
/// </summary>
[DataMember(Name="dim2In", EmitDefaultValue=false)]
public double? Dim2In { get; set; }
/// <summary>
/// Gets or Sets Dim3In
/// </summary>
[DataMember(Name="dim3In", EmitDefaultValue=false)]
public double? Dim3In { get; set; }
/// <summary>
/// Gets or Sets EstimatedZone
/// </summary>
[DataMember(Name="estimatedZone", EmitDefaultValue=false)]
public string EstimatedZone { get; set; }
/// <summary>
/// Gets or Sets ParcelAccountNo
/// </summary>
[DataMember(Name="parcelAccountNo", EmitDefaultValue=false)]
public string ParcelAccountNo { get; private set; }
/// <summary>
/// Gets or Sets ThirdPartyParcelAccountNo
/// </summary>
[DataMember(Name="thirdPartyParcelAccountNo", EmitDefaultValue=false)]
public string ThirdPartyParcelAccountNo { get; private set; }
/// <summary>
/// Gets or Sets ManifestId
/// </summary>
[DataMember(Name="manifestId", EmitDefaultValue=false)]
public int? ManifestId { get; private set; }
/// <summary>
/// Gets or Sets Residential
/// </summary>
[DataMember(Name="residential", EmitDefaultValue=false)]
public bool? Residential { get; private set; }
/// <summary>
/// Gets or Sets BillingOption
/// </summary>
[DataMember(Name="billingOption", EmitDefaultValue=false)]
public string BillingOption { get; private set; }
/// <summary>
/// Gets or Sets WeightLbs
/// </summary>
[DataMember(Name="weightLbs", EmitDefaultValue=false)]
public double? WeightLbs { get; private set; }
/// <summary>
/// Gets or Sets DimWeight
/// </summary>
[DataMember(Name="dimWeight", EmitDefaultValue=false)]
public double? DimWeight { get; private set; }
/// <summary>
/// Gets or Sets LicensePlateNumber
/// </summary>
[DataMember(Name="licensePlateNumber", EmitDefaultValue=false)]
public string LicensePlateNumber { get; private set; }
/// <summary>
/// Gets or Sets ChargedFreightAmount
/// </summary>
[DataMember(Name="chargedFreightAmount", EmitDefaultValue=false)]
public double? ChargedFreightAmount { get; private set; }
/// <summary>
/// Gets or Sets PublishedFreightAmount
/// </summary>
[DataMember(Name="publishedFreightAmount", EmitDefaultValue=false)]
public double? PublishedFreightAmount { get; private set; }
/// <summary>
/// Gets or Sets RetailFreightAmount
/// </summary>
[DataMember(Name="retailFreightAmount", EmitDefaultValue=false)]
public double? RetailFreightAmount { get; private 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 ParcelShipment {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append(" ShipDate: ").Append(ShipDate).Append("\n");
sb.Append(" DeliveredDate: ").Append(DeliveredDate).Append("\n");
sb.Append(" TrackingNo: ").Append(TrackingNo).Append("\n");
sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n");
sb.Append(" LobId: ").Append(LobId).Append("\n");
sb.Append(" OrderNo: ").Append(OrderNo).Append("\n");
sb.Append(" CartonNo: ").Append(CartonNo).Append("\n");
sb.Append(" NumberOfCartons: ").Append(NumberOfCartons).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" Shipped: ").Append(Shipped).Append("\n");
sb.Append(" CarrierServiceId: ").Append(CarrierServiceId).Append("\n");
sb.Append(" Dim1In: ").Append(Dim1In).Append("\n");
sb.Append(" Dim2In: ").Append(Dim2In).Append("\n");
sb.Append(" Dim3In: ").Append(Dim3In).Append("\n");
sb.Append(" EstimatedZone: ").Append(EstimatedZone).Append("\n");
sb.Append(" ParcelAccountNo: ").Append(ParcelAccountNo).Append("\n");
sb.Append(" ThirdPartyParcelAccountNo: ").Append(ThirdPartyParcelAccountNo).Append("\n");
sb.Append(" ManifestId: ").Append(ManifestId).Append("\n");
sb.Append(" Residential: ").Append(Residential).Append("\n");
sb.Append(" BillingOption: ").Append(BillingOption).Append("\n");
sb.Append(" WeightLbs: ").Append(WeightLbs).Append("\n");
sb.Append(" DimWeight: ").Append(DimWeight).Append("\n");
sb.Append(" LicensePlateNumber: ").Append(LicensePlateNumber).Append("\n");
sb.Append(" ChargedFreightAmount: ").Append(ChargedFreightAmount).Append("\n");
sb.Append(" PublishedFreightAmount: ").Append(PublishedFreightAmount).Append("\n");
sb.Append(" RetailFreightAmount: ").Append(RetailFreightAmount).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 ParcelShipment);
}
/// <summary>
/// Returns true if ParcelShipment instances are equal
/// </summary>
/// <param name="other">Instance of ParcelShipment to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ParcelShipment other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
) &&
(
this.ShipDate == other.ShipDate ||
this.ShipDate != null &&
this.ShipDate.Equals(other.ShipDate)
) &&
(
this.DeliveredDate == other.DeliveredDate ||
this.DeliveredDate != null &&
this.DeliveredDate.Equals(other.DeliveredDate)
) &&
(
this.TrackingNo == other.TrackingNo ||
this.TrackingNo != null &&
this.TrackingNo.Equals(other.TrackingNo)
) &&
(
this.WarehouseId == other.WarehouseId ||
this.WarehouseId != null &&
this.WarehouseId.Equals(other.WarehouseId)
) &&
(
this.LobId == other.LobId ||
this.LobId != null &&
this.LobId.Equals(other.LobId)
) &&
(
this.OrderNo == other.OrderNo ||
this.OrderNo != null &&
this.OrderNo.Equals(other.OrderNo)
) &&
(
this.CartonNo == other.CartonNo ||
this.CartonNo != null &&
this.CartonNo.Equals(other.CartonNo)
) &&
(
this.NumberOfCartons == other.NumberOfCartons ||
this.NumberOfCartons != null &&
this.NumberOfCartons.Equals(other.NumberOfCartons)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.Shipped == other.Shipped ||
this.Shipped != null &&
this.Shipped.Equals(other.Shipped)
) &&
(
this.CarrierServiceId == other.CarrierServiceId ||
this.CarrierServiceId != null &&
this.CarrierServiceId.Equals(other.CarrierServiceId)
) &&
(
this.Dim1In == other.Dim1In ||
this.Dim1In != null &&
this.Dim1In.Equals(other.Dim1In)
) &&
(
this.Dim2In == other.Dim2In ||
this.Dim2In != null &&
this.Dim2In.Equals(other.Dim2In)
) &&
(
this.Dim3In == other.Dim3In ||
this.Dim3In != null &&
this.Dim3In.Equals(other.Dim3In)
) &&
(
this.EstimatedZone == other.EstimatedZone ||
this.EstimatedZone != null &&
this.EstimatedZone.Equals(other.EstimatedZone)
) &&
(
this.ParcelAccountNo == other.ParcelAccountNo ||
this.ParcelAccountNo != null &&
this.ParcelAccountNo.Equals(other.ParcelAccountNo)
) &&
(
this.ThirdPartyParcelAccountNo == other.ThirdPartyParcelAccountNo ||
this.ThirdPartyParcelAccountNo != null &&
this.ThirdPartyParcelAccountNo.Equals(other.ThirdPartyParcelAccountNo)
) &&
(
this.ManifestId == other.ManifestId ||
this.ManifestId != null &&
this.ManifestId.Equals(other.ManifestId)
) &&
(
this.Residential == other.Residential ||
this.Residential != null &&
this.Residential.Equals(other.Residential)
) &&
(
this.BillingOption == other.BillingOption ||
this.BillingOption != null &&
this.BillingOption.Equals(other.BillingOption)
) &&
(
this.WeightLbs == other.WeightLbs ||
this.WeightLbs != null &&
this.WeightLbs.Equals(other.WeightLbs)
) &&
(
this.DimWeight == other.DimWeight ||
this.DimWeight != null &&
this.DimWeight.Equals(other.DimWeight)
) &&
(
this.LicensePlateNumber == other.LicensePlateNumber ||
this.LicensePlateNumber != null &&
this.LicensePlateNumber.Equals(other.LicensePlateNumber)
) &&
(
this.ChargedFreightAmount == other.ChargedFreightAmount ||
this.ChargedFreightAmount != null &&
this.ChargedFreightAmount.Equals(other.ChargedFreightAmount)
) &&
(
this.PublishedFreightAmount == other.PublishedFreightAmount ||
this.PublishedFreightAmount != null &&
this.PublishedFreightAmount.Equals(other.PublishedFreightAmount)
) &&
(
this.RetailFreightAmount == other.RetailFreightAmount ||
this.RetailFreightAmount != null &&
this.RetailFreightAmount.Equals(other.RetailFreightAmount)
);
}
/// <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.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
if (this.ShipDate != null)
hash = hash * 59 + this.ShipDate.GetHashCode();
if (this.DeliveredDate != null)
hash = hash * 59 + this.DeliveredDate.GetHashCode();
if (this.TrackingNo != null)
hash = hash * 59 + this.TrackingNo.GetHashCode();
if (this.WarehouseId != null)
hash = hash * 59 + this.WarehouseId.GetHashCode();
if (this.LobId != null)
hash = hash * 59 + this.LobId.GetHashCode();
if (this.OrderNo != null)
hash = hash * 59 + this.OrderNo.GetHashCode();
if (this.CartonNo != null)
hash = hash * 59 + this.CartonNo.GetHashCode();
if (this.NumberOfCartons != null)
hash = hash * 59 + this.NumberOfCartons.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.Shipped != null)
hash = hash * 59 + this.Shipped.GetHashCode();
if (this.CarrierServiceId != null)
hash = hash * 59 + this.CarrierServiceId.GetHashCode();
if (this.Dim1In != null)
hash = hash * 59 + this.Dim1In.GetHashCode();
if (this.Dim2In != null)
hash = hash * 59 + this.Dim2In.GetHashCode();
if (this.Dim3In != null)
hash = hash * 59 + this.Dim3In.GetHashCode();
if (this.EstimatedZone != null)
hash = hash * 59 + this.EstimatedZone.GetHashCode();
if (this.ParcelAccountNo != null)
hash = hash * 59 + this.ParcelAccountNo.GetHashCode();
if (this.ThirdPartyParcelAccountNo != null)
hash = hash * 59 + this.ThirdPartyParcelAccountNo.GetHashCode();
if (this.ManifestId != null)
hash = hash * 59 + this.ManifestId.GetHashCode();
if (this.Residential != null)
hash = hash * 59 + this.Residential.GetHashCode();
if (this.BillingOption != null)
hash = hash * 59 + this.BillingOption.GetHashCode();
if (this.WeightLbs != null)
hash = hash * 59 + this.WeightLbs.GetHashCode();
if (this.DimWeight != null)
hash = hash * 59 + this.DimWeight.GetHashCode();
if (this.LicensePlateNumber != null)
hash = hash * 59 + this.LicensePlateNumber.GetHashCode();
if (this.ChargedFreightAmount != null)
hash = hash * 59 + this.ChargedFreightAmount.GetHashCode();
if (this.PublishedFreightAmount != null)
hash = hash * 59 + this.PublishedFreightAmount.GetHashCode();
if (this.RetailFreightAmount != null)
hash = hash * 59 + this.RetailFreightAmount.GetHashCode();
return hash;
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elasticbeanstalk-2010-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.ElasticBeanstalk.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.ElasticBeanstalk.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for TerminateEnvironment operation
/// </summary>
public class TerminateEnvironmentResponseUnmarshaller : XmlResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
TerminateEnvironmentResponse response = new TerminateEnvironmentResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.IsStartElement)
{
if(context.TestExpression("TerminateEnvironmentResult", 2))
{
UnmarshallResult(context, response);
continue;
}
if (context.TestExpression("ResponseMetadata", 2))
{
response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
}
}
}
return response;
}
private static void UnmarshallResult(XmlUnmarshallerContext context, TerminateEnvironmentResponse response)
{
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("AbortableOperationInProgress", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
response.AbortableOperationInProgress = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ApplicationName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.ApplicationName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("CNAME", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.CNAME = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("DateCreated", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
response.DateCreated = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("DateUpdated", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
response.DateUpdated = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Description", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Description = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("EndpointURL", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.EndpointURL = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("EnvironmentId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.EnvironmentId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("EnvironmentName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.EnvironmentName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Health", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Health = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("HealthStatus", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.HealthStatus = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Resources", targetDepth))
{
var unmarshaller = EnvironmentResourcesDescriptionUnmarshaller.Instance;
response.Resources = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("SolutionStackName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.SolutionStackName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Status", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Status = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("TemplateName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.TemplateName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Tier", targetDepth))
{
var unmarshaller = EnvironmentTierUnmarshaller.Instance;
response.Tier = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("VersionLabel", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.VersionLabel = unmarshaller.Unmarshall(context);
continue;
}
}
}
return;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("InsufficientPrivilegesException"))
{
return new InsufficientPrivilegesException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonElasticBeanstalkException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static TerminateEnvironmentResponseUnmarshaller _instance = new TerminateEnvironmentResponseUnmarshaller();
internal static TerminateEnvironmentResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static TerminateEnvironmentResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SqlExecute.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.SqlServer
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using MSBuild.ExtensionPack.SqlServer.Extended;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>Execute</i> (<b>Required: </b> ConnectionString, Sql or Files <b>Optional:</b> CodePage, CommandTimeout, Parameters, Retry, UseTransaction, IgnoreScriptErrors, StripMultiLineComments <b>Output: </b> FailedScripts)</para>
/// <para><i>ExecuteRawReader</i> (<b>Required: </b> ConnectionString, Sql <b>Optional:</b> CodePage, CommandTimeout, Parameters, Retry, UseTransaction, IgnoreScriptErrors <b>Output: </b> RawReaderResult, FailedScripts)</para>
/// <para><i>ExecuteReader</i> (<b>Required: </b> ConnectionString, Sql <b>Optional:</b> CodePage, CommandTimeout, Parameters, Retry, UseTransaction, IgnoreScriptErrors <b>Output: </b> ReaderResult, FailedScripts)</para>
/// <para><i>ExecuteScalar</i> (<b>Required: </b> ConnectionString, Sql <b>Optional:</b> CodePage, CommandTimeout, Parameters, Retry, UseTransaction, IgnoreScriptErrors <b>Output: </b> ScalarResult, FailedScripts)</para>
/// <para><b>Remote Execution Support:</b> NA</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <ItemGroup>
/// <Files Include="C:\a\Proc1.sql"/>
/// <Files Include="C:\a\Proc2.sql"/>
/// <Files Include="C:\a\Proc3.sql"/>
/// <File2s Include="C:\a\SQLQuery1.sql"/>
/// <File2s Include="C:\a\SQLQuery2.sql"/>
/// </ItemGroup>
/// <Target Name="Default">
/// <!-- Execute SQL and return a scalar -->
/// <MSBuild.ExtensionPack.SqlServer.SqlExecute TaskAction="ExecuteScalar" UseTransaction="true" Sql="Select GETDATE()" ConnectionString="Data Source=desktop\Sql2008;Initial Catalog=;Integrated Security=True">
/// <Output PropertyName="ScResult" TaskParameter="ScalarResult"/>
/// </MSBuild.ExtensionPack.SqlServer.SqlExecute>
/// <Message Text="$(ScResult)"/>
/// <!-- Execute SQL and return the result in raw text form -->
/// <MSBuild.ExtensionPack.SqlServer.SqlExecute TaskAction="ExecuteRawReader" UseTransaction="true" Sql="Select * from sys.tables" ConnectionString="Data Source=desktop\Sql2008;Initial Catalog=;Integrated Security=True">
/// <Output PropertyName="RawResult" TaskParameter="RawReaderResult"/>
/// </MSBuild.ExtensionPack.SqlServer.SqlExecute>
/// <Message Text="$(RawResult)"/>
/// <!-- Execute SQL and return the result in an Item. Each column is available as metadata -->
/// <MSBuild.ExtensionPack.SqlServer.SqlExecute TaskAction="ExecuteReader" Sql="Select * from sys.tables" ConnectionString="Data Source=desktop\Sql2008;Initial Catalog=;Integrated Security=True">
/// <Output ItemName="RResult" TaskParameter="ReaderResult"/>
/// </MSBuild.ExtensionPack.SqlServer.SqlExecute>
/// <Message Text="%(RResult.Identity) - %(RResult.object_id)"/>
/// <!-- Execute some sql files -->
/// <MSBuild.ExtensionPack.SqlServer.SqlExecute TaskAction="Execute" Retry="true" UseTransaction="true" Files="@(Files)" ConnectionString="Data Source=desktop\Sql2008;Initial Catalog=;Integrated Security=True"/>
/// <!-- Use Parameter substitution -->
/// <ItemGroup>
/// <SqlFiles Include="createLinkedServer.sql"/>
/// <SqlParameters Include="true">
/// <name>%24(LINKEDSERVER)</name>
/// <value>myserver\myinstance</value>
/// </SqlParameters>
/// </ItemGroup>
/// <MSBuild.ExtensionPack.SqlServer.SqlExecute TaskAction="Execute" Files="@(SqlFiles)" ConnectionString="Data Source=desktop\Sql2008;Initial Catalog=;Integrated Security=True" Parameters="@(SqlParameters)" />
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class SqlExecute : BaseTask
{
private const string ExecuteTaskAction = "Execute";
private const string ExecuteScalarTaskAction = "ExecuteScalar";
private const string ExecuteReaderTaskAction = "ExecuteReader";
private const string ExecuteRawReaderTaskAction = "ExecuteRawReader";
private static readonly Regex Splitter = new Regex(@"^\s*GO\s+", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline);
private int commandTimeout = 30;
private DateTime timer;
private bool stripMultiLineComments = true;
internal delegate void ScriptExecutionEventHandler(object sender, ExecuteEventArgs e);
internal event ScriptExecutionEventHandler ScriptFileExecuted;
/// <summary>
/// Sets the connection string to use for executing the Sql or Files
/// </summary>
public string ConnectionString { get; set; }
/// <summary>
/// Sets the timeout in seconds. Default is 30
/// </summary>
public int CommandTimeout
{
get { return this.commandTimeout; }
set { this.commandTimeout = value; }
}
/// <summary>
/// Allows setting encoding code page to be used. Default is System.Text.Encoding.Default
/// All code pages are listed here: http://msdn.microsoft.com/en-us/library/system.text.encoding
/// </summary>
public int CodePage { get; set; }
/// <summary>
/// Sets the files to execute
/// </summary>
public ITaskItem[] Files { get; set; }
/// <summary>
/// Sets the Sql to execute
/// </summary>
public string Sql { get; set; }
/// <summary>
/// Sets the parameters to substitute at execution time. These are CASE SENSITIVE.
/// </summary>
public ITaskItem[] Parameters { get; set; }
/// <summary>
/// Specifies whether files should be re-executed if they initially fail
/// </summary>
public bool Retry { get; set; }
/// <summary>
/// Specifies whether to parse out multi-line comments before executing. This can be handy if your comments contain GO statements. Please note that if your sql contains code with /* in it, then you should set this to false. Default is true.
/// </summary>
public bool StripMultiLineComments
{
get { return this.stripMultiLineComments; }
set { this.stripMultiLineComments = value; }
}
/// <summary>
/// Set to true to run the sql within a transaction
/// </summary>
public bool UseTransaction { get; set; }
/// <summary>
/// Ignore any script errors, i.e. continue executing any remaining scripts when an error is encountered. Failed
/// scripts will be returned in the FailedScripts output item.
/// </summary>
public bool IgnoreScriptErrors { get; set; }
/// <summary>
/// Gets the scalar result
/// </summary>
[Output]
public string ScalarResult { get; set; }
/// <summary>
/// Gets the raw output from the reader
/// </summary>
[Output]
public string RawReaderResult { get; set; }
/// <summary>
/// Gets the output from a reader in an Item with metadata matching the names of columns. The first column returned will be used as the identity.
/// </summary>
[Output]
public ITaskItem[] ReaderResult { get; set; }
/// <summary>
/// A list of failed scripts. Each will have metadata item ErrorMessage set to the error encountered.
/// </summary>
[Output]
public ITaskItem[] FailedScripts { get; set; }
protected override void InternalExecute()
{
switch (this.TaskAction)
{
case ExecuteTaskAction:
case ExecuteScalarTaskAction:
case ExecuteReaderTaskAction:
case ExecuteRawReaderTaskAction:
this.ExecuteSql();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private string LoadScript(string fileName)
{
System.Text.Encoding readEncoding;
if (this.CodePage > 0)
{
try
{
readEncoding = System.Text.Encoding.GetEncoding(this.CodePage);
}
catch
{
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid CodePage passed: {0}", this.CodePage));
throw;
}
}
else
{
readEncoding = System.Text.Encoding.Default;
}
string retValue;
using (StreamReader textFileReader = new StreamReader(fileName, readEncoding, true))
{
retValue = new SqlScriptLoader(textFileReader, this.StripMultiLineComments).ReadToEnd();
}
return retValue;
}
private string SubstituteParameters(string sqlCommandText)
{
if (this.Parameters == null)
{
return sqlCommandText;
}
return this.Parameters.Aggregate(sqlCommandText, (current, parameter) => current.Replace(parameter.GetMetadata("name"), parameter.GetMetadata("value")));
}
private void ExecuteSql()
{
this.ScriptFileExecuted += this.ScriptExecuted;
try
{
this.timer = DateTime.Now;
if (!string.IsNullOrEmpty(this.Sql))
{
this.ExecuteText();
}
else
{
this.ExecuteFiles();
}
}
finally
{
this.ScriptFileExecuted -= this.ScriptExecuted;
}
}
private void ExecuteFiles()
{
bool retry = true;
int previousFailures = this.Files.Length;
ApplicationException lastException = null;
using (SqlConnection sqlConnection = this.CreateConnection(this.ConnectionString))
{
sqlConnection.Open();
while (retry)
{
int errorNo = 0;
ITaskItem[] failures = new ITaskItem[this.Files.Length];
var failedScripts = new List<ITaskItem>();
foreach (ITaskItem fileInfo in this.Files)
{
this.LogTaskMessage(MessageImportance.High, string.Format(CultureInfo.CurrentCulture, "Execute: {0}", fileInfo.ItemSpec));
try
{
this.LogTaskMessage(MessageImportance.Low, "Loading {0}.", new[] { fileInfo.ItemSpec });
string sqlCommandText = this.SubstituteParameters(this.LoadScript(fileInfo.ItemSpec)) + Environment.NewLine;
string[] batches = Splitter.Split(sqlCommandText);
this.LogTaskMessage(MessageImportance.Low, "Split {0} into {1} batches.", new object[] { fileInfo.ItemSpec, batches.Length });
SqlTransaction sqlTransaction = null;
SqlCommand command = sqlConnection.CreateCommand();
if (this.UseTransaction)
{
sqlTransaction = sqlConnection.BeginTransaction();
}
try
{
int batchNum = 1;
foreach (string batchText in batches)
{
sqlCommandText = batchText.Trim();
if (sqlCommandText.Length > 0)
{
command.CommandText = sqlCommandText;
command.CommandTimeout = this.CommandTimeout;
command.Connection = sqlConnection;
command.Transaction = sqlTransaction;
this.LogTaskMessage(MessageImportance.Low, "Executing Batch {0}", new object[] { batchNum++ });
this.LogTaskMessage(MessageImportance.Low, sqlCommandText);
command.ExecuteNonQuery();
}
}
if (sqlTransaction != null)
{
sqlTransaction.Commit();
}
}
catch
{
if (sqlTransaction != null)
{
sqlTransaction.Rollback();
}
throw;
}
this.OnScriptFileExecuted(new ExecuteEventArgs(new FileInfo(fileInfo.ItemSpec)));
}
catch (SqlException ex)
{
fileInfo.SetMetadata("ErrorMessage", ex.Message);
failedScripts.Add(fileInfo);
lastException = new ApplicationException(string.Format(CultureInfo.CurrentUICulture, "{0}. {1}", fileInfo.ItemSpec, ex.Message), ex);
if (!this.Retry && !this.IgnoreScriptErrors)
{
throw lastException;
}
failures[errorNo] = fileInfo;
errorNo++;
this.OnScriptFileExecuted(new ExecuteEventArgs(new FileInfo(fileInfo.ItemSpec), ex));
}
}
if (!this.Retry)
{
retry = false;
}
else
{
if (errorNo > 0)
{
this.Files = new ITaskItem[errorNo];
for (int i = 0; i < errorNo; i++)
{
this.Files[i] = failures[i];
}
if (this.Files.Length >= previousFailures && !this.IgnoreScriptErrors)
{
throw lastException;
}
previousFailures = this.Files.Length;
}
else
{
retry = false;
}
}
this.FailedScripts = failedScripts.ToArray();
}
}
}
private void ExecuteText()
{
using (SqlConnection sqlConnection = this.CreateConnection(this.ConnectionString))
using (SqlCommand command = new SqlCommand(this.SubstituteParameters(this.Sql), sqlConnection))
{
command.CommandTimeout = this.CommandTimeout;
this.LogTaskMessage(MessageImportance.High, string.Format(CultureInfo.CurrentCulture, "Execute: {0}", command.CommandText));
sqlConnection.Open();
SqlTransaction sqlTransaction = null;
try
{
if (this.UseTransaction)
{
sqlTransaction = sqlConnection.BeginTransaction();
command.Transaction = sqlTransaction;
}
switch (this.TaskAction)
{
case ExecuteTaskAction:
command.ExecuteNonQuery();
break;
case ExecuteScalarTaskAction:
var result = command.ExecuteScalar();
this.ScalarResult = result.ToString();
break;
case ExecuteReaderTaskAction:
ArrayList rows = new ArrayList();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
ITaskItem rowItem = new TaskItem(reader[0].ToString());
for (int i = 0; i < reader.FieldCount; i++)
{
rowItem.SetMetadata(reader.GetName(i), reader[i].ToString());
}
rows.Add(rowItem);
}
}
this.ReaderResult = new ITaskItem[rows.Count];
for (int i = 0; i < rows.Count; i++)
{
this.ReaderResult[i] = (ITaskItem)rows[i];
}
break;
case ExecuteRawReaderTaskAction:
using (SqlDataReader rawreader = command.ExecuteReader())
{
this.RawReaderResult = string.Empty;
while (rawreader.Read())
{
string resultRow = string.Empty;
for (int i = 0; i < rawreader.FieldCount; i++)
{
resultRow += rawreader[i] + " ";
}
this.RawReaderResult += resultRow + Environment.NewLine;
}
}
break;
}
if (sqlTransaction != null)
{
sqlTransaction.Commit();
}
TimeSpan s = DateTime.Now - this.timer;
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Execution Time: {0} seconds", s.TotalSeconds));
this.timer = DateTime.Now;
}
catch
{
if (sqlTransaction != null)
{
sqlTransaction.Rollback();
}
throw;
}
}
}
private SqlConnection CreateConnection(string connectionString)
{
SqlConnection returnedConnection;
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
connection.InfoMessage += this.TraceMessageEventHandler;
returnedConnection = connection;
connection = null;
}
finally
{
if (connection != null)
{
connection.Close();
}
}
return returnedConnection;
}
private void TraceMessageEventHandler(object sender, SqlInfoMessageEventArgs e)
{
if (this.ScriptFileExecuted != null)
{
ExecuteEventArgs args = new ExecuteEventArgs(e.Errors);
this.ScriptFileExecuted(null, args);
}
}
private void OnScriptFileExecuted(ExecuteEventArgs scriptFileExecuted)
{
if (scriptFileExecuted != null && this.ScriptFileExecuted != null)
{
this.ScriptFileExecuted(null, scriptFileExecuted);
}
}
private void ScriptExecuted(object sender, ExecuteEventArgs scriptInfo)
{
if (scriptInfo.ScriptFileInfo != null)
{
if (scriptInfo.Succeeded)
{
TimeSpan s = DateTime.Now - this.timer;
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Successfully executed: {0} ({1} seconds)", scriptInfo.ScriptFileInfo.Name, s.TotalSeconds));
this.timer = DateTime.Now;
}
else
{
TimeSpan s = DateTime.Now - this.timer;
this.LogTaskWarning(string.Format(CultureInfo.CurrentCulture, "Failed to executed: {0}. {1} ({2} seconds)", scriptInfo.ScriptFileInfo.Name, scriptInfo.ExecutionException.Message, s.TotalSeconds));
this.timer = DateTime.Now;
}
}
else
{
if (scriptInfo.SqlInfo != null)
{
foreach (SqlError infoMessage in scriptInfo.SqlInfo)
{
this.LogTaskMessage(" - " + infoMessage.Message);
}
}
}
}
}
}
| |
// 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.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestParameterGroupingTestService : Microsoft.Rest.ServiceClient<AutoRestParameterGroupingTestService>, IAutoRestParameterGroupingTestService, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.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 System.Net.Http.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(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.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="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestParameterGroupingTestService(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the 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(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestParameterGroupingTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestParameterGroupingTestService(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.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. Credentials needed for the client to connect to Azure.
/// </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="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestParameterGroupingTestService(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.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. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestParameterGroupingTestService(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.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. Credentials needed for the client to connect to Azure.
/// </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(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.ParameterGrouping = new ParameterGroupingOperations(this);
this.BaseUri = new System.Uri("https://localhost");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace DeveloperHomePageApi.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// 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 System;
using System.Collections;
using System.Threading.Tasks;
using UnityEngine;
using NUnit.Framework;
using UnityEngine.TestTools;
using static TiltBrush.AsyncTestUtils;
namespace TiltBrush {
internal class TestMisc {
[Test]
public void TestStreamlineStackTrace() {
string input = "UnityEngine.Debug:Assert(Boolean, String)\r\nTiltBrush.SketchMemoryScript:SanityCheckGeometryGeneration(MemoryBrushStroke) (at Assets/Scripts/SketchMemoryScript.cs:709)";
string output = ExceptionRenderScript.StreamlineStackTrace(input);
Assert.AreEqual(output, "Debug.Assert \r\nSketchMemoryScript.SanityCheckGeometryGeneration 709");
}
// Embedded
[TestCase(.1f,.1f,.1f, 3,.1f,.1f, 1, 0, 0)]
// Face tests
[TestCase( 4, 1, 1, 3, 1, 1, 1, 0, 0)] // +x face
[TestCase(-4, 1, 1, -3, 1, 1, -1, 0, 0)] // -x face
[TestCase( 1, 8, 2, 1, 4, 2, 0, 1, 0)] // +y face
[TestCase( 1, -8, 2, 1, -4, 2, 0, -1, 0)] // -y face
[TestCase(-1, -2, 8, -1, -2, 5, 0, 0, 1)] // +z face
[TestCase(-1, -2, -8, -1, -2, -5, 0, 0, -1)] // -z face
// Edge tests
[TestCase( 8, 8, 2, 3, 4, 2, 0,0,0)] // +x+y edge
[TestCase(-8, 8, 2, -3, 4, 2, 0,0,0)] // -x+y edge
// Vert tests
[TestCase( 8, -8, -8, 3, -4, -5, 0,0,0)] // +x-y-z vert
public void TestClosestPointOnBox(
float px, float py, float pz,
float spx, float spy, float spz,
float nx, float ny, float nz) {
var pos = new Vector3(px, py, pz);
var halfWidth = new Vector3(3, 4, 5);
var expectedSurfacePos = new Vector3(spx, spy, spz);
var expectedSurfaceNorm = new Vector3(nx, ny, nz);
Vector3 surfacePos, surfaceNorm;
CubeStencil.FindClosestPointOnBoxSurface(pos, halfWidth,
out surfacePos, out surfaceNorm);
MathTestUtils.AssertAlmostEqual(expectedSurfacePos, surfacePos);
if (expectedSurfaceNorm != Vector3.zero) {
MathTestUtils.AssertAlmostEqual(expectedSurfaceNorm, surfaceNorm);
} else {
// Test case wants us to calculate it from scratch
Vector3 diff = pos - expectedSurfacePos;
if (diff != Vector3.zero) {
MathTestUtils.AssertAlmostEqual(diff.normalized, surfaceNorm);
}
}
}
[Test]
public void TestClosestPointOnBoxEdgeCases() {
var halfWidth = new Vector3(3, 4, 5);
// Try all permutations of points directly on verts, faces, edges
for (int xsign=-1; xsign<=1; ++xsign)
for (int ysign=-1; ysign<=1; ++ysign)
for (int zsign=-1; zsign<=1; ++zsign) {
int numFaces = Mathf.Abs(xsign) + Mathf.Abs(ysign) + Mathf.Abs(zsign);
// Only care about running tests where the point is on 2 or 3 faces (ie edge, or vert)
if (numFaces <= 1) { continue; }
var pos = new Vector3(xsign * halfWidth.x,
ysign * halfWidth.y,
zsign * halfWidth.z);
Vector3 surfacePos, surfaceNorm;
CubeStencil.FindClosestPointOnBoxSurface(pos, halfWidth,
out surfacePos, out surfaceNorm);
MathTestUtils.AssertAlmostEqual(pos, surfacePos);
MathTestUtils.AssertAlmostEqual(1, surfaceNorm.magnitude);
for (int axis=0; axis<3; ++axis) {
float p = pos[axis];
float h = halfWidth[axis];
float n = surfaceNorm[axis];
// The normal is not well defined, but it should at least point away from the box
if (p == h) {
Assert.GreaterOrEqual(n, 0, "Axis {0}", axis);
} else if (p == -h) {
Assert.LessOrEqual(n, 0, "Axis {0}", axis);
} else if (-h < p & p < h) {
// Should have no component parallel to the edge we're on
Assert.AreEqual(n, 0, "Axis {0}", axis);
} else {
Assert.Fail("Bad test");
}
}
}
}
[Test]
public static void TestUuid3() {
// Test values computed using python uuid.uuid3
Assert.AreEqual(GuidUtils.Uuid3(Guid.Empty, "fancy"),
new Guid("e033f80d-b580-3145-8f4b-3d90f8c0da30"));
Assert.AreEqual(GuidUtils.Uuid3(GuidUtils.kNamespaceDns, "fancy"),
new Guid("5d5c7347-4e4b-3a86-a58e-3615d4aa6b2e"));
}
[Test]
public static void TestUuid5() {
// Test values computed using python uuid.uuid5
Assert.AreEqual(GuidUtils.Uuid5(Guid.Empty, "fancy"),
new Guid("f8893632-dedc-566d-83f1-afda8c3bbd31"));
Assert.AreEqual(GuidUtils.Uuid5(GuidUtils.kNamespaceDns, "fancy"),
new Guid("750c4490-5470-5f19-a5e9-98c1ce534c7e"));
}
static void TestUnityGuidHelper(string rfcGuid_, string unityGuid) {
Guid rfcGuid = new Guid(rfcGuid_);
Assert.AreEqual(unityGuid, GuidUtils.SerializeToUnity(rfcGuid));
Assert.AreEqual(rfcGuid, GuidUtils.DeserializeFromUnity(unityGuid));
}
[Test]
public static void TestUnityGuidSerialization() {
TestUnityGuidHelper("3b63530f-b85e-4dca-b52a-e7926a3a97a3", "f03536b3e58bacd45ba27e29a6a3793a");
TestUnityGuidHelper("71581662-6a39-214c-9576-ee104ce08228", "2661851793a6c4125967ee01c40e2882");
TestUnityGuidHelper("e46f7048-3b57-4e5e-a34b-b633730b2796", "8407f64e75b3e5e43ab46b3337b07269");
}
static void RfcTestHelper(string input, string expectedAsciiOutput) {
Assert.AreEqual(expectedAsciiOutput, TextUtils.Rfc5987Encode(input));
}
[Test]
public void TestRfc5987Encode() {
// all of the attr-char characters (plus space)
RfcTestHelper("abcdefghijkl mnopqrstuvwxyz", "UTF-8''abcdefghijkl%20mnopqrstuvwxyz");
RfcTestHelper("ABCDEFGHIJKL MNOPQRSTUVWXYZ", "UTF-8''ABCDEFGHIJKL%20MNOPQRSTUVWXYZ");
RfcTestHelper("0123456789", "UTF-8''0123456789");
RfcTestHelper("!#$&+-.^_`|~", "UTF-8''!#$&+-.^_`|~");
// ascii and displayable but not in attr-char
RfcTestHelper(" \"%'()*,/:;<=>?@[\\]{}", "UTF-8''%20%22%25%27%28%29%2a%2c%2f%3a%3b%3c%3d%3e%3f%40%5b%5c%5d%7b%7d");
// some control characters
RfcTestHelper("\x00\x01\x02\x03\x04\x05\r\n\t", "UTF-8''%00%01%02%03%04%05%0d%0a%09");
// some 2-, 3-, and 4-byte utf-8 sequences
RfcTestHelper("_\u00fc-", "UTF-8''_%c3%bc-");
RfcTestHelper("_\u20ac-", "UTF-8''_%e2%82%ac-");
RfcTestHelper("_\U0001d306-", "UTF-8''_%f0%9d%8c%86-");
}
// Tests that SetImageUrlOptions works whether or not there is an options section
// in the input URL.
[Test]
public void TestSetImageUrlOptions() {
// Just a quick test that SetImageUrl
Assert.AreEqual(
OAuth2Identity.SetImageUrlOptions(
"https://lh3.googleusercontent.com/a-/AN66SAy7y9N4Do-folxEcPjtglaoHtam6THlfn8wk8aF=s100"),
"https://lh3.googleusercontent.com/a-/AN66SAy7y9N4Do-folxEcPjtglaoHtam6THlfn8wk8aF=s128-c-k-no-rj");
Assert.AreEqual(
OAuth2Identity.SetImageUrlOptions(
"https://lh3.googleusercontent.com/a-/AN66SAy7y9N4Do-folxEcPjtglaoHtam6THlfn8wk8aF"),
"https://lh3.googleusercontent.com/a-/AN66SAy7y9N4Do-folxEcPjtglaoHtam6THlfn8wk8aF=s128-c-k-no-rj");
}
[UnityTest]
public IEnumerator TestAsUnityTestStartsOnUnityThread() => AsUnityTest(async () => {
Assert.AreEqual(
System.Threading.SynchronizationContext.Current,
UnityAsyncAwaitUtil.SyncContextUtil.UnitySynchronizationContext);
await new WaitForBackgroundThread();
Assert.AreNotEqual(
System.Threading.SynchronizationContext.Current,
UnityAsyncAwaitUtil.SyncContextUtil.UnitySynchronizationContext);
});
// A test that our integration of AsyncAwaitUtil and com.unity.editorcoroutines works.
// Also serves as an example of how to test async code, because the Unity version of NUnit
// doesn't have direct support for async test methods.
[UnityTest]
public IEnumerator TestAsyncAwaitUtilWorksAtEditTime() => AsUnityTest(async () => {
const int kNumFrames = 3;
float dt = 0;
// This should put us on the Unity thread...
await Awaiters.NextFrame;
for (int i = 0; i < kNumFrames; ++i) {
dt -= Time.realtimeSinceStartup; // ...and this will throw if we're not.
await Awaiters.NextFrame;
dt += Time.realtimeSinceStartup;
}
Assert.Less(dt / kNumFrames, 2f);
});
[UnityTest]
public IEnumerator TestImageUtils_DownloadTextureAsync() => AsUnityTest(async () => {
const string kUrl = "https://lh3.googleusercontent.com/a-/AN66SAy7y9N4Do-folxEcPjtglaoHtam6THlfn8wk8aF=s100";
//await Awaiters.NextFrame; // DownloadTextureAsync is a main-thread-only API
Texture2D tex = await ImageUtils.DownloadTextureAsync(kUrl);
Assert.AreEqual(100, tex.width);
Assert.AreEqual(100, tex.height);
});
}
}
| |
using System;
using UnityEngine.Serialization;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
[Flags]
public enum CameraSettingsFields
{
none = 0,
bufferClearColorMode = 1 << 1,
bufferClearBackgroundColorHDR = 1 << 2,
bufferClearClearDepth = 1 << 3,
volumesLayerMask = 1 << 4,
volumesAnchorOverride = 1 << 5,
frustumMode = 1 << 6,
frustumAspect = 1 << 7,
frustumFarClipPlane = 1 << 8,
frustumNearClipPlane = 1 << 9,
frustumFieldOfView = 1 << 10,
frustumProjectionMatrix = 1 << 11,
cullingUseOcclusionCulling = 1 << 12,
cullingCullingMask = 1 << 13,
cullingInvertFaceCulling = 1 << 14,
customRenderingSettings = 1 << 15,
flipYMode = 1 << 16,
frameSettings = 1 << 17,
probeLayerMask = 1 << 18
}
[Serializable]
public struct CameraSettingsOverride
{
public CameraSettingsFields camera;
}
/// <summary>Contains all settings required to setup a camera in HDRP.</summary>
[Serializable]
public struct CameraSettings
{
/// <summary>Defines how color and depth buffers are cleared.</summary>
[Serializable]
public struct BufferClearing
{
/// <summary>Default value.</summary>
public static readonly BufferClearing @default = new BufferClearing
{
clearColorMode = HDAdditionalCameraData.ClearColorMode.Sky,
backgroundColorHDR = new Color32(6, 18, 48, 0),
clearDepth = true
};
/// <summary>Define the source for the clear color.</summary>
public HDAdditionalCameraData.ClearColorMode clearColorMode;
/// <summary>
/// The color to use when
/// <c><see cref="clearColorMode"/> == <see cref="HDAdditionalCameraData.ClearColorMode.Color"/></c>.
/// </summary>
[ColorUsage(true, true)]
public Color backgroundColorHDR;
/// <summary>True to clear the depth.</summary>
public bool clearDepth;
}
/// <summary>Defines how the volume framework is queried.</summary>
[Serializable]
public struct Volumes
{
/// <summary>Default value.</summary>
public static readonly Volumes @default = new Volumes
{
layerMask = -1,
anchorOverride = null
};
/// <summary>The <see cref="LayerMask"/> to use for the volumes.</summary>
public LayerMask layerMask;
/// <summary>If not null, define the location of the evaluation of the volume framework.</summary>
public Transform anchorOverride;
}
/// <summary>Defines the projection matrix of the camera.</summary>
[Serializable]
public struct Frustum
{
/// <summary>Default value.</summary>
public static readonly Frustum @default = new Frustum
{
mode = Mode.ComputeProjectionMatrix,
aspect = 1.0f,
farClipPlane = 1000.0f,
nearClipPlane = 0.1f,
fieldOfView = 90.0f,
projectionMatrix = Matrix4x4.identity
};
/// <summary>Defines how the projection matrix is computed.</summary>
public enum Mode
{
/// <summary>
/// For perspective projection, the matrix is computed from <see cref="aspect"/>,
/// <see cref="farClipPlane"/>, <see cref="nearClipPlane"/> and <see cref="fieldOfView"/> parameters.
///
/// Orthographic projection is not currently supported.
/// </summary>
ComputeProjectionMatrix,
/// <summary>The projection matrix provided is assigned.</summary>
UseProjectionMatrixField
}
/// <summary>Which mode will be used for the projection matrix.</summary>
public Mode mode;
/// <summary>Aspect ratio of the frustum (width/height).</summary>
public float aspect;
/// <summary>Far clip plane distance.</summary>
public float farClipPlane;
/// <summary>Near clip plane distance.</summary>
public float nearClipPlane;
/// <summary>Field of view for perspective matrix (for y axis, in degree).</summary>
[Range(1, 179.0f)]
public float fieldOfView;
/// <summary>Projection matrix used for <see cref="Mode.UseProjectionMatrixField"/> mode.</summary>
public Matrix4x4 projectionMatrix;
/// <summary>Compute the projection matrix based on the mode and settings provided.</summary>
/// <returns>The projection matrix.</returns>
public Matrix4x4 ComputeProjectionMatrix()
{
return Matrix4x4.Perspective(fieldOfView, aspect, nearClipPlane, farClipPlane);
}
public Matrix4x4 GetUsedProjectionMatrix()
{
switch (mode)
{
case Mode.ComputeProjectionMatrix: return ComputeProjectionMatrix();
case Mode.UseProjectionMatrixField: return projectionMatrix;
default: throw new ArgumentException();
}
}
}
/// <summary>Defines the culling settings of the camera.</summary>
[Serializable]
public struct Culling
{
/// <summary>Default value.</summary>
public static readonly Culling @default = new Culling
{
cullingMask = -1,
useOcclusionCulling = true
};
/// <summary>True when occlusion culling will be performed during rendering, false otherwise.</summary>
public bool useOcclusionCulling;
/// <summary>The mask for visible objects.</summary>
public LayerMask cullingMask;
}
/// <summary>Default value.</summary>
public static readonly CameraSettings @default = new CameraSettings
{
bufferClearing = BufferClearing.@default,
culling = Culling.@default,
renderingPathCustomFrameSettings = FrameSettings.defaultCamera,
frustum = Frustum.@default,
customRenderingSettings = false,
volumes = Volumes.@default,
flipYMode = HDAdditionalCameraData.FlipYMode.Automatic,
invertFaceCulling = false,
probeLayerMask = ~0
};
public static CameraSettings From(HDCamera hdCamera)
{
var settings = @default;
settings.culling.cullingMask = hdCamera.camera.cullingMask;
settings.culling.useOcclusionCulling = hdCamera.camera.useOcclusionCulling;
settings.frustum.aspect = hdCamera.camera.aspect;
settings.frustum.farClipPlane = hdCamera.camera.farClipPlane;
settings.frustum.nearClipPlane = hdCamera.camera.nearClipPlane;
settings.frustum.fieldOfView = hdCamera.camera.fieldOfView;
settings.frustum.mode = Frustum.Mode.UseProjectionMatrixField;
settings.frustum.projectionMatrix = hdCamera.camera.projectionMatrix;
settings.invertFaceCulling = false;
var add = hdCamera.camera.GetComponent<HDAdditionalCameraData>();
if (add != null && !add.Equals(null))
{
settings.customRenderingSettings = add.customRenderingSettings;
settings.bufferClearing.backgroundColorHDR = add.backgroundColorHDR;
settings.bufferClearing.clearColorMode = add.clearColorMode;
settings.bufferClearing.clearDepth = add.clearDepth;
settings.flipYMode = add.flipYMode;
settings.renderingPathCustomFrameSettings = add.renderingPathCustomFrameSettings;
settings.renderingPathCustomFrameSettingsOverrideMask = add.renderingPathCustomFrameSettingsOverrideMask;
settings.volumes = new Volumes
{
anchorOverride = add.volumeAnchorOverride,
layerMask = add.volumeLayerMask
};
settings.probeLayerMask = add.probeLayerMask;
settings.invertFaceCulling = add.invertFaceCulling;
}
// (case 1131731) Camera.RenderToCubemap inverts faces
// Unity's API is using LHS standard when rendering cubemaps, so we need to invert the face culling
// in that specific case.
// We try to guess with a lot of constraints when this is the case.
var isLHSViewMatrix = hdCamera.camera.worldToCameraMatrix.determinant > 0;
var isPerspectiveMatrix = Mathf.Approximately(hdCamera.camera.projectionMatrix.m32, -1);
var isFOV45Degrees = Mathf.Approximately(hdCamera.camera.projectionMatrix.m00, 1)
&& Mathf.Approximately(hdCamera.camera.projectionMatrix.m11, 1);
var useATempBuffer = hdCamera.camera.activeTexture != null
&& !hdCamera.camera.activeTexture.Equals(null)
&& hdCamera.camera.activeTexture.name.StartsWith("TempBuffer");
if (isLHSViewMatrix && isPerspectiveMatrix && isFOV45Degrees && useATempBuffer)
settings.invertFaceCulling = true;
return settings;
}
/// <summary>Override rendering settings if true.</summary>
public bool customRenderingSettings;
/// <summary>Frame settings to use.</summary>
public FrameSettings renderingPathCustomFrameSettings;
/// <summary>Frame settings mask to use.</summary>
public FrameSettingsOverrideMask renderingPathCustomFrameSettingsOverrideMask;
/// <summary>Buffer clearing settings to use.</summary>
public BufferClearing bufferClearing;
/// <summary>Volumes settings to use.</summary>
public Volumes volumes;
/// <summary>Frustum settings to use.</summary>
public Frustum frustum;
/// <summary>Culling settings to use.</summary>
public Culling culling;
/// <summary>True to invert face culling, false otherwise.</summary>
public bool invertFaceCulling;
/// <summary>The mode to use when we want to flip the Y axis.</summary>
public HDAdditionalCameraData.FlipYMode flipYMode;
/// <summary>The layer mask to use to filter probes that can influence this camera.</summary>
public LayerMask probeLayerMask;
/// <summary>Which default FrameSettings should be used when rendering with these parameters.</summary>
public FrameSettingsRenderType defaultFrameSettings;
[SerializeField, FormerlySerializedAs("renderingPath"), Obsolete("For data migration")]
internal int m_ObsoleteRenderingPath;
#pragma warning disable 618 // Type or member is obsolete
[SerializeField, FormerlySerializedAs("frameSettings"), Obsolete("For data migration")]
internal ObsoleteFrameSettings m_ObsoleteFrameSettings;
#pragma warning restore 618
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Free.Controls.OpenStreetMap
{
class TileManager
{
string cacheDirectory=Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)+"\\Free Framework\\OpenStreetMap\\Cache";
TimeSpan refreshTimeSpan=new TimeSpan(7, 0, 1, 0);
BitmapPooledLoader pooledLoader;
Bitmap errorImage;
public Control HostMapPanel { get; set; }
public string DataProvider { get; set; }
public int TilePoolSize
{
get { return (int)pooledLoader.MaxImages; }
set { pooledLoader.MaxImages=(uint)Math.Abs(value); }
}
public string FilenameExtension { get; set; }
public int DaysBeforeRefresh
{
get { return refreshTimeSpan.Days; }
set { refreshTimeSpan=new TimeSpan(Math.Abs(value), 0, 1, 0); }
}
public TileManager(Control mapPanel, string dataProvider): this(mapPanel, dataProvider, 7, 1000, ".png") { }
public TileManager(Control mapPanel, string dataProvider, int daysBeforeRefresh, uint tilePoolSize, string filenameextension)
{
errorImage=new Bitmap(GetType(), "raster.png");
if(!Directory.Exists(cacheDirectory))
{
char[] sep=new char[] { '/', '\\' };
string[] pathParts=cacheDirectory.Split(sep, StringSplitOptions.RemoveEmptyEntries);
string path="";
foreach(string i in pathParts)
{
path+=i+"\\";
if(path.Length<=3) continue; // root (C:\)
if(!Directory.Exists(path))
{
try { Directory.CreateDirectory(path); }
catch { }
}
}
}
string[] tmps=GetFiles(cacheDirectory, "*.tmp");
foreach(string i in tmps)
{
try
{
File.Delete(i);
}
catch
{
}
}
HostMapPanel=mapPanel;
DataProvider=dataProvider;
refreshTimeSpan=new TimeSpan(daysBeforeRefresh, 0, 1, 0);
pooledLoader=new BitmapPooledLoader(tilePoolSize);
FilenameExtension=filenameextension;
}
public void ClearCache()
{
string[] tmps=GetFiles(cacheDirectory, FilenameExtension);
foreach(string i in tmps) File.Delete(i);
}
public void DownloadCache(int maxlevel)
{
for(int i=0; i<maxlevel; i++)
{
int maxTilesDimension=1<<i;
for(int x=0; x<maxTilesDimension; x++)
{
for(int y=0; y<maxTilesDimension; y++)
{
string fn=GetTileFilename(i, x, y);
if(File.Exists(fn))
{
// determine file age
if(DateTime.Now-refreshTimeSpan>new FileInfo(fn).LastWriteTime)
{
// check if file already in queue
if(!File.Exists(fn+".tmp")) DownloadTileAsync(i, x, y); // refresh
}
continue;
}
if(!File.Exists(fn+".tmp")) DownloadTileAsync(i, x, y);
}
}
}
}
public Bitmap GetTile(int zoom, int x, int y)
{
if(x<0||x>=Math.Pow(2, zoom)||y<0||y>=Math.Pow(2, zoom)) return errorImage;
string fn=GetTileFilename(zoom, x, y);
if(File.Exists(fn))
{
// determine file age
if(DateTime.Now-refreshTimeSpan>new FileInfo(fn).LastWriteTime)
{
// check if file already in queue
if(!File.Exists(fn+".tmp"))
{
DownloadTileAsync(zoom, x, y); // refresh
}
}
return pooledLoader.FromFile(fn)??errorImage;
}
if(!File.Exists(fn+".tmp")) DownloadTileAsync(zoom, x, y);
if(zoom==0) return errorImage;
Bitmap zoomOut=GetTile(zoom-1, x/2, y/2);
Bitmap ret=new Bitmap(zoomOut.Width, zoomOut.Height);
Graphics g=null;
try
{
g=Graphics.FromImage(ret);
g.Clear(Color.Transparent);
int posx=-(x%2)*zoomOut.Width;
int posy=-(y%2)*zoomOut.Height;
g.DrawImage(zoomOut, posx, posy, zoomOut.Width*2+1, zoomOut.Height*2+1);
}
finally
{
if(g!=null) g.Dispose();
}
return ret;
}
void ClientDownloadFileAsyncHandler(object sender, AsyncCompletedEventArgs e)
{
string filename=e.UserState as string;
if(filename==null) return;
if(e.Error!=null)
{
try { File.Delete(filename); }
catch { }
return;
}
string newfilename=GetPathFilenameWithoutExt(filename);
if(File.Exists(newfilename))
{
try { File.Delete(newfilename); }
catch { }
return;
}
try { File.Move(filename, newfilename); }
catch { }
if(HostMapPanel!=null) HostMapPanel.Invalidate();
}
public void DownloadTileAsync(int zoom, int x, int y)
{
var t=Task.Factory.StartNew(() => DownloadTile(zoom, x, y));
}
void DownloadTile(int zoom, int x, int y)
{
if(x<0||x>=Math.Pow(2, zoom)||y<0||y>=Math.Pow(2, zoom)) return;
try
{
WebClient client=new WebClient();
client.DownloadFileCompleted+=new System.ComponentModel.AsyncCompletedEventHandler(ClientDownloadFileAsyncHandler);
string fn=GetTileFilename(zoom, x, y)+".tmp";
client.DownloadFileAsync(new Uri(DataProvider+zoom+"/"+x+"/"+y+FilenameExtension), fn, fn);
}
catch
{
}
}
string GetTileFilename(int zoom, int x, int y)
{
return cacheDirectory+"\\"+zoom+"_"+x+"_"+y+FilenameExtension;
}
static string GetPathFilenameWithoutExt(string filename)
{
FileInfo ret=new FileInfo(filename);
if(ret.DirectoryName.Length==3) return ret.DirectoryName+ret.Name.Substring(0, ret.Name.Length-ret.Extension.Length);
return ret.DirectoryName+'\\'+ret.Name.Substring(0, ret.Name.Length-ret.Extension.Length);
}
public static string[] GetFiles(string directory, string filter)
{
if(!Directory.Exists(directory)) return new string[0];
try
{
return Directory.GetFiles(directory, filter);
}
catch
{
return new string[0];
}
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Rest.Generator.Azure.NodeJS.Properties;
using Microsoft.Rest.Generator.Azure.NodeJS.Templates;
using Microsoft.Rest.Generator.ClientModel;
using Microsoft.Rest.Generator.NodeJS;
using Microsoft.Rest.Generator.NodeJS.Templates;
using Microsoft.Rest.Generator.Utilities;
using System.Collections.Generic;
namespace Microsoft.Rest.Generator.Azure.NodeJS
{
public class AzureNodeJSCodeGenerator : NodeJSCodeGenerator
{
private const string ClientRuntimePackage = "ms-rest-azure version 1.12.0";
// List of models with paging extensions.
private IList<PageTemplateModel> pageModels;
public AzureNodeJSCodeGenerator(Settings settings)
: base(settings)
{
pageModels = new List<PageTemplateModel>();
}
public override string Name
{
get { return "Azure.NodeJS"; }
}
public override string Description
{
// TODO resource string.
get { return "Azure specific NodeJS code generator."; }
}
public override string UsageInstructions
{
get
{
return string.Format(CultureInfo.InvariantCulture,
Resources.UsageInformation, ClientRuntimePackage);
}
}
public override string ImplementationFileExtension
{
get { return ".js"; }
}
/// <summary>
/// Normalizes client model by updating names and types to be language specific.
/// </summary>
/// <param name="serviceClient"></param>
public override void NormalizeClientModel(ServiceClient serviceClient)
{
// MethodNames are normalized explicitly to provide a consitent method name while
// generating cloned methods for long running operations with reserved words. For
// example - beginDeleteMethod() insteadof beginDelete() as delete is a reserved word.
Namer.NormalizeMethodNames(serviceClient);
AzureExtensions.NormalizeAzureClientModel(serviceClient, Settings, Namer);
base.NormalizeClientModel(serviceClient);
NormalizeApiVersion(serviceClient);
NormalizePaginatedMethods(serviceClient);
ExtendAllResourcesToBaseResource(serviceClient);
}
private static void ExtendAllResourcesToBaseResource(ServiceClient serviceClient)
{
if (serviceClient != null)
{
foreach (var model in serviceClient.ModelTypes)
{
if (model.Extensions.ContainsKey(AzureExtensions.AzureResourceExtension) &&
(bool)model.Extensions[AzureExtensions.AzureResourceExtension])
{
model.BaseModelType = new CompositeType { Name = "BaseResource", SerializedName = "BaseResource" };
}
}
}
}
private static void NormalizeApiVersion(ServiceClient serviceClient)
{
serviceClient.Properties.Where(
p => p.SerializedName.Equals(AzureExtensions.ApiVersion, StringComparison.OrdinalIgnoreCase))
.ForEach(p => p.DefaultValue = p.DefaultValue.Replace("\"", "'"));
serviceClient.Properties.Where(
p => p.SerializedName.Equals(AzureExtensions.AcceptLanguage, StringComparison.OrdinalIgnoreCase))
.ForEach(p => p.DefaultValue = p.DefaultValue.Replace("\"", "'"));
}
/// <summary>
/// Changes paginated method signatures to return Page type.
/// </summary>
/// <param name="serviceClient"></param>
public virtual void NormalizePaginatedMethods(ServiceClient serviceClient)
{
if (serviceClient == null)
{
throw new ArgumentNullException("serviceClient");
}
foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension)))
{
string nextLinkName = null;
var ext = method.Extensions[AzureExtensions.PageableExtension] as Newtonsoft.Json.Linq.JContainer;
if (ext == null)
{
continue;
}
nextLinkName = (string)ext["nextLinkName"];
string itemName = (string)ext["itemName"] ?? "value";
foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeType).Select(s => s.Key).ToArray())
{
var compositType = (CompositeType)method.Responses[responseStatus].Body;
var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceType) as SequenceType;
// if the type is a wrapper over page-able response
if (sequenceType != null)
{
compositType.Extensions[AzureExtensions.PageableExtension] = true;
var pageTemplateModel = new PageTemplateModel(compositType, serviceClient, nextLinkName, itemName);
if (!pageModels.Contains(pageTemplateModel))
{
pageModels.Add(pageTemplateModel);
}
}
}
}
}
/// <summary>
/// Generate Azure NodeJS client code for given ServiceClient.
/// </summary>
/// <param name="serviceClient"></param>
/// <returns></returns>
public override async Task Generate(ServiceClient serviceClient)
{
var serviceClientTemplateModel = new AzureServiceClientTemplateModel(serviceClient);
// Service client
var serviceClientTemplate = new Microsoft.Rest.Generator.Azure.NodeJS.Templates.AzureServiceClientTemplate
{
Model = serviceClientTemplateModel
};
await Write(serviceClientTemplate, serviceClient.Name.ToCamelCase() + ".js");
if (!DisableTypeScriptGeneration)
{
var serviceClientTemplateTS = new AzureServiceClientTemplateTS
{
Model = serviceClientTemplateModel,
};
await Write(serviceClientTemplateTS, serviceClient.Name.ToCamelCase() + ".d.ts");
}
//Models
if (serviceClient.ModelTypes.Any())
{
// Paged Models
foreach (var pageModel in pageModels)
{
//Add the PageTemplateModel to AzureServiceClientTemplateModel
if (!serviceClientTemplateModel.PageTemplateModels.Contains(pageModel))
{
serviceClientTemplateModel.PageTemplateModels.Add(pageModel);
}
var pageTemplate = new PageModelTemplate
{
Model = pageModel
};
await Write(pageTemplate, Path.Combine("models", pageModel.Name.ToCamelCase() + ".js"));
}
var modelIndexTemplate = new AzureModelIndexTemplate
{
Model = serviceClientTemplateModel
};
await Write(modelIndexTemplate, Path.Combine("models", "index.js"));
if (!DisableTypeScriptGeneration)
{
var modelIndexTemplateTS = new AzureModelIndexTemplateTS
{
Model = serviceClientTemplateModel
};
await Write(modelIndexTemplateTS, Path.Combine("models", "index.d.ts"));
}
foreach (var modelType in serviceClientTemplateModel.ModelTemplateModels)
{
var modelTemplate = new ModelTemplate
{
Model = modelType
};
await Write(modelTemplate, Path.Combine("models", modelType.Name.ToCamelCase() + ".js"));
}
}
//MethodGroups
if (serviceClientTemplateModel.MethodGroupModels.Any())
{
var methodGroupIndexTemplate = new MethodGroupIndexTemplate
{
Model = serviceClientTemplateModel
};
await Write(methodGroupIndexTemplate, Path.Combine("operations", "index.js"));
if (!DisableTypeScriptGeneration)
{
var methodGroupIndexTemplateTS = new MethodGroupIndexTemplateTS
{
Model = serviceClientTemplateModel
};
await Write(methodGroupIndexTemplateTS, Path.Combine("operations", "index.d.ts"));
}
foreach (var methodGroupModel in serviceClientTemplateModel.MethodGroupModels)
{
var methodGroupTemplate = new AzureMethodGroupTemplate
{
Model = methodGroupModel as AzureMethodGroupTemplateModel
};
await Write(methodGroupTemplate, Path.Combine("operations", methodGroupModel.MethodGroupType.ToCamelCase() + ".js"));
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Security;
using Microsoft.Build.Framework;
namespace GodotSharpTools.Build
{
public class BuildInstance : IDisposable
{
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static void godot_icall_BuildInstance_ExitCallback(string solution, string config, int exitCode);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static string godot_icall_BuildInstance_get_MSBuildPath();
private static string MSBuildPath
{
get { return godot_icall_BuildInstance_get_MSBuildPath(); }
}
private string solution;
private string config;
private Process process;
private int exitCode;
public int ExitCode { get { return exitCode; } }
public bool IsRunning { get { return process != null && !process.HasExited; } }
public BuildInstance(string solution, string config)
{
this.solution = solution;
this.config = config;
}
public bool Build(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null)
{
string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customProperties);
ProcessStartInfo startInfo = new ProcessStartInfo(MSBuildPath, compilerArgs);
// No console output, thanks
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
// Needed when running from Developer Command Prompt for VS
RemovePlatformVariable(startInfo.EnvironmentVariables);
using (Process process = new Process())
{
process.StartInfo = startInfo;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
exitCode = process.ExitCode;
}
return true;
}
public bool BuildAsync(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null)
{
if (process != null)
throw new InvalidOperationException("Already in use");
string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customProperties);
ProcessStartInfo startInfo = new ProcessStartInfo("msbuild", compilerArgs);
// No console output, thanks
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
// Needed when running from Developer Command Prompt for VS
RemovePlatformVariable(startInfo.EnvironmentVariables);
process = new Process();
process.StartInfo = startInfo;
process.EnableRaisingEvents = true;
process.Exited += new EventHandler(BuildProcess_Exited);
process.Start();
return true;
}
private string BuildArguments(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties)
{
string arguments = string.Format("{0} /v:normal /t:Build /p:{1} /l:{2},{3};{4}",
solution,
"Configuration=" + config,
typeof(GodotBuildLogger).FullName,
loggerAssemblyPath,
loggerOutputDir
);
if (customProperties != null)
{
foreach (string customProperty in customProperties)
{
arguments += " /p:" + customProperty;
}
}
return arguments;
}
private void RemovePlatformVariable(StringDictionary environmentVariables)
{
// EnvironmentVariables is case sensitive? Seriously?
List<string> platformEnvironmentVariables = new List<string>();
foreach (string env in environmentVariables.Keys)
{
if (env.ToUpper() == "PLATFORM")
platformEnvironmentVariables.Add(env);
}
foreach (string env in platformEnvironmentVariables)
environmentVariables.Remove(env);
}
private void BuildProcess_Exited(object sender, System.EventArgs e)
{
exitCode = process.ExitCode;
godot_icall_BuildInstance_ExitCallback(solution, config, exitCode);
Dispose();
}
public void Dispose()
{
if (process != null)
{
process.Dispose();
process = null;
}
}
}
public class GodotBuildLogger : ILogger
{
public string Parameters { get; set; }
public LoggerVerbosity Verbosity { get; set; }
public void Initialize(IEventSource eventSource)
{
if (null == Parameters)
throw new LoggerException("Log directory was not set.");
string[] parameters = Parameters.Split(';');
string logDir = parameters[0];
if (String.IsNullOrEmpty(logDir))
throw new LoggerException("Log directory was not set.");
if (parameters.Length > 1)
throw new LoggerException("Too many parameters passed.");
string logFile = Path.Combine(logDir, "msbuild_log.txt");
string issuesFile = Path.Combine(logDir, "msbuild_issues.csv");
try
{
if (!Directory.Exists(logDir))
Directory.CreateDirectory(logDir);
this.logStreamWriter = new StreamWriter(logFile);
this.issuesStreamWriter = new StreamWriter(issuesFile);
}
catch (Exception ex)
{
if
(
ex is UnauthorizedAccessException
|| ex is ArgumentNullException
|| ex is PathTooLongException
|| ex is DirectoryNotFoundException
|| ex is NotSupportedException
|| ex is ArgumentException
|| ex is SecurityException
|| ex is IOException
)
{
throw new LoggerException("Failed to create log file: " + ex.Message);
}
else
{
// Unexpected failure
throw;
}
}
eventSource.ProjectStarted += new ProjectStartedEventHandler(eventSource_ProjectStarted);
eventSource.TaskStarted += new TaskStartedEventHandler(eventSource_TaskStarted);
eventSource.MessageRaised += new BuildMessageEventHandler(eventSource_MessageRaised);
eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
eventSource.ErrorRaised += new BuildErrorEventHandler(eventSource_ErrorRaised);
eventSource.ProjectFinished += new ProjectFinishedEventHandler(eventSource_ProjectFinished);
}
void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e)
{
string line = String.Format("{0}({1},{2}): error {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message);
if (e.ProjectFile.Length > 0)
line += string.Format(" [{0}]", e.ProjectFile);
WriteLine(line);
string errorLine = String.Format(@"error,{0},{1},{2},{3},{4},{5}",
e.File.CsvEscape(), e.LineNumber, e.ColumnNumber,
e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile.CsvEscape());
issuesStreamWriter.WriteLine(errorLine);
}
void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
{
string line = String.Format("{0}({1},{2}): warning {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message, e.ProjectFile);
if (e.ProjectFile != null && e.ProjectFile.Length > 0)
line += string.Format(" [{0}]", e.ProjectFile);
WriteLine(line);
string warningLine = String.Format(@"warning,{0},{1},{2},{3},{4},{5}",
e.File.CsvEscape(), e.LineNumber, e.ColumnNumber,
e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile != null ? e.ProjectFile.CsvEscape() : string.Empty);
issuesStreamWriter.WriteLine(warningLine);
}
void eventSource_MessageRaised(object sender, BuildMessageEventArgs e)
{
// BuildMessageEventArgs adds Importance to BuildEventArgs
// Let's take account of the verbosity setting we've been passed in deciding whether to log the message
if ((e.Importance == MessageImportance.High && IsVerbosityAtLeast(LoggerVerbosity.Minimal))
|| (e.Importance == MessageImportance.Normal && IsVerbosityAtLeast(LoggerVerbosity.Normal))
|| (e.Importance == MessageImportance.Low && IsVerbosityAtLeast(LoggerVerbosity.Detailed))
)
{
WriteLineWithSenderAndMessage(String.Empty, e);
}
}
void eventSource_TaskStarted(object sender, TaskStartedEventArgs e)
{
// TaskStartedEventArgs adds ProjectFile, TaskFile, TaskName
// To keep this log clean, this logger will ignore these events.
}
void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e)
{
WriteLine(e.Message);
indent++;
}
void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e)
{
indent--;
WriteLine(e.Message);
}
/// <summary>
/// Write a line to the log, adding the SenderName
/// </summary>
private void WriteLineWithSender(string line, BuildEventArgs e)
{
if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/))
{
// Well, if the sender name is MSBuild, let's leave it out for prettiness
WriteLine(line);
}
else
{
WriteLine(e.SenderName + ": " + line);
}
}
/// <summary>
/// Write a line to the log, adding the SenderName and Message
/// (these parameters are on all MSBuild event argument objects)
/// </summary>
private void WriteLineWithSenderAndMessage(string line, BuildEventArgs e)
{
if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/))
{
// Well, if the sender name is MSBuild, let's leave it out for prettiness
WriteLine(line + e.Message);
}
else
{
WriteLine(e.SenderName + ": " + line + e.Message);
}
}
private void WriteLine(string line)
{
for (int i = indent; i > 0; i--)
{
logStreamWriter.Write("\t");
}
logStreamWriter.WriteLine(line);
}
public void Shutdown()
{
logStreamWriter.Close();
issuesStreamWriter.Close();
}
public bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity)
{
return this.Verbosity >= checkVerbosity;
}
private StreamWriter logStreamWriter;
private StreamWriter issuesStreamWriter;
private int indent;
}
}
| |
// ****************************************************************
// Copyright 2008, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org
// ****************************************************************
using System;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// The Numerics class contains common operations on numeric values.
/// </summary>
public class Numerics
{
#region Numeric Type Recognition
/// <summary>
/// Checks the type of the object, returning true if
/// the object is a numeric type.
/// </summary>
/// <param name="obj">The object to check</param>
/// <returns>true if the object is a numeric type</returns>
public static bool IsNumericType(Object obj)
{
return IsFloatingPointNumeric( obj ) || IsFixedPointNumeric( obj );
}
/// <summary>
/// Checks the type of the object, returning true if
/// the object is a floating point numeric type.
/// </summary>
/// <param name="obj">The object to check</param>
/// <returns>true if the object is a floating point numeric type</returns>
public static bool IsFloatingPointNumeric(Object obj)
{
if (null != obj)
{
if (obj is System.Double) return true;
if (obj is System.Single) return true;
}
return false;
}
/// <summary>
/// Checks the type of the object, returning true if
/// the object is a fixed point numeric type.
/// </summary>
/// <param name="obj">The object to check</param>
/// <returns>true if the object is a fixed point numeric type</returns>
public static bool IsFixedPointNumeric(Object obj)
{
if (null != obj)
{
if (obj is System.Byte) return true;
if (obj is System.SByte) return true;
if (obj is System.Decimal) return true;
if (obj is System.Int32) return true;
if (obj is System.UInt32) return true;
if (obj is System.Int64) return true;
if (obj is System.UInt64) return true;
if (obj is System.Int16) return true;
if (obj is System.UInt16) return true;
}
return false;
}
#endregion
#region Numeric Equality
/// <summary>
/// Test two numeric values for equality, performing the usual numeric
/// conversions and using a provided or default tolerance. If the tolerance
/// provided is Empty, this method may set it to a default tolerance.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value</param>
/// <param name="tolerance">A reference to the tolerance in effect</param>
/// <returns>True if the values are equal</returns>
public static bool AreEqual( object expected, object actual, ref Tolerance tolerance )
{
if ( expected is double || actual is double )
return AreEqual( Convert.ToDouble(expected), Convert.ToDouble(actual), ref tolerance );
if ( expected is float || actual is float )
return AreEqual( Convert.ToSingle(expected), Convert.ToSingle(actual), ref tolerance );
if (tolerance.Mode == ToleranceMode.Ulps)
throw new InvalidOperationException("Ulps may only be specified for floating point arguments");
if ( expected is decimal || actual is decimal )
return AreEqual( Convert.ToDecimal(expected), Convert.ToDecimal(actual), tolerance );
if (expected is ulong || actual is ulong)
return AreEqual(Convert.ToUInt64(expected), Convert.ToUInt64(actual), tolerance );
if ( expected is long || actual is long )
return AreEqual( Convert.ToInt64(expected), Convert.ToInt64(actual), tolerance );
if ( expected is uint || actual is uint )
return AreEqual( Convert.ToUInt32(expected), Convert.ToUInt32(actual), tolerance );
return AreEqual( Convert.ToInt32(expected), Convert.ToInt32(actual), tolerance );
}
private static bool AreEqual( double expected, double actual, ref Tolerance tolerance )
{
if (double.IsNaN(expected) && double.IsNaN(actual))
return true;
// Handle infinity specially since subtracting two infinite values gives
// NaN and the following test fails. mono also needs NaN to be handled
// specially although ms.net could use either method. Also, handle
// situation where no tolerance is used.
if (double.IsInfinity(expected) || double.IsNaN(expected) || double.IsNaN(actual))
{
return expected.Equals(actual);
}
if (tolerance.IsEmpty && GlobalSettings.DefaultFloatingPointTolerance > 0.0d)
tolerance = new Tolerance(GlobalSettings.DefaultFloatingPointTolerance);
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value);
case ToleranceMode.Percent:
if (expected == 0.0)
return expected.Equals(actual);
double relativeError = Math.Abs((expected - actual) / expected);
return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0);
#if !NETCF_1_0
case ToleranceMode.Ulps:
return FloatingPointNumerics.AreAlmostEqualUlps(
expected, actual, Convert.ToInt64(tolerance.Value));
#endif
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
private static bool AreEqual( float expected, float actual, ref Tolerance tolerance )
{
if ( float.IsNaN(expected) && float.IsNaN(actual) )
return true;
// handle infinity specially since subtracting two infinite values gives
// NaN and the following test fails. mono also needs NaN to be handled
// specially although ms.net could use either method.
if (float.IsInfinity(expected) || float.IsNaN(expected) || float.IsNaN(actual))
{
return expected.Equals(actual);
}
if (tolerance.IsEmpty && GlobalSettings.DefaultFloatingPointTolerance > 0.0d)
tolerance = new Tolerance(GlobalSettings.DefaultFloatingPointTolerance);
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value);
case ToleranceMode.Percent:
if (expected == 0.0f)
return expected.Equals(actual);
float relativeError = Math.Abs((expected - actual) / expected);
return (relativeError <= Convert.ToSingle(tolerance.Value) / 100.0f);
#if !NETCF_1_0
case ToleranceMode.Ulps:
return FloatingPointNumerics.AreAlmostEqualUlps(
expected, actual, Convert.ToInt32(tolerance.Value));
#endif
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
private static bool AreEqual( decimal expected, decimal actual, Tolerance tolerance )
{
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
decimal decimalTolerance = Convert.ToDecimal(tolerance.Value);
if(decimalTolerance > 0m)
return Math.Abs(expected - actual) <= decimalTolerance;
return expected.Equals( actual );
case ToleranceMode.Percent:
if(expected == 0m)
return expected.Equals(actual);
double relativeError = Math.Abs(
(double)(expected - actual) / (double)expected);
return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0);
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
private static bool AreEqual( ulong expected, ulong actual, Tolerance tolerance )
{
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
ulong ulongTolerance = Convert.ToUInt64(tolerance.Value);
if(ulongTolerance > 0ul)
{
ulong diff = expected >= actual ? expected - actual : actual - expected;
return diff <= ulongTolerance;
}
return expected.Equals( actual );
case ToleranceMode.Percent:
if (expected == 0ul)
return expected.Equals(actual);
// Can't do a simple Math.Abs() here since it's unsigned
ulong difference = Math.Max(expected, actual) - Math.Min(expected, actual);
double relativeError = Math.Abs( (double)difference / (double)expected );
return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0);
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
private static bool AreEqual( long expected, long actual, Tolerance tolerance )
{
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
long longTolerance = Convert.ToInt64(tolerance.Value);
if(longTolerance > 0L)
return Math.Abs(expected - actual) <= longTolerance;
return expected.Equals( actual );
case ToleranceMode.Percent:
if(expected == 0L)
return expected.Equals(actual);
double relativeError = Math.Abs(
(double)(expected - actual) / (double)expected);
return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0);
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
private static bool AreEqual( uint expected, uint actual, Tolerance tolerance )
{
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
uint uintTolerance = Convert.ToUInt32(tolerance.Value);
if(uintTolerance > 0)
{
uint diff = expected >= actual ? expected - actual : actual - expected;
return diff <= uintTolerance;
}
return expected.Equals( actual );
case ToleranceMode.Percent:
if(expected == 0u)
return expected.Equals(actual);
// Can't do a simple Math.Abs() here since it's unsigned
uint difference = Math.Max(expected, actual) - Math.Min(expected, actual);
double relativeError = Math.Abs((double)difference / (double)expected );
return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0);
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
private static bool AreEqual( int expected, int actual, Tolerance tolerance )
{
switch (tolerance.Mode)
{
case ToleranceMode.None:
return expected.Equals(actual);
case ToleranceMode.Linear:
int intTolerance = Convert.ToInt32(tolerance.Value);
if (intTolerance > 0)
return Math.Abs(expected - actual) <= intTolerance;
return expected.Equals(actual);
case ToleranceMode.Percent:
if (expected == 0)
return expected.Equals(actual);
double relativeError = Math.Abs(
(double)(expected - actual) / (double)expected);
return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0);
default:
throw new ArgumentException("Unknown tolerance mode specified", "mode");
}
}
#endregion
#region Numeric Comparisons
/// <summary>
/// Compare two numeric values, performing the usual numeric conversions.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="actual">The actual value</param>
/// <returns>The relationship of the values to each other</returns>
public static int Compare( object expected, object actual )
{
if( !IsNumericType( expected ) || !IsNumericType( actual ) )
throw new ArgumentException( "Both arguments must be numeric");
if ( IsFloatingPointNumeric(expected) || IsFloatingPointNumeric(actual) )
return Convert.ToDouble(expected).CompareTo(Convert.ToDouble(actual));
if ( expected is decimal || actual is decimal )
return Convert.ToDecimal(expected).CompareTo(Convert.ToDecimal(actual));
if ( expected is ulong || actual is ulong )
return Convert.ToUInt64(expected).CompareTo(Convert.ToUInt64(actual));
if ( expected is long || actual is long )
return Convert.ToInt64(expected).CompareTo(Convert.ToInt64(actual));
if ( expected is uint || actual is uint )
return Convert.ToUInt32(expected).CompareTo(Convert.ToUInt32(actual));
return Convert.ToInt32(expected).CompareTo(Convert.ToInt32(actual));
}
#endregion
private Numerics()
{
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
public enum wheelScaleType { larger, smaller, wider, thinner }
public class Wheels : MonoBehaviour {
private bool initialized = false;
GUIContent[] comboBoxList;
private ComboBox comboBoxControl;// = new ComboBox();
public GUIStyle listStyle = new GUIStyle();
public List<CarPart> selectableWheels = new List<CarPart>();
//public List<Car> matchingCars = new List<Car>();
public bool activateComboBox = true;
public CarPart currentWheelSelection;
public List<CarPart> currentInstantiatedWheels = new List<CarPart>();
private CarPart wheel;
private GameObject wheelsNode;
private Rect guiLeftArea;
public Camera guiLeftCam;
public GUIStyle buttonStyle = new GUIStyle();
//public wheelScaleType scaleType = CarPartType.Body;
// ----------------------------------------------------------------------
public void init(){
guiLeftArea = new Rect (guiLeftCam.pixelRect.xMin, guiLeftCam.pixelRect.yMax * 2.33f, guiLeftCam.pixelRect.width, guiLeftCam.pixelRect.height);
// set size of ComboBoxList
comboBoxList = new GUIContent[this.selectableWheels.Count];
// set entries of ComboBoxList
for(int i = 0; i < this.selectableWheels.Count; i++){
this.comboBoxList[i] = new GUIContent(this.selectableWheels[i].id.ToString());
}
// style ComboBox
this.listStyle.normal.textColor = Color.black;
this.listStyle.onHover.background = this.listStyle.hover.background = new Texture2D(2, 2);
this.listStyle.padding.left = 4;
this.listStyle.padding.right = 4;
this.listStyle.padding.top = 4;
this.listStyle.padding.bottom = 4;
// set currentCar in comboBox
//foreach(CarPart cp in this.SelectableWheels){
Rect rect = new Rect (guiLeftArea.xMax *.05f, guiLeftArea.y * .22f, guiLeftArea.width /1.6f , guiLeftArea.height / 35);
this.comboBoxControl = new ComboBox(rect, this.comboBoxList[0], this.comboBoxList, buttonStyle, "box", this.listStyle);
this.initialized = true;
// set first item to init currentWheel
this.currentWheelSelection = this.selectableWheels[0];
this.setWheels(this.currentWheelSelection);
}
// ------------------------------------------------------------------------
private void OnGUI ()
{
if(!initialized){
return;
}
//this.comboBoxControl.Show ();
if(this.activateComboBox){
// gives the current selected id to the instantiate method
this.instantiateCarPart (this.comboBoxControl.Show ());
}
}
// -----------------------------------------------------------------------
public void instantiateCarPart(int id){
if (this.selectableWheels[id] != this.currentWheelSelection) {
GUIManager.SetShowMainMenuBool(true);
// destroy the old instance of carPart (wheels) and load the new parts
this.setWheels(this.selectableWheels[id]);
// set the actual wheelId to the new currentWheelSelection
this.currentWheelSelection = this.selectableWheels[id];
//set index for comboListBox
this.comboBoxControl.SelectedItemIndex = id;
}
}
// -----------------------------------------------------------------------
public void setWheels(CarPart currentCarPart){
// destroy all already instantiated Wheel-GOs and clear List
this.destroyWheels();
//Get wheel locator of car
List<CarPart> wheelLocators = new List<CarPart> ();
foreach(CarPart cp in Controller.instance.currentCar.GetComponentsInChildren<CarPart>()){
if(cp.carPartType.Equals(CarPartType.WheelLocator)){
// add appropriate cp to list
wheelLocators.Add(cp);
}
}
// instantiate a wheel for any wheelLocator
for(int i = 0; i < wheelLocators.Count; i++){
// instantiate
CarPart instantiatedCarPart = (CarPart)GameObject.Instantiate (currentCarPart);
// add instantiated cp to list
this.currentInstantiatedWheels.Add(instantiatedCarPart);
// set position
Transform wheelLocatorTransform = wheelLocators[i].transform;
instantiatedCarPart.transform.position = wheelLocatorTransform.position;
instantiatedCarPart.transform.localEulerAngles = wheelLocatorTransform.localEulerAngles;
instantiatedCarPart.transform.parent = wheelLocatorTransform;
//this.setCarPartParent();
}
}
// -----------------------------------------------------------------------------
public void destroyWheels(){
foreach(CarPart go in this.currentInstantiatedWheels){
GameObject.DestroyImmediate(go.gameObject);
}
this.currentInstantiatedWheels.Clear();
}
// -----------------------------------------------------------------------------
public float getWheelSizeY(){
return currentInstantiatedWheels [0].transform.localScale.y;
}
public float getWheelWidth(){
return currentInstantiatedWheels [0].transform.localScale.x;
}
public void setWheelSize(float newSize){
foreach(CarPart cp in this.currentInstantiatedWheels){
cp.transform.localScale = new Vector3 (cp.transform.localScale.x, newSize, newSize);
}
}
public void setWheelThickness(float newSize){
foreach(CarPart cp in this.currentInstantiatedWheels){
cp.transform.localScale = new Vector3 (newSize, cp.transform.localScale.y, cp.transform.localScale.z);
}
}
public void setWheelScale(wheelScaleType scaleType){
Debug.Log (currentInstantiatedWheels[0].transform.localScale);
if(scaleType.Equals(wheelScaleType.larger)){
foreach(CarPart cp in this.currentInstantiatedWheels){
cp.transform.localScale = new Vector3 (cp.transform.localScale.x, cp.transform.localScale.y + 0.1f, cp.transform.localScale.z + 0.1f);
}
}
else if(scaleType.Equals(wheelScaleType.smaller)){
foreach(CarPart cp in this.currentInstantiatedWheels){
cp.transform.localScale = new Vector3 (cp.transform.localScale.x, cp.transform.localScale.y - 0.1f, cp.transform.localScale.z - 0.1f);
}
}
else if(scaleType.Equals(wheelScaleType.wider)){
foreach(CarPart cp in this.currentInstantiatedWheels){
cp.transform.localScale = new Vector3 (cp.transform.localScale.x + 0.1f, cp.transform.localScale.y, cp.transform.localScale.z);
}
}
else if(scaleType.Equals(wheelScaleType.thinner)){
foreach(CarPart cp in this.currentInstantiatedWheels){
cp.transform.localScale = new Vector3 (cp.transform.localScale.x - 0.1f, cp.transform.localScale.y, cp.transform.localScale.z);
}
}
}
// -----------------------------------------------------------------------------
public int getComboListIndexForCarPartId(string cpId){
int index = -1;
foreach(CarPart cp in this.selectableWheels){
if(cp.id.Equals(cpId)){
index = this.selectableWheels.IndexOf(cp);
}
}
return index;
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;
namespace LibGit2Sharp
{
/// <summary>
/// Holds the patch between two trees.
/// <para>The individual patches for each file can be accessed through the indexer of this class.</para>
/// <para>Building a patch is an expensive operation. If you only need to know which files have been added,
/// deleted, modified, ..., then consider using a simpler <see cref="TreeChanges"/>.</para>
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class Patch : IEnumerable<PatchEntryChanges>, IDiffResult
{
private readonly StringBuilder fullPatchBuilder = new StringBuilder();
private readonly IDictionary<FilePath, PatchEntryChanges> changes = new Dictionary<FilePath, PatchEntryChanges>();
private int linesAdded;
private int linesDeleted;
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected Patch()
{ }
internal unsafe Patch(DiffHandle diff)
{
using (diff)
{
int count = Proxy.git_diff_num_deltas(diff);
for (int i = 0; i < count; i++)
{
using (var patch = Proxy.git_patch_from_diff(diff, i))
{
var delta = Proxy.git_diff_get_delta(diff, i);
AddFileChange(delta);
Proxy.git_patch_print(patch, PrintCallBack);
}
}
}
}
private unsafe void AddFileChange(git_diff_delta* delta)
{
var treeEntryChanges = new TreeEntryChanges(delta);
changes.Add(treeEntryChanges.Path, new PatchEntryChanges(delta->flags.HasFlag(GitDiffFlags.GIT_DIFF_FLAG_BINARY), treeEntryChanges));
}
private unsafe int PrintCallBack(git_diff_delta* delta, GitDiffHunk hunk, GitDiffLine line, IntPtr payload)
{
string patchPart = LaxUtf8Marshaler.FromNative(line.content, (int)line.contentLen);
// Deleted files mean no "new file" path
var pathPtr = delta->new_file.Path != null
? delta->new_file.Path
: delta->old_file.Path;
var filePath = LaxFilePathMarshaler.FromNative(pathPtr);
PatchEntryChanges currentChange = this[filePath];
string prefix = string.Empty;
switch (line.lineOrigin)
{
case GitDiffLineOrigin.GIT_DIFF_LINE_CONTEXT:
prefix = " ";
break;
case GitDiffLineOrigin.GIT_DIFF_LINE_ADDITION:
linesAdded++;
currentChange.LinesAdded++;
prefix = "+";
break;
case GitDiffLineOrigin.GIT_DIFF_LINE_DELETION:
linesDeleted++;
currentChange.LinesDeleted++;
prefix = "-";
break;
}
string formattedOutput = string.Concat(prefix, patchPart);
fullPatchBuilder.Append(formattedOutput);
currentChange.AppendToPatch(formattedOutput);
return 0;
}
#region IEnumerable<PatchEntryChanges> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the collection.</returns>
public virtual IEnumerator<PatchEntryChanges> GetEnumerator()
{
return changes.Values.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
/// <summary>
/// Gets the <see cref="ContentChanges"/> corresponding to the specified <paramref name="path"/>.
/// </summary>
public virtual PatchEntryChanges this[string path]
{
get { return this[(FilePath)path]; }
}
private PatchEntryChanges this[FilePath path]
{
get
{
PatchEntryChanges entryChanges;
if (changes.TryGetValue(path, out entryChanges))
{
return entryChanges;
}
return null;
}
}
/// <summary>
/// The total number of lines added in this diff.
/// </summary>
public virtual int LinesAdded
{
get { return linesAdded; }
}
/// <summary>
/// The total number of lines deleted in this diff.
/// </summary>
public virtual int LinesDeleted
{
get { return linesDeleted; }
}
/// <summary>
/// The full patch file of this diff.
/// </summary>
public virtual string Content
{
get { return fullPatchBuilder.ToString(); }
}
/// <summary>
/// Implicit operator for string conversion.
/// </summary>
/// <param name="patch"><see cref="Patch"/>.</param>
/// <returns>The patch content as string.</returns>
public static implicit operator string (Patch patch)
{
return patch.fullPatchBuilder.ToString();
}
private string DebuggerDisplay
{
get
{
return string.Format(CultureInfo.InvariantCulture,
"+{0} -{1}",
linesAdded,
linesDeleted);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
// This doesn't do anything yet because it loads everything
// eagerly and disposes of the diff handle in the constructor.
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp.Swizzle
{
/// <summary>
/// Temporary vector of type uint with 3 components, used for implementing swizzling for uvec3.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct swizzle_uvec3
{
#region Fields
/// <summary>
/// x-component
/// </summary>
internal readonly uint x;
/// <summary>
/// y-component
/// </summary>
internal readonly uint y;
/// <summary>
/// z-component
/// </summary>
internal readonly uint z;
#endregion
#region Constructors
/// <summary>
/// Constructor for swizzle_uvec3.
/// </summary>
internal swizzle_uvec3(uint x, uint y, uint z)
{
this.x = x;
this.y = y;
this.z = z;
}
#endregion
#region Properties
/// <summary>
/// Returns uvec3.xx swizzling.
/// </summary>
public uvec2 xx => new uvec2(x, x);
/// <summary>
/// Returns uvec3.rr swizzling (equivalent to uvec3.xx).
/// </summary>
public uvec2 rr => new uvec2(x, x);
/// <summary>
/// Returns uvec3.xxx swizzling.
/// </summary>
public uvec3 xxx => new uvec3(x, x, x);
/// <summary>
/// Returns uvec3.rrr swizzling (equivalent to uvec3.xxx).
/// </summary>
public uvec3 rrr => new uvec3(x, x, x);
/// <summary>
/// Returns uvec3.xxxx swizzling.
/// </summary>
public uvec4 xxxx => new uvec4(x, x, x, x);
/// <summary>
/// Returns uvec3.rrrr swizzling (equivalent to uvec3.xxxx).
/// </summary>
public uvec4 rrrr => new uvec4(x, x, x, x);
/// <summary>
/// Returns uvec3.xxxy swizzling.
/// </summary>
public uvec4 xxxy => new uvec4(x, x, x, y);
/// <summary>
/// Returns uvec3.rrrg swizzling (equivalent to uvec3.xxxy).
/// </summary>
public uvec4 rrrg => new uvec4(x, x, x, y);
/// <summary>
/// Returns uvec3.xxxz swizzling.
/// </summary>
public uvec4 xxxz => new uvec4(x, x, x, z);
/// <summary>
/// Returns uvec3.rrrb swizzling (equivalent to uvec3.xxxz).
/// </summary>
public uvec4 rrrb => new uvec4(x, x, x, z);
/// <summary>
/// Returns uvec3.xxy swizzling.
/// </summary>
public uvec3 xxy => new uvec3(x, x, y);
/// <summary>
/// Returns uvec3.rrg swizzling (equivalent to uvec3.xxy).
/// </summary>
public uvec3 rrg => new uvec3(x, x, y);
/// <summary>
/// Returns uvec3.xxyx swizzling.
/// </summary>
public uvec4 xxyx => new uvec4(x, x, y, x);
/// <summary>
/// Returns uvec3.rrgr swizzling (equivalent to uvec3.xxyx).
/// </summary>
public uvec4 rrgr => new uvec4(x, x, y, x);
/// <summary>
/// Returns uvec3.xxyy swizzling.
/// </summary>
public uvec4 xxyy => new uvec4(x, x, y, y);
/// <summary>
/// Returns uvec3.rrgg swizzling (equivalent to uvec3.xxyy).
/// </summary>
public uvec4 rrgg => new uvec4(x, x, y, y);
/// <summary>
/// Returns uvec3.xxyz swizzling.
/// </summary>
public uvec4 xxyz => new uvec4(x, x, y, z);
/// <summary>
/// Returns uvec3.rrgb swizzling (equivalent to uvec3.xxyz).
/// </summary>
public uvec4 rrgb => new uvec4(x, x, y, z);
/// <summary>
/// Returns uvec3.xxz swizzling.
/// </summary>
public uvec3 xxz => new uvec3(x, x, z);
/// <summary>
/// Returns uvec3.rrb swizzling (equivalent to uvec3.xxz).
/// </summary>
public uvec3 rrb => new uvec3(x, x, z);
/// <summary>
/// Returns uvec3.xxzx swizzling.
/// </summary>
public uvec4 xxzx => new uvec4(x, x, z, x);
/// <summary>
/// Returns uvec3.rrbr swizzling (equivalent to uvec3.xxzx).
/// </summary>
public uvec4 rrbr => new uvec4(x, x, z, x);
/// <summary>
/// Returns uvec3.xxzy swizzling.
/// </summary>
public uvec4 xxzy => new uvec4(x, x, z, y);
/// <summary>
/// Returns uvec3.rrbg swizzling (equivalent to uvec3.xxzy).
/// </summary>
public uvec4 rrbg => new uvec4(x, x, z, y);
/// <summary>
/// Returns uvec3.xxzz swizzling.
/// </summary>
public uvec4 xxzz => new uvec4(x, x, z, z);
/// <summary>
/// Returns uvec3.rrbb swizzling (equivalent to uvec3.xxzz).
/// </summary>
public uvec4 rrbb => new uvec4(x, x, z, z);
/// <summary>
/// Returns uvec3.xy swizzling.
/// </summary>
public uvec2 xy => new uvec2(x, y);
/// <summary>
/// Returns uvec3.rg swizzling (equivalent to uvec3.xy).
/// </summary>
public uvec2 rg => new uvec2(x, y);
/// <summary>
/// Returns uvec3.xyx swizzling.
/// </summary>
public uvec3 xyx => new uvec3(x, y, x);
/// <summary>
/// Returns uvec3.rgr swizzling (equivalent to uvec3.xyx).
/// </summary>
public uvec3 rgr => new uvec3(x, y, x);
/// <summary>
/// Returns uvec3.xyxx swizzling.
/// </summary>
public uvec4 xyxx => new uvec4(x, y, x, x);
/// <summary>
/// Returns uvec3.rgrr swizzling (equivalent to uvec3.xyxx).
/// </summary>
public uvec4 rgrr => new uvec4(x, y, x, x);
/// <summary>
/// Returns uvec3.xyxy swizzling.
/// </summary>
public uvec4 xyxy => new uvec4(x, y, x, y);
/// <summary>
/// Returns uvec3.rgrg swizzling (equivalent to uvec3.xyxy).
/// </summary>
public uvec4 rgrg => new uvec4(x, y, x, y);
/// <summary>
/// Returns uvec3.xyxz swizzling.
/// </summary>
public uvec4 xyxz => new uvec4(x, y, x, z);
/// <summary>
/// Returns uvec3.rgrb swizzling (equivalent to uvec3.xyxz).
/// </summary>
public uvec4 rgrb => new uvec4(x, y, x, z);
/// <summary>
/// Returns uvec3.xyy swizzling.
/// </summary>
public uvec3 xyy => new uvec3(x, y, y);
/// <summary>
/// Returns uvec3.rgg swizzling (equivalent to uvec3.xyy).
/// </summary>
public uvec3 rgg => new uvec3(x, y, y);
/// <summary>
/// Returns uvec3.xyyx swizzling.
/// </summary>
public uvec4 xyyx => new uvec4(x, y, y, x);
/// <summary>
/// Returns uvec3.rggr swizzling (equivalent to uvec3.xyyx).
/// </summary>
public uvec4 rggr => new uvec4(x, y, y, x);
/// <summary>
/// Returns uvec3.xyyy swizzling.
/// </summary>
public uvec4 xyyy => new uvec4(x, y, y, y);
/// <summary>
/// Returns uvec3.rggg swizzling (equivalent to uvec3.xyyy).
/// </summary>
public uvec4 rggg => new uvec4(x, y, y, y);
/// <summary>
/// Returns uvec3.xyyz swizzling.
/// </summary>
public uvec4 xyyz => new uvec4(x, y, y, z);
/// <summary>
/// Returns uvec3.rggb swizzling (equivalent to uvec3.xyyz).
/// </summary>
public uvec4 rggb => new uvec4(x, y, y, z);
/// <summary>
/// Returns uvec3.xyz swizzling.
/// </summary>
public uvec3 xyz => new uvec3(x, y, z);
/// <summary>
/// Returns uvec3.rgb swizzling (equivalent to uvec3.xyz).
/// </summary>
public uvec3 rgb => new uvec3(x, y, z);
/// <summary>
/// Returns uvec3.xyzx swizzling.
/// </summary>
public uvec4 xyzx => new uvec4(x, y, z, x);
/// <summary>
/// Returns uvec3.rgbr swizzling (equivalent to uvec3.xyzx).
/// </summary>
public uvec4 rgbr => new uvec4(x, y, z, x);
/// <summary>
/// Returns uvec3.xyzy swizzling.
/// </summary>
public uvec4 xyzy => new uvec4(x, y, z, y);
/// <summary>
/// Returns uvec3.rgbg swizzling (equivalent to uvec3.xyzy).
/// </summary>
public uvec4 rgbg => new uvec4(x, y, z, y);
/// <summary>
/// Returns uvec3.xyzz swizzling.
/// </summary>
public uvec4 xyzz => new uvec4(x, y, z, z);
/// <summary>
/// Returns uvec3.rgbb swizzling (equivalent to uvec3.xyzz).
/// </summary>
public uvec4 rgbb => new uvec4(x, y, z, z);
/// <summary>
/// Returns uvec3.xz swizzling.
/// </summary>
public uvec2 xz => new uvec2(x, z);
/// <summary>
/// Returns uvec3.rb swizzling (equivalent to uvec3.xz).
/// </summary>
public uvec2 rb => new uvec2(x, z);
/// <summary>
/// Returns uvec3.xzx swizzling.
/// </summary>
public uvec3 xzx => new uvec3(x, z, x);
/// <summary>
/// Returns uvec3.rbr swizzling (equivalent to uvec3.xzx).
/// </summary>
public uvec3 rbr => new uvec3(x, z, x);
/// <summary>
/// Returns uvec3.xzxx swizzling.
/// </summary>
public uvec4 xzxx => new uvec4(x, z, x, x);
/// <summary>
/// Returns uvec3.rbrr swizzling (equivalent to uvec3.xzxx).
/// </summary>
public uvec4 rbrr => new uvec4(x, z, x, x);
/// <summary>
/// Returns uvec3.xzxy swizzling.
/// </summary>
public uvec4 xzxy => new uvec4(x, z, x, y);
/// <summary>
/// Returns uvec3.rbrg swizzling (equivalent to uvec3.xzxy).
/// </summary>
public uvec4 rbrg => new uvec4(x, z, x, y);
/// <summary>
/// Returns uvec3.xzxz swizzling.
/// </summary>
public uvec4 xzxz => new uvec4(x, z, x, z);
/// <summary>
/// Returns uvec3.rbrb swizzling (equivalent to uvec3.xzxz).
/// </summary>
public uvec4 rbrb => new uvec4(x, z, x, z);
/// <summary>
/// Returns uvec3.xzy swizzling.
/// </summary>
public uvec3 xzy => new uvec3(x, z, y);
/// <summary>
/// Returns uvec3.rbg swizzling (equivalent to uvec3.xzy).
/// </summary>
public uvec3 rbg => new uvec3(x, z, y);
/// <summary>
/// Returns uvec3.xzyx swizzling.
/// </summary>
public uvec4 xzyx => new uvec4(x, z, y, x);
/// <summary>
/// Returns uvec3.rbgr swizzling (equivalent to uvec3.xzyx).
/// </summary>
public uvec4 rbgr => new uvec4(x, z, y, x);
/// <summary>
/// Returns uvec3.xzyy swizzling.
/// </summary>
public uvec4 xzyy => new uvec4(x, z, y, y);
/// <summary>
/// Returns uvec3.rbgg swizzling (equivalent to uvec3.xzyy).
/// </summary>
public uvec4 rbgg => new uvec4(x, z, y, y);
/// <summary>
/// Returns uvec3.xzyz swizzling.
/// </summary>
public uvec4 xzyz => new uvec4(x, z, y, z);
/// <summary>
/// Returns uvec3.rbgb swizzling (equivalent to uvec3.xzyz).
/// </summary>
public uvec4 rbgb => new uvec4(x, z, y, z);
/// <summary>
/// Returns uvec3.xzz swizzling.
/// </summary>
public uvec3 xzz => new uvec3(x, z, z);
/// <summary>
/// Returns uvec3.rbb swizzling (equivalent to uvec3.xzz).
/// </summary>
public uvec3 rbb => new uvec3(x, z, z);
/// <summary>
/// Returns uvec3.xzzx swizzling.
/// </summary>
public uvec4 xzzx => new uvec4(x, z, z, x);
/// <summary>
/// Returns uvec3.rbbr swizzling (equivalent to uvec3.xzzx).
/// </summary>
public uvec4 rbbr => new uvec4(x, z, z, x);
/// <summary>
/// Returns uvec3.xzzy swizzling.
/// </summary>
public uvec4 xzzy => new uvec4(x, z, z, y);
/// <summary>
/// Returns uvec3.rbbg swizzling (equivalent to uvec3.xzzy).
/// </summary>
public uvec4 rbbg => new uvec4(x, z, z, y);
/// <summary>
/// Returns uvec3.xzzz swizzling.
/// </summary>
public uvec4 xzzz => new uvec4(x, z, z, z);
/// <summary>
/// Returns uvec3.rbbb swizzling (equivalent to uvec3.xzzz).
/// </summary>
public uvec4 rbbb => new uvec4(x, z, z, z);
/// <summary>
/// Returns uvec3.yx swizzling.
/// </summary>
public uvec2 yx => new uvec2(y, x);
/// <summary>
/// Returns uvec3.gr swizzling (equivalent to uvec3.yx).
/// </summary>
public uvec2 gr => new uvec2(y, x);
/// <summary>
/// Returns uvec3.yxx swizzling.
/// </summary>
public uvec3 yxx => new uvec3(y, x, x);
/// <summary>
/// Returns uvec3.grr swizzling (equivalent to uvec3.yxx).
/// </summary>
public uvec3 grr => new uvec3(y, x, x);
/// <summary>
/// Returns uvec3.yxxx swizzling.
/// </summary>
public uvec4 yxxx => new uvec4(y, x, x, x);
/// <summary>
/// Returns uvec3.grrr swizzling (equivalent to uvec3.yxxx).
/// </summary>
public uvec4 grrr => new uvec4(y, x, x, x);
/// <summary>
/// Returns uvec3.yxxy swizzling.
/// </summary>
public uvec4 yxxy => new uvec4(y, x, x, y);
/// <summary>
/// Returns uvec3.grrg swizzling (equivalent to uvec3.yxxy).
/// </summary>
public uvec4 grrg => new uvec4(y, x, x, y);
/// <summary>
/// Returns uvec3.yxxz swizzling.
/// </summary>
public uvec4 yxxz => new uvec4(y, x, x, z);
/// <summary>
/// Returns uvec3.grrb swizzling (equivalent to uvec3.yxxz).
/// </summary>
public uvec4 grrb => new uvec4(y, x, x, z);
/// <summary>
/// Returns uvec3.yxy swizzling.
/// </summary>
public uvec3 yxy => new uvec3(y, x, y);
/// <summary>
/// Returns uvec3.grg swizzling (equivalent to uvec3.yxy).
/// </summary>
public uvec3 grg => new uvec3(y, x, y);
/// <summary>
/// Returns uvec3.yxyx swizzling.
/// </summary>
public uvec4 yxyx => new uvec4(y, x, y, x);
/// <summary>
/// Returns uvec3.grgr swizzling (equivalent to uvec3.yxyx).
/// </summary>
public uvec4 grgr => new uvec4(y, x, y, x);
/// <summary>
/// Returns uvec3.yxyy swizzling.
/// </summary>
public uvec4 yxyy => new uvec4(y, x, y, y);
/// <summary>
/// Returns uvec3.grgg swizzling (equivalent to uvec3.yxyy).
/// </summary>
public uvec4 grgg => new uvec4(y, x, y, y);
/// <summary>
/// Returns uvec3.yxyz swizzling.
/// </summary>
public uvec4 yxyz => new uvec4(y, x, y, z);
/// <summary>
/// Returns uvec3.grgb swizzling (equivalent to uvec3.yxyz).
/// </summary>
public uvec4 grgb => new uvec4(y, x, y, z);
/// <summary>
/// Returns uvec3.yxz swizzling.
/// </summary>
public uvec3 yxz => new uvec3(y, x, z);
/// <summary>
/// Returns uvec3.grb swizzling (equivalent to uvec3.yxz).
/// </summary>
public uvec3 grb => new uvec3(y, x, z);
/// <summary>
/// Returns uvec3.yxzx swizzling.
/// </summary>
public uvec4 yxzx => new uvec4(y, x, z, x);
/// <summary>
/// Returns uvec3.grbr swizzling (equivalent to uvec3.yxzx).
/// </summary>
public uvec4 grbr => new uvec4(y, x, z, x);
/// <summary>
/// Returns uvec3.yxzy swizzling.
/// </summary>
public uvec4 yxzy => new uvec4(y, x, z, y);
/// <summary>
/// Returns uvec3.grbg swizzling (equivalent to uvec3.yxzy).
/// </summary>
public uvec4 grbg => new uvec4(y, x, z, y);
/// <summary>
/// Returns uvec3.yxzz swizzling.
/// </summary>
public uvec4 yxzz => new uvec4(y, x, z, z);
/// <summary>
/// Returns uvec3.grbb swizzling (equivalent to uvec3.yxzz).
/// </summary>
public uvec4 grbb => new uvec4(y, x, z, z);
/// <summary>
/// Returns uvec3.yy swizzling.
/// </summary>
public uvec2 yy => new uvec2(y, y);
/// <summary>
/// Returns uvec3.gg swizzling (equivalent to uvec3.yy).
/// </summary>
public uvec2 gg => new uvec2(y, y);
/// <summary>
/// Returns uvec3.yyx swizzling.
/// </summary>
public uvec3 yyx => new uvec3(y, y, x);
/// <summary>
/// Returns uvec3.ggr swizzling (equivalent to uvec3.yyx).
/// </summary>
public uvec3 ggr => new uvec3(y, y, x);
/// <summary>
/// Returns uvec3.yyxx swizzling.
/// </summary>
public uvec4 yyxx => new uvec4(y, y, x, x);
/// <summary>
/// Returns uvec3.ggrr swizzling (equivalent to uvec3.yyxx).
/// </summary>
public uvec4 ggrr => new uvec4(y, y, x, x);
/// <summary>
/// Returns uvec3.yyxy swizzling.
/// </summary>
public uvec4 yyxy => new uvec4(y, y, x, y);
/// <summary>
/// Returns uvec3.ggrg swizzling (equivalent to uvec3.yyxy).
/// </summary>
public uvec4 ggrg => new uvec4(y, y, x, y);
/// <summary>
/// Returns uvec3.yyxz swizzling.
/// </summary>
public uvec4 yyxz => new uvec4(y, y, x, z);
/// <summary>
/// Returns uvec3.ggrb swizzling (equivalent to uvec3.yyxz).
/// </summary>
public uvec4 ggrb => new uvec4(y, y, x, z);
/// <summary>
/// Returns uvec3.yyy swizzling.
/// </summary>
public uvec3 yyy => new uvec3(y, y, y);
/// <summary>
/// Returns uvec3.ggg swizzling (equivalent to uvec3.yyy).
/// </summary>
public uvec3 ggg => new uvec3(y, y, y);
/// <summary>
/// Returns uvec3.yyyx swizzling.
/// </summary>
public uvec4 yyyx => new uvec4(y, y, y, x);
/// <summary>
/// Returns uvec3.gggr swizzling (equivalent to uvec3.yyyx).
/// </summary>
public uvec4 gggr => new uvec4(y, y, y, x);
/// <summary>
/// Returns uvec3.yyyy swizzling.
/// </summary>
public uvec4 yyyy => new uvec4(y, y, y, y);
/// <summary>
/// Returns uvec3.gggg swizzling (equivalent to uvec3.yyyy).
/// </summary>
public uvec4 gggg => new uvec4(y, y, y, y);
/// <summary>
/// Returns uvec3.yyyz swizzling.
/// </summary>
public uvec4 yyyz => new uvec4(y, y, y, z);
/// <summary>
/// Returns uvec3.gggb swizzling (equivalent to uvec3.yyyz).
/// </summary>
public uvec4 gggb => new uvec4(y, y, y, z);
/// <summary>
/// Returns uvec3.yyz swizzling.
/// </summary>
public uvec3 yyz => new uvec3(y, y, z);
/// <summary>
/// Returns uvec3.ggb swizzling (equivalent to uvec3.yyz).
/// </summary>
public uvec3 ggb => new uvec3(y, y, z);
/// <summary>
/// Returns uvec3.yyzx swizzling.
/// </summary>
public uvec4 yyzx => new uvec4(y, y, z, x);
/// <summary>
/// Returns uvec3.ggbr swizzling (equivalent to uvec3.yyzx).
/// </summary>
public uvec4 ggbr => new uvec4(y, y, z, x);
/// <summary>
/// Returns uvec3.yyzy swizzling.
/// </summary>
public uvec4 yyzy => new uvec4(y, y, z, y);
/// <summary>
/// Returns uvec3.ggbg swizzling (equivalent to uvec3.yyzy).
/// </summary>
public uvec4 ggbg => new uvec4(y, y, z, y);
/// <summary>
/// Returns uvec3.yyzz swizzling.
/// </summary>
public uvec4 yyzz => new uvec4(y, y, z, z);
/// <summary>
/// Returns uvec3.ggbb swizzling (equivalent to uvec3.yyzz).
/// </summary>
public uvec4 ggbb => new uvec4(y, y, z, z);
/// <summary>
/// Returns uvec3.yz swizzling.
/// </summary>
public uvec2 yz => new uvec2(y, z);
/// <summary>
/// Returns uvec3.gb swizzling (equivalent to uvec3.yz).
/// </summary>
public uvec2 gb => new uvec2(y, z);
/// <summary>
/// Returns uvec3.yzx swizzling.
/// </summary>
public uvec3 yzx => new uvec3(y, z, x);
/// <summary>
/// Returns uvec3.gbr swizzling (equivalent to uvec3.yzx).
/// </summary>
public uvec3 gbr => new uvec3(y, z, x);
/// <summary>
/// Returns uvec3.yzxx swizzling.
/// </summary>
public uvec4 yzxx => new uvec4(y, z, x, x);
/// <summary>
/// Returns uvec3.gbrr swizzling (equivalent to uvec3.yzxx).
/// </summary>
public uvec4 gbrr => new uvec4(y, z, x, x);
/// <summary>
/// Returns uvec3.yzxy swizzling.
/// </summary>
public uvec4 yzxy => new uvec4(y, z, x, y);
/// <summary>
/// Returns uvec3.gbrg swizzling (equivalent to uvec3.yzxy).
/// </summary>
public uvec4 gbrg => new uvec4(y, z, x, y);
/// <summary>
/// Returns uvec3.yzxz swizzling.
/// </summary>
public uvec4 yzxz => new uvec4(y, z, x, z);
/// <summary>
/// Returns uvec3.gbrb swizzling (equivalent to uvec3.yzxz).
/// </summary>
public uvec4 gbrb => new uvec4(y, z, x, z);
/// <summary>
/// Returns uvec3.yzy swizzling.
/// </summary>
public uvec3 yzy => new uvec3(y, z, y);
/// <summary>
/// Returns uvec3.gbg swizzling (equivalent to uvec3.yzy).
/// </summary>
public uvec3 gbg => new uvec3(y, z, y);
/// <summary>
/// Returns uvec3.yzyx swizzling.
/// </summary>
public uvec4 yzyx => new uvec4(y, z, y, x);
/// <summary>
/// Returns uvec3.gbgr swizzling (equivalent to uvec3.yzyx).
/// </summary>
public uvec4 gbgr => new uvec4(y, z, y, x);
/// <summary>
/// Returns uvec3.yzyy swizzling.
/// </summary>
public uvec4 yzyy => new uvec4(y, z, y, y);
/// <summary>
/// Returns uvec3.gbgg swizzling (equivalent to uvec3.yzyy).
/// </summary>
public uvec4 gbgg => new uvec4(y, z, y, y);
/// <summary>
/// Returns uvec3.yzyz swizzling.
/// </summary>
public uvec4 yzyz => new uvec4(y, z, y, z);
/// <summary>
/// Returns uvec3.gbgb swizzling (equivalent to uvec3.yzyz).
/// </summary>
public uvec4 gbgb => new uvec4(y, z, y, z);
/// <summary>
/// Returns uvec3.yzz swizzling.
/// </summary>
public uvec3 yzz => new uvec3(y, z, z);
/// <summary>
/// Returns uvec3.gbb swizzling (equivalent to uvec3.yzz).
/// </summary>
public uvec3 gbb => new uvec3(y, z, z);
/// <summary>
/// Returns uvec3.yzzx swizzling.
/// </summary>
public uvec4 yzzx => new uvec4(y, z, z, x);
/// <summary>
/// Returns uvec3.gbbr swizzling (equivalent to uvec3.yzzx).
/// </summary>
public uvec4 gbbr => new uvec4(y, z, z, x);
/// <summary>
/// Returns uvec3.yzzy swizzling.
/// </summary>
public uvec4 yzzy => new uvec4(y, z, z, y);
/// <summary>
/// Returns uvec3.gbbg swizzling (equivalent to uvec3.yzzy).
/// </summary>
public uvec4 gbbg => new uvec4(y, z, z, y);
/// <summary>
/// Returns uvec3.yzzz swizzling.
/// </summary>
public uvec4 yzzz => new uvec4(y, z, z, z);
/// <summary>
/// Returns uvec3.gbbb swizzling (equivalent to uvec3.yzzz).
/// </summary>
public uvec4 gbbb => new uvec4(y, z, z, z);
/// <summary>
/// Returns uvec3.zx swizzling.
/// </summary>
public uvec2 zx => new uvec2(z, x);
/// <summary>
/// Returns uvec3.br swizzling (equivalent to uvec3.zx).
/// </summary>
public uvec2 br => new uvec2(z, x);
/// <summary>
/// Returns uvec3.zxx swizzling.
/// </summary>
public uvec3 zxx => new uvec3(z, x, x);
/// <summary>
/// Returns uvec3.brr swizzling (equivalent to uvec3.zxx).
/// </summary>
public uvec3 brr => new uvec3(z, x, x);
/// <summary>
/// Returns uvec3.zxxx swizzling.
/// </summary>
public uvec4 zxxx => new uvec4(z, x, x, x);
/// <summary>
/// Returns uvec3.brrr swizzling (equivalent to uvec3.zxxx).
/// </summary>
public uvec4 brrr => new uvec4(z, x, x, x);
/// <summary>
/// Returns uvec3.zxxy swizzling.
/// </summary>
public uvec4 zxxy => new uvec4(z, x, x, y);
/// <summary>
/// Returns uvec3.brrg swizzling (equivalent to uvec3.zxxy).
/// </summary>
public uvec4 brrg => new uvec4(z, x, x, y);
/// <summary>
/// Returns uvec3.zxxz swizzling.
/// </summary>
public uvec4 zxxz => new uvec4(z, x, x, z);
/// <summary>
/// Returns uvec3.brrb swizzling (equivalent to uvec3.zxxz).
/// </summary>
public uvec4 brrb => new uvec4(z, x, x, z);
/// <summary>
/// Returns uvec3.zxy swizzling.
/// </summary>
public uvec3 zxy => new uvec3(z, x, y);
/// <summary>
/// Returns uvec3.brg swizzling (equivalent to uvec3.zxy).
/// </summary>
public uvec3 brg => new uvec3(z, x, y);
/// <summary>
/// Returns uvec3.zxyx swizzling.
/// </summary>
public uvec4 zxyx => new uvec4(z, x, y, x);
/// <summary>
/// Returns uvec3.brgr swizzling (equivalent to uvec3.zxyx).
/// </summary>
public uvec4 brgr => new uvec4(z, x, y, x);
/// <summary>
/// Returns uvec3.zxyy swizzling.
/// </summary>
public uvec4 zxyy => new uvec4(z, x, y, y);
/// <summary>
/// Returns uvec3.brgg swizzling (equivalent to uvec3.zxyy).
/// </summary>
public uvec4 brgg => new uvec4(z, x, y, y);
/// <summary>
/// Returns uvec3.zxyz swizzling.
/// </summary>
public uvec4 zxyz => new uvec4(z, x, y, z);
/// <summary>
/// Returns uvec3.brgb swizzling (equivalent to uvec3.zxyz).
/// </summary>
public uvec4 brgb => new uvec4(z, x, y, z);
/// <summary>
/// Returns uvec3.zxz swizzling.
/// </summary>
public uvec3 zxz => new uvec3(z, x, z);
/// <summary>
/// Returns uvec3.brb swizzling (equivalent to uvec3.zxz).
/// </summary>
public uvec3 brb => new uvec3(z, x, z);
/// <summary>
/// Returns uvec3.zxzx swizzling.
/// </summary>
public uvec4 zxzx => new uvec4(z, x, z, x);
/// <summary>
/// Returns uvec3.brbr swizzling (equivalent to uvec3.zxzx).
/// </summary>
public uvec4 brbr => new uvec4(z, x, z, x);
/// <summary>
/// Returns uvec3.zxzy swizzling.
/// </summary>
public uvec4 zxzy => new uvec4(z, x, z, y);
/// <summary>
/// Returns uvec3.brbg swizzling (equivalent to uvec3.zxzy).
/// </summary>
public uvec4 brbg => new uvec4(z, x, z, y);
/// <summary>
/// Returns uvec3.zxzz swizzling.
/// </summary>
public uvec4 zxzz => new uvec4(z, x, z, z);
/// <summary>
/// Returns uvec3.brbb swizzling (equivalent to uvec3.zxzz).
/// </summary>
public uvec4 brbb => new uvec4(z, x, z, z);
/// <summary>
/// Returns uvec3.zy swizzling.
/// </summary>
public uvec2 zy => new uvec2(z, y);
/// <summary>
/// Returns uvec3.bg swizzling (equivalent to uvec3.zy).
/// </summary>
public uvec2 bg => new uvec2(z, y);
/// <summary>
/// Returns uvec3.zyx swizzling.
/// </summary>
public uvec3 zyx => new uvec3(z, y, x);
/// <summary>
/// Returns uvec3.bgr swizzling (equivalent to uvec3.zyx).
/// </summary>
public uvec3 bgr => new uvec3(z, y, x);
/// <summary>
/// Returns uvec3.zyxx swizzling.
/// </summary>
public uvec4 zyxx => new uvec4(z, y, x, x);
/// <summary>
/// Returns uvec3.bgrr swizzling (equivalent to uvec3.zyxx).
/// </summary>
public uvec4 bgrr => new uvec4(z, y, x, x);
/// <summary>
/// Returns uvec3.zyxy swizzling.
/// </summary>
public uvec4 zyxy => new uvec4(z, y, x, y);
/// <summary>
/// Returns uvec3.bgrg swizzling (equivalent to uvec3.zyxy).
/// </summary>
public uvec4 bgrg => new uvec4(z, y, x, y);
/// <summary>
/// Returns uvec3.zyxz swizzling.
/// </summary>
public uvec4 zyxz => new uvec4(z, y, x, z);
/// <summary>
/// Returns uvec3.bgrb swizzling (equivalent to uvec3.zyxz).
/// </summary>
public uvec4 bgrb => new uvec4(z, y, x, z);
/// <summary>
/// Returns uvec3.zyy swizzling.
/// </summary>
public uvec3 zyy => new uvec3(z, y, y);
/// <summary>
/// Returns uvec3.bgg swizzling (equivalent to uvec3.zyy).
/// </summary>
public uvec3 bgg => new uvec3(z, y, y);
/// <summary>
/// Returns uvec3.zyyx swizzling.
/// </summary>
public uvec4 zyyx => new uvec4(z, y, y, x);
/// <summary>
/// Returns uvec3.bggr swizzling (equivalent to uvec3.zyyx).
/// </summary>
public uvec4 bggr => new uvec4(z, y, y, x);
/// <summary>
/// Returns uvec3.zyyy swizzling.
/// </summary>
public uvec4 zyyy => new uvec4(z, y, y, y);
/// <summary>
/// Returns uvec3.bggg swizzling (equivalent to uvec3.zyyy).
/// </summary>
public uvec4 bggg => new uvec4(z, y, y, y);
/// <summary>
/// Returns uvec3.zyyz swizzling.
/// </summary>
public uvec4 zyyz => new uvec4(z, y, y, z);
/// <summary>
/// Returns uvec3.bggb swizzling (equivalent to uvec3.zyyz).
/// </summary>
public uvec4 bggb => new uvec4(z, y, y, z);
/// <summary>
/// Returns uvec3.zyz swizzling.
/// </summary>
public uvec3 zyz => new uvec3(z, y, z);
/// <summary>
/// Returns uvec3.bgb swizzling (equivalent to uvec3.zyz).
/// </summary>
public uvec3 bgb => new uvec3(z, y, z);
/// <summary>
/// Returns uvec3.zyzx swizzling.
/// </summary>
public uvec4 zyzx => new uvec4(z, y, z, x);
/// <summary>
/// Returns uvec3.bgbr swizzling (equivalent to uvec3.zyzx).
/// </summary>
public uvec4 bgbr => new uvec4(z, y, z, x);
/// <summary>
/// Returns uvec3.zyzy swizzling.
/// </summary>
public uvec4 zyzy => new uvec4(z, y, z, y);
/// <summary>
/// Returns uvec3.bgbg swizzling (equivalent to uvec3.zyzy).
/// </summary>
public uvec4 bgbg => new uvec4(z, y, z, y);
/// <summary>
/// Returns uvec3.zyzz swizzling.
/// </summary>
public uvec4 zyzz => new uvec4(z, y, z, z);
/// <summary>
/// Returns uvec3.bgbb swizzling (equivalent to uvec3.zyzz).
/// </summary>
public uvec4 bgbb => new uvec4(z, y, z, z);
/// <summary>
/// Returns uvec3.zz swizzling.
/// </summary>
public uvec2 zz => new uvec2(z, z);
/// <summary>
/// Returns uvec3.bb swizzling (equivalent to uvec3.zz).
/// </summary>
public uvec2 bb => new uvec2(z, z);
/// <summary>
/// Returns uvec3.zzx swizzling.
/// </summary>
public uvec3 zzx => new uvec3(z, z, x);
/// <summary>
/// Returns uvec3.bbr swizzling (equivalent to uvec3.zzx).
/// </summary>
public uvec3 bbr => new uvec3(z, z, x);
/// <summary>
/// Returns uvec3.zzxx swizzling.
/// </summary>
public uvec4 zzxx => new uvec4(z, z, x, x);
/// <summary>
/// Returns uvec3.bbrr swizzling (equivalent to uvec3.zzxx).
/// </summary>
public uvec4 bbrr => new uvec4(z, z, x, x);
/// <summary>
/// Returns uvec3.zzxy swizzling.
/// </summary>
public uvec4 zzxy => new uvec4(z, z, x, y);
/// <summary>
/// Returns uvec3.bbrg swizzling (equivalent to uvec3.zzxy).
/// </summary>
public uvec4 bbrg => new uvec4(z, z, x, y);
/// <summary>
/// Returns uvec3.zzxz swizzling.
/// </summary>
public uvec4 zzxz => new uvec4(z, z, x, z);
/// <summary>
/// Returns uvec3.bbrb swizzling (equivalent to uvec3.zzxz).
/// </summary>
public uvec4 bbrb => new uvec4(z, z, x, z);
/// <summary>
/// Returns uvec3.zzy swizzling.
/// </summary>
public uvec3 zzy => new uvec3(z, z, y);
/// <summary>
/// Returns uvec3.bbg swizzling (equivalent to uvec3.zzy).
/// </summary>
public uvec3 bbg => new uvec3(z, z, y);
/// <summary>
/// Returns uvec3.zzyx swizzling.
/// </summary>
public uvec4 zzyx => new uvec4(z, z, y, x);
/// <summary>
/// Returns uvec3.bbgr swizzling (equivalent to uvec3.zzyx).
/// </summary>
public uvec4 bbgr => new uvec4(z, z, y, x);
/// <summary>
/// Returns uvec3.zzyy swizzling.
/// </summary>
public uvec4 zzyy => new uvec4(z, z, y, y);
/// <summary>
/// Returns uvec3.bbgg swizzling (equivalent to uvec3.zzyy).
/// </summary>
public uvec4 bbgg => new uvec4(z, z, y, y);
/// <summary>
/// Returns uvec3.zzyz swizzling.
/// </summary>
public uvec4 zzyz => new uvec4(z, z, y, z);
/// <summary>
/// Returns uvec3.bbgb swizzling (equivalent to uvec3.zzyz).
/// </summary>
public uvec4 bbgb => new uvec4(z, z, y, z);
/// <summary>
/// Returns uvec3.zzz swizzling.
/// </summary>
public uvec3 zzz => new uvec3(z, z, z);
/// <summary>
/// Returns uvec3.bbb swizzling (equivalent to uvec3.zzz).
/// </summary>
public uvec3 bbb => new uvec3(z, z, z);
/// <summary>
/// Returns uvec3.zzzx swizzling.
/// </summary>
public uvec4 zzzx => new uvec4(z, z, z, x);
/// <summary>
/// Returns uvec3.bbbr swizzling (equivalent to uvec3.zzzx).
/// </summary>
public uvec4 bbbr => new uvec4(z, z, z, x);
/// <summary>
/// Returns uvec3.zzzy swizzling.
/// </summary>
public uvec4 zzzy => new uvec4(z, z, z, y);
/// <summary>
/// Returns uvec3.bbbg swizzling (equivalent to uvec3.zzzy).
/// </summary>
public uvec4 bbbg => new uvec4(z, z, z, y);
/// <summary>
/// Returns uvec3.zzzz swizzling.
/// </summary>
public uvec4 zzzz => new uvec4(z, z, z, z);
/// <summary>
/// Returns uvec3.bbbb swizzling (equivalent to uvec3.zzzz).
/// </summary>
public uvec4 bbbb => new uvec4(z, z, z, z);
#endregion
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudioTools.Project.Automation {
/// <summary>
/// Contains all of the properties of a given object that are contained in a generic collection of properties.
/// </summary>
[ComVisible(true)]
public class OAProperties : EnvDTE.Properties {
private NodeProperties target;
private Dictionary<string, EnvDTE.Property> properties = new Dictionary<string, EnvDTE.Property>();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public OAProperties(NodeProperties target) {
Utilities.ArgumentNotNull("target", target);
this.target = target;
this.AddPropertiesFromType(target.GetType());
}
/// <summary>
/// Defines the NodeProperties object that contains the defines the properties.
/// </summary>
public NodeProperties Target {
get {
return this.target;
}
}
#region EnvDTE.Properties
/// <summary>
/// Microsoft Internal Use Only.
/// </summary>
public virtual object Application {
get { return null; }
}
/// <summary>
/// Gets a value indicating the number of objects in the collection.
/// </summary>
public int Count {
get { return properties.Count; }
}
/// <summary>
/// Gets the top-level extensibility object.
/// </summary>
public virtual EnvDTE.DTE DTE {
get {
if (this.target.HierarchyNode == null || this.target.HierarchyNode.ProjectMgr == null || this.target.HierarchyNode.ProjectMgr.IsClosed ||
this.target.HierarchyNode.ProjectMgr.Site == null) {
throw new InvalidOperationException();
}
return this.target.HierarchyNode.ProjectMgr.Site.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
}
}
/// <summary>
/// Gets an enumeration for items in a collection.
/// </summary>
/// <returns>An enumerator. </returns>
public IEnumerator GetEnumerator() {
if (this.properties.Count == 0) {
yield return new OANullProperty(this);
}
IEnumerator enumerator = this.properties.Values.GetEnumerator();
while (enumerator.MoveNext()) {
yield return enumerator.Current;
}
}
/// <summary>
/// Returns an indexed member of a Properties collection.
/// </summary>
/// <param name="index">The index at which to return a member.</param>
/// <returns>A Property object.</returns>
public virtual EnvDTE.Property Item(object index) {
if (index is string) {
string indexAsString = (string)index;
if (this.properties.ContainsKey(indexAsString)) {
return this.properties[indexAsString];
}
} else if (index is int) {
int realIndex = (int)index - 1;
if (realIndex >= 0 && realIndex < this.properties.Count) {
IEnumerator enumerator = this.properties.Values.GetEnumerator();
int i = 0;
while (enumerator.MoveNext()) {
if (i++ == realIndex) {
return (EnvDTE.Property)enumerator.Current;
}
}
}
}
throw new ArgumentException(SR.GetString(SR.InvalidParameter), "index");
}
/// <summary>
/// Gets the immediate parent object of a Properties collection.
/// </summary>
public virtual object Parent {
get { return null; }
}
#endregion
#region methods
/// <summary>
/// Add properties to the collection of properties filtering only those properties which are com-visible and AutomationBrowsable
/// </summary>
/// <param name="targetType">The type of NodeProperties the we should filter on</param>
private void AddPropertiesFromType(Type targetType) {
Utilities.ArgumentNotNull("targetType", targetType);
// If the type is not COM visible, we do not expose any of the properties
if (!IsComVisible(targetType)) {
return;
}
// Add all properties being ComVisible and AutomationVisible
PropertyInfo[] propertyInfos = targetType.GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos) {
if (!IsInMap(propertyInfo) && IsComVisible(propertyInfo) && IsAutomationVisible(propertyInfo)) {
AddProperty(propertyInfo);
}
}
}
#endregion
#region virtual methods
/// <summary>
/// Creates a new OAProperty object and adds it to the current list of properties
/// </summary>
/// <param name="propertyInfo">The property to be associated with an OAProperty object</param>
private void AddProperty(PropertyInfo propertyInfo) {
var attrs = propertyInfo.GetCustomAttributes(typeof(PropertyNameAttribute), false);
string name = propertyInfo.Name;
if (attrs.Length > 0) {
name = ((PropertyNameAttribute)attrs[0]).Name;
}
this.properties.Add(name, new OAProperty(this, propertyInfo));
}
#endregion
#region helper methods
private bool IsInMap(PropertyInfo propertyInfo) {
return this.properties.ContainsKey(propertyInfo.Name);
}
private static bool IsAutomationVisible(PropertyInfo propertyInfo) {
object[] customAttributesOnProperty = propertyInfo.GetCustomAttributes(typeof(AutomationBrowsableAttribute), true);
foreach (AutomationBrowsableAttribute attr in customAttributesOnProperty) {
if (!attr.Browsable) {
return false;
}
}
return true;
}
private static bool IsComVisible(Type targetType) {
object[] customAttributesOnProperty = targetType.GetCustomAttributes(typeof(ComVisibleAttribute), true);
foreach (ComVisibleAttribute attr in customAttributesOnProperty) {
if (!attr.Value) {
return false;
}
}
return true;
}
private static bool IsComVisible(PropertyInfo propertyInfo) {
object[] customAttributesOnProperty = propertyInfo.GetCustomAttributes(typeof(ComVisibleAttribute), true);
foreach (ComVisibleAttribute attr in customAttributesOnProperty) {
if (!attr.Value) {
return false;
}
}
return true;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
static class CSharpCompilationOptionsExtensions
{
[Fact]
public void WithModuleName()
{
// ModuleName
Assert.Equal(null, TestOptions.ReleaseDll.WithModuleName(null).ModuleName);
TestOptions.ReleaseDll.WithModuleName("").VerifyErrors(
// error CS7087: Name cannot be empty.
// Parameter name: ModuleName
Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(
@"Name cannot be empty.
Parameter name: ModuleName"
));
TestOptions.ReleaseDll.WithModuleName("a\0a").VerifyErrors(
// error CS7087: Name contains invalid characters.
// Parameter name: ModuleName
Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(new ArgumentException(CodeAnalysisResources.NameCannotBeEmpty, "ModuleName").Message));
TestOptions.ReleaseDll.WithModuleName("a\uD800b").VerifyErrors(
// error CS7087: Name contains invalid characters.
// Parameter name: ModuleName
Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(new ArgumentException(CodeAnalysisResources.NameCannotBeEmpty, "ModuleName").Message));
TestOptions.ReleaseDll.WithModuleName("a\\b").VerifyErrors(
// error CS7087: Name contains invalid characters.
// Parameter name: ModuleName
Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters.
Parameter name: ModuleName")
);
TestOptions.ReleaseDll.WithModuleName("a/b").VerifyErrors(
// error CS7087: Name contains invalid characters.
// Parameter name: ModuleName
Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters.
Parameter name: ModuleName")
);
TestOptions.ReleaseDll.WithModuleName("a:b").VerifyErrors(
// error CS7087: Name contains invalid characters.
// Parameter name: ModuleName
Diagnostic(ErrorCode.ERR_BadCompilationOption).WithArguments(@"Name contains invalid characters.
Parameter name: ModuleName")
);
}
public static void VerifyErrors(this CSharpCompilationOptions options, params DiagnosticDescription[] expected)
{
options.Errors.Verify(expected);
}
}
public class CSharpCompilationOptionsTests : CSharpTestBase
{
private void TestProperty<T>(
Func<CSharpCompilationOptions, T, CSharpCompilationOptions> factory,
Func<CSharpCompilationOptions, T> getter,
T validNonDefaultValue)
{
var oldOpt1 = new CSharpCompilationOptions(OutputKind.ConsoleApplication);
var validDefaultValue = getter(oldOpt1);
// we need non-default value to test Equals and GetHashCode
Assert.NotEqual(validNonDefaultValue, validDefaultValue);
// check that the assigned value can be read:
var newOpt1 = factory(oldOpt1, validNonDefaultValue);
Assert.Equal(validNonDefaultValue, getter(newOpt1));
Assert.Equal(0, newOpt1.Errors.Length);
// check that creating new options with the same value yields the same options instance:
var newOpt1_alias = factory(newOpt1, validNonDefaultValue);
Assert.Same(newOpt1_alias, newOpt1);
// check that Equals and GetHashCode work
var newOpt2 = factory(oldOpt1, validNonDefaultValue);
Assert.False(newOpt1.Equals(oldOpt1));
Assert.True(newOpt1.Equals(newOpt2));
Assert.Equal(newOpt1.GetHashCode(), newOpt2.GetHashCode());
// test default(T):
Assert.NotNull(factory(oldOpt1, default(T)));
}
[Fact]
public void Invariants()
{
TestProperty((old, value) => old.WithOutputKind(value), opt => opt.OutputKind, OutputKind.DynamicallyLinkedLibrary);
TestProperty((old, value) => old.WithModuleName(value), opt => opt.ModuleName, "foo.dll");
TestProperty((old, value) => old.WithMainTypeName(value), opt => opt.MainTypeName, "Foo.Bar");
TestProperty((old, value) => old.WithScriptClassName(value), opt => opt.ScriptClassName, "<Script>");
TestProperty((old, value) => old.WithUsings(value), opt => opt.Usings, ImmutableArray.Create("A", "B"));
TestProperty((old, value) => old.WithOptimizationLevel(value), opt => opt.OptimizationLevel, OptimizationLevel.Release);
TestProperty((old, value) => old.WithOverflowChecks(value), opt => opt.CheckOverflow, true);
TestProperty((old, value) => old.WithAllowUnsafe(value), opt => opt.AllowUnsafe, true);
TestProperty((old, value) => old.WithCryptoKeyContainer(value), opt => opt.CryptoKeyContainer, "foo");
TestProperty((old, value) => old.WithCryptoKeyFile(value), opt => opt.CryptoKeyFile, "foo");
TestProperty((old, value) => old.WithDelaySign(value), opt => opt.DelaySign, true);
TestProperty((old, value) => old.WithPlatform(value), opt => opt.Platform, Platform.Itanium);
TestProperty((old, value) => old.WithGeneralDiagnosticOption(value), opt => opt.GeneralDiagnosticOption, ReportDiagnostic.Suppress);
TestProperty((old, value) => old.WithWarningLevel(value), opt => opt.WarningLevel, 3);
TestProperty((old, value) => old.WithSpecificDiagnosticOptions(value), opt => opt.SpecificDiagnosticOptions,
new Dictionary<string, ReportDiagnostic> { { "CS0001", ReportDiagnostic.Error } }.ToImmutableDictionary());
TestProperty((old, value) => old.WithConcurrentBuild(value), opt => opt.ConcurrentBuild, false);
TestProperty((old, value) => old.WithExtendedCustomDebugInformation(value), opt => opt.ExtendedCustomDebugInformation, false);
TestProperty((old, value) => old.WithXmlReferenceResolver(value), opt => opt.XmlReferenceResolver, new XmlFileResolver(null));
TestProperty((old, value) => old.WithMetadataReferenceResolver(value), opt => opt.MetadataReferenceResolver, new AssemblyReferenceResolver(new MetadataFileReferenceResolver(new string[0], null), new MetadataFileReferenceProvider()));
TestProperty((old, value) => old.WithAssemblyIdentityComparer(value), opt => opt.AssemblyIdentityComparer, new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy()));
TestProperty((old, value) => old.WithStrongNameProvider(value), opt => opt.StrongNameProvider, new DesktopStrongNameProvider());
}
[Fact]
public void WithXxx()
{
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName(null).VerifyErrors(
// error CS7088: Invalid 'ScriptClassName' value: 'null'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "null"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName("blah\0foo").VerifyErrors(
// error CS7088: Invalid 'ScriptClassName' value: 'blah\0foo'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "blah\0foo"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithScriptClassName("").VerifyErrors(
// error CS7088: Invalid 'ScriptClassName' value: ''.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", ""));
Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName(null).Errors.Length);
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName("blah\0foo").VerifyErrors(
// error CS7088: Invalid 'MainTypeName' value: 'blah\0foo'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "blah\0foo"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithMainTypeName("").VerifyErrors(
// error CS7088: Invalid 'MainTypeName' value: ''.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", ""));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOutputKind((OutputKind)Int32.MaxValue).VerifyErrors(
// error CS7088: Invalid 'OutputKind' value: 'Int32.MaxValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MaxValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOutputKind((OutputKind)Int32.MinValue).VerifyErrors(
// error CS7088: Invalid 'OutputKind' value: 'Int32.MinValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MinValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel((OptimizationLevel)Int32.MaxValue).VerifyErrors(
// error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MaxValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MaxValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithOptimizationLevel((OptimizationLevel)Int32.MinValue).VerifyErrors(
// error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MinValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MinValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithPlatform((Platform)Int32.MaxValue).VerifyErrors(
// error CS1672: Invalid option 'Int32.MaxValue' for /platform; must be anycpu, x86, Itanium or x64
Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MaxValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithPlatform((Platform)Int32.MinValue).VerifyErrors(
// error CS1672: Invalid option 'Int32.MinValue' for /platform; must be anycpu, x86, Itanium or x64
Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MinValue.ToString()));
var defaultWarnings = new CSharpCompilationOptions(OutputKind.ConsoleApplication);
Assert.Equal(ReportDiagnostic.Default, defaultWarnings.GeneralDiagnosticOption);
Assert.Equal(4, defaultWarnings.WarningLevel);
Assert.Equal(ReportDiagnostic.Error, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithGeneralDiagnosticOption(ReportDiagnostic.Error).GeneralDiagnosticOption);
Assert.Equal(ReportDiagnostic.Default, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithGeneralDiagnosticOption(ReportDiagnostic.Default).GeneralDiagnosticOption);
}
[Fact]
public void WithUsings()
{
var actual1 = new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new[] { "A", "B" }).Usings;
Assert.True(actual1.SequenceEqual(new[] { "A", "B" }));
var actual2 = new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(Enumerable.Repeat("A", 1)).Usings;
Assert.True(actual2.SequenceEqual(Enumerable.Repeat("A", 1)));
Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("A", "B").WithUsings(null).Usings.Count());
Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("A", "B").WithUsings((string[])null).Usings.Count());
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { null }).VerifyErrors(
// error CS7088: Invalid 'Usings' value: 'null'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "null"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { "" }).VerifyErrors(
// error CS7088: Invalid 'Usings' value: ''.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", ""));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings(new string[] { "blah\0foo" }).VerifyErrors(
// error CS7088: Invalid 'Usings' value: 'blah\0foo'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "blah\0foo"));
}
[Fact]
public void WithWarnings()
{
var warnings = new Dictionary<string, ReportDiagnostic>
{
{ MessageProvider.Instance.GetIdForErrorCode(1), ReportDiagnostic.Error },
{ MessageProvider.Instance.GetIdForErrorCode(2), ReportDiagnostic.Suppress },
{ MessageProvider.Instance.GetIdForErrorCode(3), ReportDiagnostic.Warn }
};
Assert.Equal(3, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithSpecificDiagnosticOptions(warnings).SpecificDiagnosticOptions.Count);
Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithSpecificDiagnosticOptions(null).SpecificDiagnosticOptions.Count);
Assert.Equal(1, new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(1).WarningLevel);
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(-1).VerifyErrors(
// error CS7088: Invalid 'WarningLevel' value: '-1'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "-1"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithWarningLevel(5).VerifyErrors(
// error CS7088: Invalid 'WarningLevel' value: '5'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "5"));
}
[Fact]
public void ConstructorValidation()
{
new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { null }).VerifyErrors(
// error CS7088: Invalid 'Usings' value: 'null'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "null"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { "" }).VerifyErrors(
// error CS7088: Invalid 'Usings' value: ''.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", ""));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, usings: new string[] { "blah\0foo" }).VerifyErrors(
// error CS7088: Invalid 'Usings' value: 'blah\0foo'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("Usings", "blah\0foo"));
Assert.Equal("Script", new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: null).ScriptClassName);
new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: "blah\0foo").VerifyErrors(
// error CS7088: Invalid 'ScriptClassName' value: 'blah\0foo'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", "blah\0foo"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, scriptClassName: "").VerifyErrors(
// error CS7088: Invalid 'ScriptClassName' value: ''.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("ScriptClassName", ""));
Assert.Equal(0, new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: null).Errors.Length);
new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: "blah\0foo").VerifyErrors(
// error CS7088: Invalid 'MainTypeName' value: 'blah\0foo'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", "blah\0foo"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, mainTypeName: "").VerifyErrors(
// error CS7088: Invalid 'MainTypeName' value: ''.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("MainTypeName", ""));
new CSharpCompilationOptions(outputKind: (OutputKind)Int32.MaxValue).VerifyErrors(
// error CS7088: Invalid 'OutputKind' value: 'Int32.MaxValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MaxValue.ToString()));
new CSharpCompilationOptions(outputKind: (OutputKind)Int32.MinValue).VerifyErrors(
// error CS7088: Invalid 'OutputKind' value: 'Int32.MinValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OutputKind", Int32.MinValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: (OptimizationLevel)Int32.MaxValue).VerifyErrors(
// error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MaxValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MaxValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel: (OptimizationLevel)Int32.MinValue).VerifyErrors(
// error CS7088: Invalid 'OptimizationLevel' value: 'Int32.MinValue'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("OptimizationLevel", Int32.MinValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, platform: (Platform)Int32.MinValue).VerifyErrors(
// error CS1672: Invalid option 'Int32.MinValue' for /platform; must be anycpu, x86, Itanium or x64
Diagnostic(ErrorCode.ERR_BadPlatformType).WithArguments(Int32.MinValue.ToString()));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, warningLevel: -1).VerifyErrors(
// error CS7088: Invalid 'WarningLevel' value: '-1'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "-1"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, warningLevel: 5).VerifyErrors(
// error CS7088: Invalid 'WarningLevel' value: '5'.
Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("WarningLevel", "5"));
new CSharpCompilationOptions(OutputKind.ConsoleApplication, platform: Platform.AnyCpu32BitPreferred).VerifyErrors();
new CSharpCompilationOptions(OutputKind.WindowsRuntimeApplication, platform: Platform.AnyCpu32BitPreferred).VerifyErrors();
new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata, platform: Platform.AnyCpu32BitPreferred).VerifyErrors(
Diagnostic(ErrorCode.ERR_BadPrefer32OnLib));
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, platform: Platform.AnyCpu32BitPreferred).VerifyErrors(
Diagnostic(ErrorCode.ERR_BadPrefer32OnLib));
}
/// <summary>
/// If this test fails, please update the <see cref="CSharpCompilationOptions.GetHashCode"/>
/// and <see cref="CSharpCompilationOptions.Equals(CSharpCompilationOptions)"/> methods to
/// make sure they are doing the right thing with your new field and then update the baseline
/// here.
/// </summary>
[Fact]
public void TestFieldsForEqualsAndGetHashCode()
{
ReflectionAssert.AssertPublicAndInternalFieldsAndProperties(
typeof(CSharpCompilationOptions),
"AllowUnsafe",
"Usings");
}
[Fact]
public void TestEqualitySemantics()
{
Assert.Equal(CreateCSharpCompilationOptions(), CreateCSharpCompilationOptions());
}
private static CSharpCompilationOptions CreateCSharpCompilationOptions()
{
string moduleName = null;
string mainTypeName = null;
string scriptClassName = null;
IEnumerable<string> usings = null;
OptimizationLevel optimizationLevel = OptimizationLevel.Debug;
bool checkOverflow = false;
bool allowUnsafe = false;
string cryptoKeyContainer = null;
string cryptoKeyFile = null;
bool? delaySign = null;
Platform platform = 0;
ReportDiagnostic generalDiagnosticOption = 0;
int warningLevel = 0;
IEnumerable<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptions = null;
bool concurrentBuild = false;
bool extendedCustomDebugInformation = true;
XmlReferenceResolver xmlReferenceResolver = new XmlFileResolver(null);
SourceReferenceResolver sourceReferenceResolver = new SourceFileResolver(ImmutableArray<string>.Empty, null);
MetadataReferenceResolver metadataReferenceResolver = new AssemblyReferenceResolver(new MetadataFileReferenceResolver(ImmutableArray<string>.Empty, null), MetadataFileReferenceProvider.Default);
AssemblyIdentityComparer assemblyIdentityComparer = AssemblyIdentityComparer.Default; // Currently uses reference equality
StrongNameProvider strongNameProvider = new DesktopStrongNameProvider();
MetadataImportOptions metadataImportOptions = 0;
ImmutableArray<string> features = ImmutableArray<string>.Empty;
return new CSharpCompilationOptions(OutputKind.ConsoleApplication, moduleName, mainTypeName, scriptClassName, usings,
optimizationLevel, checkOverflow, allowUnsafe, cryptoKeyContainer, cryptoKeyFile, delaySign,
platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions,
concurrentBuild, extendedCustomDebugInformation, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver,
assemblyIdentityComparer, strongNameProvider, metadataImportOptions, features);
}
[Fact]
public void Serializability1()
{
VerifySerializability(new CSharpSerializableCompilationOptions(new CSharpCompilationOptions(
outputKind: OutputKind.WindowsApplication,
usings: new[] { "F", "G" },
generalDiagnosticOption: ReportDiagnostic.Hidden,
specificDiagnosticOptions: new[] { KeyValuePair.Create("CS0001", ReportDiagnostic.Suppress) })));
}
[Fact]
public void Serializability2()
{
var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp3, DocumentationMode.Diagnose, SourceCodeKind.Interactive);
var compilationOptions = new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
moduleName: "M",
optimizationLevel: OptimizationLevel.Release);
compilationOptions = compilationOptions.
WithConcurrentBuild(!compilationOptions.ConcurrentBuild).
WithExtendedCustomDebugInformation(!compilationOptions.ExtendedCustomDebugInformation);
var deserializedCompilationOptions = VerifySerializability(new CSharpSerializableCompilationOptions(compilationOptions)).Options;
Assert.Equal(compilationOptions.OutputKind, deserializedCompilationOptions.OutputKind);
Assert.Equal(compilationOptions.ModuleName, deserializedCompilationOptions.ModuleName);
Assert.Equal(compilationOptions.OptimizationLevel, deserializedCompilationOptions.OptimizationLevel);
Assert.Equal(compilationOptions.ConcurrentBuild, deserializedCompilationOptions.ConcurrentBuild);
Assert.Equal(compilationOptions.ExtendedCustomDebugInformation, deserializedCompilationOptions.ExtendedCustomDebugInformation);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace DraftSimulator.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// 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.Linq;
using Internal.Metadata.NativeFormat.Writer;
using ILCompiler.Metadata;
using Cts = Internal.TypeSystem;
using Xunit;
#pragma warning disable xUnit2013 // Do not use Assert.Equal() to check for collection size
namespace MetadataTransformTests
{
public class SimpleTests
{
private TestTypeSystemContext _context;
private Cts.Ecma.EcmaModule _systemModule;
public SimpleTests()
{
_context = new TestTypeSystemContext();
_systemModule = _context.CreateModuleForSimpleName("PrimaryMetadataAssembly");
_context.SetSystemModule(_systemModule);
}
[Fact]
public void TestAllTypes()
{
var policy = new SingleFileMetadataPolicy();
var transformResult = MetadataTransform.Run(policy, new[] { _systemModule });
Assert.Equal(1, transformResult.Scopes.Count());
Assert.Equal(
_systemModule.GetAllTypes().Count(x => !policy.IsBlocked(x)),
transformResult.Scopes.Single().GetAllTypes().Count());
}
[Fact]
public void TestBlockedInterface()
{
// __ComObject implements ICastable, which is a metadata blocked type and should not show
// up in the __ComObject interface list.
var policy = new SingleFileMetadataPolicy();
var transformResult = MetadataTransform.Run(policy, new[] { _systemModule });
Cts.MetadataType icastable = _systemModule.GetType("System.Private.CompilerServices", "ICastable");
Cts.MetadataType comObject = _systemModule.GetType("System", "__ComObject");
Assert.Equal(1, comObject.ExplicitlyImplementedInterfaces.Length);
Assert.Equal(icastable, comObject.ExplicitlyImplementedInterfaces[0]);
Assert.Null(transformResult.GetTransformedTypeDefinition(icastable));
Assert.Null(transformResult.GetTransformedTypeReference(icastable));
TypeDefinition comObjectRecord = transformResult.GetTransformedTypeDefinition(comObject);
Assert.NotNull(comObjectRecord);
Assert.Equal(comObject.Name, comObjectRecord.Name.Value);
Assert.Equal(0, comObjectRecord.Interfaces.Count);
}
[Fact]
public void TestStandaloneSignatureGeneration()
{
var transformResult = MetadataTransform.Run(new SingleFileMetadataPolicy(), new[] { _systemModule });
var stringRecord = transformResult.GetTransformedTypeDefinition(
(Cts.MetadataType)_context.GetWellKnownType(Cts.WellKnownType.String));
var singleRecord = transformResult.GetTransformedTypeDefinition(
(Cts.MetadataType)_context.GetWellKnownType(Cts.WellKnownType.Single));
var sig = new Cts.MethodSignature(
0, 0, _context.GetWellKnownType(Cts.WellKnownType.String),
new[] { _context.GetWellKnownType(Cts.WellKnownType.Single) });
var sigRecord = transformResult.Transform.HandleMethodSignature(sig);
// Verify the signature is connected to the existing transformResult world
Assert.Same(stringRecord, sigRecord.ReturnType);
Assert.Equal(1, sigRecord.Parameters.Count);
Assert.Same(singleRecord, sigRecord.Parameters[0]);
}
[Fact]
public void TestSampleMetadataGeneration()
{
var policy = new SingleFileMetadataPolicy();
var sampleMetadataModule = _context.GetModuleForSimpleName("SampleMetadataAssembly");
var transformResult = MetadataTransform.Run(policy,
new[] { _systemModule, sampleMetadataModule });
Assert.Equal(2, transformResult.Scopes.Count);
var systemScope = transformResult.Scopes.Single(s => s.Name.Value == "PrimaryMetadataAssembly");
var sampleScope = transformResult.Scopes.Single(s => s.Name.Value == "SampleMetadataAssembly");
Assert.Equal(_systemModule.GetAllTypes().Count(t => !policy.IsBlocked(t)), systemScope.GetAllTypes().Count());
Assert.Equal(sampleMetadataModule.GetAllTypes().Count(t => !policy.IsBlocked(t)), sampleScope.GetAllTypes().Count());
// TODO: check individual types
}
[Fact]
public void TestMultifileSanity()
{
var sampleMetadataModule = _context.GetModuleForSimpleName("SampleMetadataAssembly");
var policy = new MultifileMetadataPolicy(sampleMetadataModule);
var transformResult = MetadataTransform.Run(policy,
new[] { _systemModule, sampleMetadataModule });
Assert.Equal(1, transformResult.Scopes.Count);
var sampleScope = transformResult.Scopes.Single();
Assert.Equal(sampleMetadataModule.GetAllTypes().Count(t => !policy.IsBlocked(t)), sampleScope.GetAllTypes().Count());
var objectType = (Cts.MetadataType)_context.GetWellKnownType(Cts.WellKnownType.Object);
var objectRecord = transformResult.GetTransformedTypeReference(objectType);
Assert.Equal("Object", objectRecord.TypeName.Value);
var stringType = (Cts.MetadataType)_context.GetWellKnownType(Cts.WellKnownType.String);
var stringRecord = transformResult.GetTransformedTypeReference(stringType);
Assert.Equal("String", stringRecord.TypeName.Value);
Assert.Same(objectRecord.ParentNamespaceOrType, stringRecord.ParentNamespaceOrType);
Assert.IsType<NamespaceReference>(objectRecord.ParentNamespaceOrType);
var parentNamespace = objectRecord.ParentNamespaceOrType as NamespaceReference;
Assert.Equal("System", parentNamespace.Name.Value);
Assert.Null(transformResult.GetTransformedTypeDefinition(objectType));
Assert.Null(transformResult.GetTransformedTypeDefinition(stringType));
}
[Fact]
public void TestNestedTypeReference()
{
// A type reference nested under a type that has a definition record. The transform is required
// to create a type reference for the containing type because a type *definition* can't be a parent
// to a type *reference*.
var sampleMetadataModule = _context.GetModuleForSimpleName("SampleMetadataAssembly");
Cts.MetadataType genericOutside = sampleMetadataModule.GetType("SampleMetadata", "GenericOutside`1");
Cts.MetadataType inside = genericOutside.GetNestedType("Inside");
{
MockPolicy policy = new MockPolicy(
type =>
{
return type == genericOutside;
});
var result = MetadataTransform.Run(policy, new[] { sampleMetadataModule });
Assert.Equal(1, result.Scopes.Count);
Assert.Equal(1, result.Scopes.Single().GetAllTypes().Count());
var genericOutsideDefRecord = result.GetTransformedTypeDefinition(genericOutside);
Assert.NotNull(genericOutsideDefRecord);
Assert.Null(result.GetTransformedTypeReference(inside));
var insideRecord = result.Transform.HandleType(inside);
Assert.IsType<TypeReference>(insideRecord);
var genericOutsideRefRecord = ((TypeReference)insideRecord).ParentNamespaceOrType as TypeReference;
Assert.NotNull(genericOutsideRefRecord);
Assert.Equal(genericOutside.Name, genericOutsideRefRecord.TypeName.Value);
Assert.Same(genericOutsideDefRecord, result.GetTransformedTypeDefinition(genericOutside));
}
}
[Fact]
public void TestBlockedAttributes()
{
// Test that custom attributes referring to blocked types don't show up in metadata
var sampleMetadataModule = _context.GetModuleForSimpleName("SampleMetadataAssembly");
Cts.MetadataType attributeHolder = sampleMetadataModule.GetType("BlockedMetadata", "AttributeHolder");
var policy = new SingleFileMetadataPolicy();
var transformResult = MetadataTransform.Run(policy,
new[] { _systemModule, sampleMetadataModule });
int blockedCount = 0;
int allowedCount = 0;
foreach (var field in attributeHolder.GetFields())
{
var transformedRecord = transformResult.GetTransformedFieldDefinition(field);
Assert.NotNull(transformedRecord);
if (field.Name.StartsWith("Blocked"))
{
blockedCount++;
Assert.Equal(0, transformedRecord.CustomAttributes.Count);
}
else
{
allowedCount++;
Assert.StartsWith("Allowed", field.Name);
Assert.Equal(1, transformedRecord.CustomAttributes.Count);
}
}
Assert.Equal(5, allowedCount);
Assert.Equal(8, blockedCount);
}
[Fact]
public void TestMethodImplMetadata()
{
// Test that custom attributes referring to blocked types don't show up in metadata
var sampleMetadataModule = _context.GetModuleForSimpleName("SampleMetadataAssembly");
Cts.MetadataType iCloneable = sampleMetadataModule.GetType("SampleMetadataMethodImpl", "ICloneable");
Cts.MetadataType implementsICloneable = sampleMetadataModule.GetType("SampleMetadataMethodImpl", "ImplementsICloneable");
Cts.MethodDesc iCloneableDotClone = iCloneable.GetMethod("Clone", null);
Cts.MethodDesc iCloneableImplementation = implementsICloneable.GetMethod("SampleMetadataMethodImpl.ICloneable.Clone", null);
Cts.MethodDesc iCloneableDotGenericClone = iCloneable.GetMethod("GenericClone", null);
Cts.MethodDesc iCloneableGenericImplementation = implementsICloneable.GetMethod("SampleMetadataMethodImpl.ICloneable.GenericClone", null);
var policy = new SingleFileMetadataPolicy();
var transformResult = MetadataTransform.Run(policy,
new[] { _systemModule, sampleMetadataModule });
var iCloneableType = transformResult.GetTransformedTypeDefinition(iCloneable);
var implementsICloneableType = transformResult.GetTransformedTypeDefinition(implementsICloneable);
Assert.Equal(2, implementsICloneableType.MethodImpls.Count);
// non-generic MethodImpl
Method iCloneableDotCloneMethod = transformResult.GetTransformedMethodDefinition(iCloneableDotClone);
Method iCloneableImplementationMethod = transformResult.GetTransformedMethodDefinition(iCloneableImplementation);
QualifiedMethod methodImplMethodDecl = (QualifiedMethod)implementsICloneableType.MethodImpls[0].MethodDeclaration;
QualifiedMethod methodImplMethodBody = (QualifiedMethod)implementsICloneableType.MethodImpls[0].MethodBody;
Assert.Equal(iCloneableDotCloneMethod, methodImplMethodDecl.Method);
Assert.Equal(iCloneableType, methodImplMethodDecl.EnclosingType);
Assert.Equal(iCloneableImplementationMethod, methodImplMethodBody.Method);
Assert.Equal(implementsICloneableType, methodImplMethodBody.EnclosingType);
// generic MethodImpl
Method iCloneableDotGenericCloneMethod = transformResult.GetTransformedMethodDefinition(iCloneableDotGenericClone);
Method iCloneableGenericImplementationMethod = transformResult.GetTransformedMethodDefinition(iCloneableGenericImplementation);
QualifiedMethod methodImplGenericMethodDecl = (QualifiedMethod)implementsICloneableType.MethodImpls[1].MethodDeclaration;
QualifiedMethod methodImplGenericMethodBody = (QualifiedMethod)implementsICloneableType.MethodImpls[1].MethodBody;
Assert.Equal(iCloneableDotGenericCloneMethod, methodImplGenericMethodDecl.Method);
Assert.Equal(iCloneableType, methodImplGenericMethodDecl.EnclosingType);
Assert.Equal(iCloneableGenericImplementationMethod, methodImplGenericMethodBody.Method);
Assert.Equal(implementsICloneableType, methodImplGenericMethodBody.EnclosingType);
}
[Fact]
public void TestFunctionPointerSignatures()
{
var ilModule = _context.GetModuleForSimpleName("ILMetadataAssembly");
Cts.MetadataType typeWithFunctionPointers = ilModule.GetType("SampleMetadata", "TypeWithFunctionPointers");
var policy = new SingleFileMetadataPolicy();
var transformResult = MetadataTransform.Run(policy,
new[] { _systemModule, ilModule });
var typeWithFunctionPointersType = transformResult.GetTransformedTypeDefinition(typeWithFunctionPointers);
var objectType = transformResult.GetTransformedTypeDefinition((Cts.MetadataType)_context.GetWellKnownType(Cts.WellKnownType.Object));
Assert.Equal(1, typeWithFunctionPointersType.Fields.Count);
var theField = typeWithFunctionPointersType.Fields[0];
Assert.IsType<TypeSpecification>(theField.Signature.Type);
var theFieldSignature = (TypeSpecification)theField.Signature.Type;
Assert.IsType<FunctionPointerSignature>(theFieldSignature.Signature);
var theFieldPointerSignature = (FunctionPointerSignature)theFieldSignature.Signature;
Assert.Equal(objectType, theFieldPointerSignature.Signature.ReturnType);
Assert.Equal(1, theFieldPointerSignature.Signature.Parameters.Count);
Assert.Equal(objectType, theFieldPointerSignature.Signature.Parameters[0]);
}
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using EverReader.Models;
namespace EverReader.Migrations
{
[DbContext(typeof(EverReaderContext))]
[Migration("20151117081230_BookmarkNoteLength")]
partial class BookmarkNoteLength
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.Annotation("ProductVersion", "7.0.0-beta8-15964")
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("EverReader.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.Annotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<int?>("EvernoteCredentialsId");
b.Property<bool>("HasAuthorisedEvernote");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.Annotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.Annotation("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")
.Annotation("MaxLength", 256);
b.HasKey("Id");
b.Index("NormalizedEmail")
.Annotation("Relational:Name", "EmailIndex");
b.Index("NormalizedUserName")
.Annotation("Relational:Name", "UserNameIndex");
b.Annotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("EverReader.Models.Bookmark", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("NoteCreated");
b.Property<string>("NoteGuid");
b.Property<int>("NoteLength");
b.Property<string>("NoteTitle");
b.Property<DateTime>("NoteUpdated");
b.Property<decimal>("PercentageRead");
b.Property<int>("Type");
b.Property<DateTime>("Updated");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("EverReader.Models.EFDbEvernoteCredentials", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AuthToken");
b.Property<DateTime>("Expires");
b.Property<string>("NotebookUrl");
b.Property<string>("Shard");
b.Property<string>("UserId");
b.Property<string>("WebApiUrlPrefix");
b.HasKey("Id");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.Annotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.Annotation("MaxLength", 256);
b.HasKey("Id");
b.Index("NormalizedName")
.Annotation("Relational:Name", "RoleNameIndex");
b.Annotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId");
b.HasKey("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId");
b.HasKey("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId");
b.HasKey("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("EverReader.Models.ApplicationUser", b =>
{
b.HasOne("EverReader.Models.EFDbEvernoteCredentials")
.WithMany()
.ForeignKey("EvernoteCredentialsId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.ForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("EverReader.Models.ApplicationUser")
.WithMany()
.ForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("EverReader.Models.ApplicationUser")
.WithMany()
.ForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.ForeignKey("RoleId");
b.HasOne("EverReader.Models.ApplicationUser")
.WithMany()
.ForeignKey("UserId");
});
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
namespace System.Reflection
{
// This file defines an internal class used to throw exceptions. The main purpose is to reduce code size.
// Also it improves the likelihood that callers will be inlined.
internal static class Throw
{
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCast()
{
throw new InvalidCastException();
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void LitteEndianArchitectureRequired()
{
throw new PlatformNotSupportedException(SR.LitteEndianArchitectureRequired);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidArgument(string message, string parameterName)
{
throw new ArgumentException(message, parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidArgument_OffsetForVirtualHeapHandle()
{
throw new ArgumentException(SR.CantGetOffsetForVirtualHeapHandle, "handle");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static Exception InvalidArgument_UnexpectedHandleKind(HandleKind kind)
{
throw new ArgumentException(SR.Format(SR.UnexpectedHandleKind, kind));
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static Exception InvalidArgument_Handle(string parameterName)
{
throw new ArgumentException(SR.Format(SR.InvalidHandle), parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void SignatureNotVarArg()
{
throw new InvalidOperationException(SR.SignatureNotVarArg);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ControlFlowBuilderNotAvailable()
{
throw new InvalidOperationException(SR.ControlFlowBuilderNotAvailable);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperationBuilderAlreadyLinked()
{
throw new InvalidOperationException(SR.BuilderAlreadyLinked);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation(string message)
{
throw new InvalidOperationException(message);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation_LabelNotMarked(int id)
{
throw new InvalidOperationException(SR.Format(SR.LabelNotMarked, id));
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void LabelDoesntBelongToBuilder(string parameterName)
{
throw new ArgumentException(SR.LabelDoesntBelongToBuilder, parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void HeapHandleRequired()
{
throw new ArgumentException(SR.NotMetadataHeapHandle, "handle");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void EntityOrUserStringHandleRequired()
{
throw new ArgumentException(SR.NotMetadataTableOrUserStringHandle, "handle");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidToken()
{
throw new ArgumentException(SR.InvalidToken, "token");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentNull(string parameterName)
{
throw new ArgumentNullException(parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentEmptyString(string parameterName)
{
throw new ArgumentException(SR.ExpectedNonEmptyString, parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueArgumentNull()
{
throw new ArgumentNullException("value");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void BuilderArgumentNull()
{
throw new ArgumentNullException("builder");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentOutOfRange(string parameterName)
{
throw new ArgumentOutOfRangeException(parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ArgumentOutOfRange(string parameterName, string message)
{
throw new ArgumentOutOfRangeException(parameterName, message);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void BlobTooLarge(string parameterName)
{
throw new ArgumentOutOfRangeException(parameterName, SR.BlobTooLarge);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void IndexOutOfRange()
{
throw new ArgumentOutOfRangeException("index");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TableIndexOutOfRange()
{
throw new ArgumentOutOfRangeException("tableIndex");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueArgumentOutOfRange()
{
throw new ArgumentOutOfRangeException("value");
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void OutOfBounds()
{
throw new BadImageFormatException(SR.OutOfBoundsRead);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void WriteOutOfBounds()
{
throw new InvalidOperationException(SR.OutOfBoundsWrite);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCodedIndex()
{
throw new BadImageFormatException(SR.InvalidCodedIndex);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidHandle()
{
throw new BadImageFormatException(SR.InvalidHandle);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidCompressedInteger()
{
throw new BadImageFormatException(SR.InvalidCompressedInteger);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidSerializedString()
{
throw new BadImageFormatException(SR.InvalidSerializedString);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ImageTooSmall()
{
throw new BadImageFormatException(SR.ImageTooSmall);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ImageTooSmallOrContainsInvalidOffsetOrCount()
{
throw new BadImageFormatException(SR.ImageTooSmallOrContainsInvalidOffsetOrCount);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ReferenceOverflow()
{
throw new BadImageFormatException(SR.RowIdOrHeapOffsetTooLarge);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TableNotSorted(TableIndex tableIndex)
{
throw new BadImageFormatException(SR.Format(SR.MetadataTableNotSorted, tableIndex));
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation_TableNotSorted(TableIndex tableIndex)
{
throw new InvalidOperationException(SR.Format(SR.MetadataTableNotSorted, tableIndex));
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void InvalidOperation_PEImageNotAvailable()
{
throw new InvalidOperationException(SR.PEImageNotAvailable);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void TooManySubnamespaces()
{
throw new BadImageFormatException(SR.TooManySubnamespaces);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void ValueOverflow()
{
throw new BadImageFormatException(SR.ValueTooLarge);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void SequencePointValueOutOfRange()
{
throw new BadImageFormatException(SR.SequencePointValueOutOfRange);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void HeapSizeLimitExceeded(HeapIndex heap)
{
throw new ImageFormatLimitationException(SR.Format(SR.HeapSizeLimitExceeded, heap));
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void PEReaderDisposed()
{
throw new ObjectDisposedException(nameof(PortableExecutable.PEReader));
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Android.Telephony.Gsm.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma warning disable 1717
namespace Android.Telephony.Gsm
{
/// <java-name>
/// android/telephony/gsm/SmsManager
/// </java-name>
[Dot42.DexImport("android/telephony/gsm/SmsManager", AccessFlags = 49)]
public sealed partial class SmsManager
/* scope: __dot42__ */
{
/// <java-name>
/// STATUS_ON_SIM_FREE
/// </java-name>
[Dot42.DexImport("STATUS_ON_SIM_FREE", "I", AccessFlags = 25)]
public const int STATUS_ON_SIM_FREE = 0;
/// <java-name>
/// STATUS_ON_SIM_READ
/// </java-name>
[Dot42.DexImport("STATUS_ON_SIM_READ", "I", AccessFlags = 25)]
public const int STATUS_ON_SIM_READ = 1;
/// <java-name>
/// STATUS_ON_SIM_UNREAD
/// </java-name>
[Dot42.DexImport("STATUS_ON_SIM_UNREAD", "I", AccessFlags = 25)]
public const int STATUS_ON_SIM_UNREAD = 3;
/// <java-name>
/// STATUS_ON_SIM_SENT
/// </java-name>
[Dot42.DexImport("STATUS_ON_SIM_SENT", "I", AccessFlags = 25)]
public const int STATUS_ON_SIM_SENT = 5;
/// <java-name>
/// STATUS_ON_SIM_UNSENT
/// </java-name>
[Dot42.DexImport("STATUS_ON_SIM_UNSENT", "I", AccessFlags = 25)]
public const int STATUS_ON_SIM_UNSENT = 7;
/// <java-name>
/// RESULT_ERROR_GENERIC_FAILURE
/// </java-name>
[Dot42.DexImport("RESULT_ERROR_GENERIC_FAILURE", "I", AccessFlags = 25)]
public const int RESULT_ERROR_GENERIC_FAILURE = 1;
/// <java-name>
/// RESULT_ERROR_RADIO_OFF
/// </java-name>
[Dot42.DexImport("RESULT_ERROR_RADIO_OFF", "I", AccessFlags = 25)]
public const int RESULT_ERROR_RADIO_OFF = 2;
/// <java-name>
/// RESULT_ERROR_NULL_PDU
/// </java-name>
[Dot42.DexImport("RESULT_ERROR_NULL_PDU", "I", AccessFlags = 25)]
public const int RESULT_ERROR_NULL_PDU = 3;
/// <java-name>
/// RESULT_ERROR_NO_SERVICE
/// </java-name>
[Dot42.DexImport("RESULT_ERROR_NO_SERVICE", "I", AccessFlags = 25)]
public const int RESULT_ERROR_NO_SERVICE = 4;
[Dot42.DexImport("<init>", "()V", AccessFlags = 0)]
internal SmsManager() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getDefault
/// </java-name>
[Dot42.DexImport("getDefault", "()Landroid/telephony/gsm/SmsManager;", AccessFlags = 25)]
public static global::Android.Telephony.Gsm.SmsManager GetDefault() /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsManager);
}
/// <java-name>
/// sendTextMessage
/// </java-name>
[Dot42.DexImport("sendTextMessage", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Landroid/app/PendingIntent" +
";Landroid/app/PendingIntent;)V", AccessFlags = 17)]
public void SendTextMessage(string @string, string string1, string string2, global::Android.App.PendingIntent pendingIntent, global::Android.App.PendingIntent pendingIntent1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// divideMessage
/// </java-name>
[Dot42.DexImport("divideMessage", "(Ljava/lang/String;)Ljava/util/ArrayList;", AccessFlags = 17, Signature = "(Ljava/lang/String;)Ljava/util/ArrayList<Ljava/lang/String;>;")]
public global::Java.Util.ArrayList<string> DivideMessage(string @string) /* MethodBuilder.Create */
{
return default(global::Java.Util.ArrayList<string>);
}
/// <java-name>
/// sendMultipartTextMessage
/// </java-name>
[Dot42.DexImport("sendMultipartTextMessage", "(Ljava/lang/String;Ljava/lang/String;Ljava/util/ArrayList;Ljava/util/ArrayList;Lj" +
"ava/util/ArrayList;)V", AccessFlags = 17, Signature = "(Ljava/lang/String;Ljava/lang/String;Ljava/util/ArrayList<Ljava/lang/String;>;Lja" +
"va/util/ArrayList<Landroid/app/PendingIntent;>;Ljava/util/ArrayList<Landroid/app" +
"/PendingIntent;>;)V")]
public void SendMultipartTextMessage(string @string, string string1, global::Java.Util.ArrayList<string> arrayList, global::Java.Util.ArrayList<global::Android.App.PendingIntent> arrayList1, global::Java.Util.ArrayList<global::Android.App.PendingIntent> arrayList2) /* MethodBuilder.Create */
{
}
/// <java-name>
/// sendDataMessage
/// </java-name>
[Dot42.DexImport("sendDataMessage", "(Ljava/lang/String;Ljava/lang/String;S[BLandroid/app/PendingIntent;Landroid/app/P" +
"endingIntent;)V", AccessFlags = 17)]
public void SendDataMessage(string @string, string string1, short int16, sbyte[] sByte, global::Android.App.PendingIntent pendingIntent, global::Android.App.PendingIntent pendingIntent1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// sendDataMessage
/// </java-name>
[Dot42.DexImport("sendDataMessage", "(Ljava/lang/String;Ljava/lang/String;S[BLandroid/app/PendingIntent;Landroid/app/P" +
"endingIntent;)V", AccessFlags = 17, IgnoreFromJava = true)]
public void SendDataMessage(string @string, string string1, short int16, byte[] @byte, global::Android.App.PendingIntent pendingIntent, global::Android.App.PendingIntent pendingIntent1) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getDefault
/// </java-name>
public static global::Android.Telephony.Gsm.SmsManager Default
{
[Dot42.DexImport("getDefault", "()Landroid/telephony/gsm/SmsManager;", AccessFlags = 25)]
get{ return GetDefault(); }
}
}
/// <summary>
/// <para>Represents the cell location on a GSM phone. </para>
/// </summary>
/// <java-name>
/// android/telephony/gsm/GsmCellLocation
/// </java-name>
[Dot42.DexImport("android/telephony/gsm/GsmCellLocation", AccessFlags = 33)]
public partial class GsmCellLocation : global::Android.Telephony.CellLocation
/* scope: __dot42__ */
{
/// <summary>
/// <para>Empty constructor. Initializes the LAC and CID to -1. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public GsmCellLocation() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Initialize the object from a bundle. </para>
/// </summary>
[Dot42.DexImport("<init>", "(Landroid/os/Bundle;)V", AccessFlags = 1)]
public GsmCellLocation(global::Android.Os.Bundle bundle) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>gsm location area code, -1 if unknown, 0xffff max legal value </para>
/// </returns>
/// <java-name>
/// getLac
/// </java-name>
[Dot42.DexImport("getLac", "()I", AccessFlags = 1)]
public virtual int GetLac() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>gsm cell id, -1 if unknown, 0xffff max legal value </para>
/// </returns>
/// <java-name>
/// getCid
/// </java-name>
[Dot42.DexImport("getCid", "()I", AccessFlags = 1)]
public virtual int GetCid() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>On a UMTS network, returns the primary scrambling code of the serving cell.</para><para></para>
/// </summary>
/// <returns>
/// <para>primary scrambling code for UMTS, -1 if unknown or GSM </para>
/// </returns>
/// <java-name>
/// getPsc
/// </java-name>
[Dot42.DexImport("getPsc", "()I", AccessFlags = 1)]
public virtual int GetPsc() /* MethodBuilder.Create */
{
return default(int);
}
/// <summary>
/// <para>Invalidate this object. The location area code and the cell id are set to -1. </para>
/// </summary>
/// <java-name>
/// setStateInvalid
/// </java-name>
[Dot42.DexImport("setStateInvalid", "()V", AccessFlags = 1)]
public virtual void SetStateInvalid() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Set the location area code and the cell id. </para>
/// </summary>
/// <java-name>
/// setLacAndCid
/// </java-name>
[Dot42.DexImport("setLacAndCid", "(II)V", AccessFlags = 1)]
public virtual void SetLacAndCid(int lac, int cid) /* MethodBuilder.Create */
{
}
/// <java-name>
/// hashCode
/// </java-name>
[Dot42.DexImport("hashCode", "()I", AccessFlags = 1)]
public override int GetHashCode() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// equals
/// </java-name>
[Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)]
public override bool Equals(object o) /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Set intent notifier Bundle based on service state</para><para></para>
/// </summary>
/// <java-name>
/// fillInNotifierBundle
/// </java-name>
[Dot42.DexImport("fillInNotifierBundle", "(Landroid/os/Bundle;)V", AccessFlags = 1)]
public virtual void FillInNotifierBundle(global::Android.Os.Bundle m) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>gsm location area code, -1 if unknown, 0xffff max legal value </para>
/// </returns>
/// <java-name>
/// getLac
/// </java-name>
public int Lac
{
[Dot42.DexImport("getLac", "()I", AccessFlags = 1)]
get{ return GetLac(); }
}
/// <summary>
/// <para></para>
/// </summary>
/// <returns>
/// <para>gsm cell id, -1 if unknown, 0xffff max legal value </para>
/// </returns>
/// <java-name>
/// getCid
/// </java-name>
public int Cid
{
[Dot42.DexImport("getCid", "()I", AccessFlags = 1)]
get{ return GetCid(); }
}
/// <summary>
/// <para>On a UMTS network, returns the primary scrambling code of the serving cell.</para><para></para>
/// </summary>
/// <returns>
/// <para>primary scrambling code for UMTS, -1 if unknown or GSM </para>
/// </returns>
/// <java-name>
/// getPsc
/// </java-name>
public int Psc
{
[Dot42.DexImport("getPsc", "()I", AccessFlags = 1)]
get{ return GetPsc(); }
}
}
/// <java-name>
/// android/telephony/gsm/SmsMessage
/// </java-name>
[Dot42.DexImport("android/telephony/gsm/SmsMessage", AccessFlags = 33)]
public partial class SmsMessage
/* scope: __dot42__ */
{
/// <java-name>
/// ENCODING_UNKNOWN
/// </java-name>
[Dot42.DexImport("ENCODING_UNKNOWN", "I", AccessFlags = 25)]
public const int ENCODING_UNKNOWN = 0;
/// <java-name>
/// ENCODING_7BIT
/// </java-name>
[Dot42.DexImport("ENCODING_7BIT", "I", AccessFlags = 25)]
public const int ENCODING_7BIT = 1;
/// <java-name>
/// ENCODING_8BIT
/// </java-name>
[Dot42.DexImport("ENCODING_8BIT", "I", AccessFlags = 25)]
public const int ENCODING_8BIT = 2;
/// <java-name>
/// ENCODING_16BIT
/// </java-name>
[Dot42.DexImport("ENCODING_16BIT", "I", AccessFlags = 25)]
public const int ENCODING_16BIT = 3;
/// <java-name>
/// MAX_USER_DATA_BYTES
/// </java-name>
[Dot42.DexImport("MAX_USER_DATA_BYTES", "I", AccessFlags = 25)]
public const int MAX_USER_DATA_BYTES = 140;
/// <java-name>
/// MAX_USER_DATA_SEPTETS
/// </java-name>
[Dot42.DexImport("MAX_USER_DATA_SEPTETS", "I", AccessFlags = 25)]
public const int MAX_USER_DATA_SEPTETS = 160;
/// <java-name>
/// MAX_USER_DATA_SEPTETS_WITH_HEADER
/// </java-name>
[Dot42.DexImport("MAX_USER_DATA_SEPTETS_WITH_HEADER", "I", AccessFlags = 25)]
public const int MAX_USER_DATA_SEPTETS_WITH_HEADER = 153;
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public SmsMessage() /* MethodBuilder.Create */
{
}
/// <java-name>
/// createFromPdu
/// </java-name>
[Dot42.DexImport("createFromPdu", "([B)Landroid/telephony/gsm/SmsMessage;", AccessFlags = 9)]
public static global::Android.Telephony.Gsm.SmsMessage CreateFromPdu(sbyte[] sByte) /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsMessage);
}
/// <java-name>
/// createFromPdu
/// </java-name>
[Dot42.DexImport("createFromPdu", "([B)Landroid/telephony/gsm/SmsMessage;", AccessFlags = 9, IgnoreFromJava = true)]
public static global::Android.Telephony.Gsm.SmsMessage CreateFromPdu(byte[] @byte) /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsMessage);
}
/// <java-name>
/// getTPLayerLengthForPDU
/// </java-name>
[Dot42.DexImport("getTPLayerLengthForPDU", "(Ljava/lang/String;)I", AccessFlags = 9)]
public static int GetTPLayerLengthForPDU(string @string) /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// calculateLength
/// </java-name>
[Dot42.DexImport("calculateLength", "(Ljava/lang/CharSequence;Z)[I", AccessFlags = 9)]
public static int[] CalculateLength(global::Java.Lang.ICharSequence charSequence, bool boolean) /* MethodBuilder.Create */
{
return default(int[]);
}
/// <java-name>
/// calculateLength
/// </java-name>
[Dot42.DexImport("calculateLength", "(Ljava/lang/String;Z)[I", AccessFlags = 9)]
public static int[] CalculateLength(string @string, bool boolean) /* MethodBuilder.Create */
{
return default(int[]);
}
/// <java-name>
/// getSubmitPdu
/// </java-name>
[Dot42.DexImport("getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Landroid/telephony/gsm/S" +
"msMessage$SubmitPdu;", AccessFlags = 9)]
public static global::Android.Telephony.Gsm.SmsMessage.SubmitPdu GetSubmitPdu(string @string, string string1, string string2, bool boolean) /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsMessage.SubmitPdu);
}
/// <java-name>
/// getSubmitPdu
/// </java-name>
[Dot42.DexImport("getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;S[BZ)Landroid/telephony/gsm/SmsMessage$Submi" +
"tPdu;", AccessFlags = 9)]
public static global::Android.Telephony.Gsm.SmsMessage.SubmitPdu GetSubmitPdu(string @string, string string1, short int16, sbyte[] sByte, bool boolean) /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsMessage.SubmitPdu);
}
/// <java-name>
/// getSubmitPdu
/// </java-name>
[Dot42.DexImport("getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;S[BZ)Landroid/telephony/gsm/SmsMessage$Submi" +
"tPdu;", AccessFlags = 9, IgnoreFromJava = true)]
public static global::Android.Telephony.Gsm.SmsMessage.SubmitPdu GetSubmitPdu(string @string, string string1, short int16, byte[] @byte, bool boolean) /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsMessage.SubmitPdu);
}
/// <java-name>
/// getServiceCenterAddress
/// </java-name>
[Dot42.DexImport("getServiceCenterAddress", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetServiceCenterAddress() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getOriginatingAddress
/// </java-name>
[Dot42.DexImport("getOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetOriginatingAddress() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getDisplayOriginatingAddress
/// </java-name>
[Dot42.DexImport("getDisplayOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetDisplayOriginatingAddress() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getMessageBody
/// </java-name>
[Dot42.DexImport("getMessageBody", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetMessageBody() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getMessageClass
/// </java-name>
[Dot42.DexImport("getMessageClass", "()Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 1)]
public virtual global::Android.Telephony.Gsm.SmsMessage.MessageClass GetMessageClass() /* MethodBuilder.Create */
{
return default(global::Android.Telephony.Gsm.SmsMessage.MessageClass);
}
/// <java-name>
/// getDisplayMessageBody
/// </java-name>
[Dot42.DexImport("getDisplayMessageBody", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetDisplayMessageBody() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getPseudoSubject
/// </java-name>
[Dot42.DexImport("getPseudoSubject", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetPseudoSubject() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getTimestampMillis
/// </java-name>
[Dot42.DexImport("getTimestampMillis", "()J", AccessFlags = 1)]
public virtual long GetTimestampMillis() /* MethodBuilder.Create */
{
return default(long);
}
/// <java-name>
/// isEmail
/// </java-name>
[Dot42.DexImport("isEmail", "()Z", AccessFlags = 1)]
public virtual bool IsEmail() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// getEmailBody
/// </java-name>
[Dot42.DexImport("getEmailBody", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetEmailBody() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getEmailFrom
/// </java-name>
[Dot42.DexImport("getEmailFrom", "()Ljava/lang/String;", AccessFlags = 1)]
public virtual string GetEmailFrom() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getProtocolIdentifier
/// </java-name>
[Dot42.DexImport("getProtocolIdentifier", "()I", AccessFlags = 1)]
public virtual int GetProtocolIdentifier() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// isReplace
/// </java-name>
[Dot42.DexImport("isReplace", "()Z", AccessFlags = 1)]
public virtual bool IsReplace() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isCphsMwiMessage
/// </java-name>
[Dot42.DexImport("isCphsMwiMessage", "()Z", AccessFlags = 1)]
public virtual bool IsCphsMwiMessage() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isMWIClearMessage
/// </java-name>
[Dot42.DexImport("isMWIClearMessage", "()Z", AccessFlags = 1)]
public virtual bool IsMWIClearMessage() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isMWISetMessage
/// </java-name>
[Dot42.DexImport("isMWISetMessage", "()Z", AccessFlags = 1)]
public virtual bool IsMWISetMessage() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isMwiDontStore
/// </java-name>
[Dot42.DexImport("isMwiDontStore", "()Z", AccessFlags = 1)]
public virtual bool IsMwiDontStore() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// getUserData
/// </java-name>
[Dot42.DexImport("getUserData", "()[B", AccessFlags = 1)]
public virtual sbyte[] JavaGetUserData() /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <java-name>
/// getUserData
/// </java-name>
[Dot42.DexImport("getUserData", "()[B", AccessFlags = 1, IgnoreFromJava = true)]
public virtual byte[] GetUserData() /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <java-name>
/// getPdu
/// </java-name>
[Dot42.DexImport("getPdu", "()[B", AccessFlags = 1)]
public virtual sbyte[] JavaGetPdu() /* MethodBuilder.Create */
{
return default(sbyte[]);
}
/// <java-name>
/// getPdu
/// </java-name>
[Dot42.DexImport("getPdu", "()[B", AccessFlags = 1, IgnoreFromJava = true)]
public virtual byte[] GetPdu() /* MethodBuilder.Create */
{
return default(byte[]);
}
/// <java-name>
/// getStatusOnSim
/// </java-name>
[Dot42.DexImport("getStatusOnSim", "()I", AccessFlags = 1)]
public virtual int GetStatusOnSim() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// getIndexOnSim
/// </java-name>
[Dot42.DexImport("getIndexOnSim", "()I", AccessFlags = 1)]
public virtual int GetIndexOnSim() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// getStatus
/// </java-name>
[Dot42.DexImport("getStatus", "()I", AccessFlags = 1)]
public virtual int GetStatus() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// isStatusReportMessage
/// </java-name>
[Dot42.DexImport("isStatusReportMessage", "()Z", AccessFlags = 1)]
public virtual bool IsStatusReportMessage() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// isReplyPathPresent
/// </java-name>
[Dot42.DexImport("isReplyPathPresent", "()Z", AccessFlags = 1)]
public virtual bool IsReplyPathPresent() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// getServiceCenterAddress
/// </java-name>
public string ServiceCenterAddress
{
[Dot42.DexImport("getServiceCenterAddress", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetServiceCenterAddress(); }
}
/// <java-name>
/// getOriginatingAddress
/// </java-name>
public string OriginatingAddress
{
[Dot42.DexImport("getOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetOriginatingAddress(); }
}
/// <java-name>
/// getDisplayOriginatingAddress
/// </java-name>
public string DisplayOriginatingAddress
{
[Dot42.DexImport("getDisplayOriginatingAddress", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetDisplayOriginatingAddress(); }
}
/// <java-name>
/// getMessageBody
/// </java-name>
public string MessageBody
{
[Dot42.DexImport("getMessageBody", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMessageBody(); }
}
/// <java-name>
/// getDisplayMessageBody
/// </java-name>
public string DisplayMessageBody
{
[Dot42.DexImport("getDisplayMessageBody", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetDisplayMessageBody(); }
}
/// <java-name>
/// getPseudoSubject
/// </java-name>
public string PseudoSubject
{
[Dot42.DexImport("getPseudoSubject", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPseudoSubject(); }
}
/// <java-name>
/// getTimestampMillis
/// </java-name>
public long TimestampMillis
{
[Dot42.DexImport("getTimestampMillis", "()J", AccessFlags = 1)]
get{ return GetTimestampMillis(); }
}
/// <java-name>
/// getEmailBody
/// </java-name>
public string EmailBody
{
[Dot42.DexImport("getEmailBody", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetEmailBody(); }
}
/// <java-name>
/// getEmailFrom
/// </java-name>
public string EmailFrom
{
[Dot42.DexImport("getEmailFrom", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetEmailFrom(); }
}
/// <java-name>
/// getProtocolIdentifier
/// </java-name>
public int ProtocolIdentifier
{
[Dot42.DexImport("getProtocolIdentifier", "()I", AccessFlags = 1)]
get{ return GetProtocolIdentifier(); }
}
/// <java-name>
/// getUserData
/// </java-name>
public byte[] UserData
{
[Dot42.DexImport("getUserData", "()[B", AccessFlags = 1, IgnoreFromJava = true)]
get{ return GetUserData(); }
}
/// <java-name>
/// getPdu
/// </java-name>
public byte[] Pdu
{
[Dot42.DexImport("getPdu", "()[B", AccessFlags = 1, IgnoreFromJava = true)]
get{ return GetPdu(); }
}
/// <java-name>
/// getStatusOnSim
/// </java-name>
public int StatusOnSim
{
[Dot42.DexImport("getStatusOnSim", "()I", AccessFlags = 1)]
get{ return GetStatusOnSim(); }
}
/// <java-name>
/// getIndexOnSim
/// </java-name>
public int IndexOnSim
{
[Dot42.DexImport("getIndexOnSim", "()I", AccessFlags = 1)]
get{ return GetIndexOnSim(); }
}
/// <java-name>
/// getStatus
/// </java-name>
public int Status
{
[Dot42.DexImport("getStatus", "()I", AccessFlags = 1)]
get{ return GetStatus(); }
}
/// <java-name>
/// android/telephony/gsm/SmsMessage$SubmitPdu
/// </java-name>
[Dot42.DexImport("android/telephony/gsm/SmsMessage$SubmitPdu", AccessFlags = 9)]
public partial class SubmitPdu
/* scope: __dot42__ */
{
/// <java-name>
/// encodedScAddress
/// </java-name>
[Dot42.DexImport("encodedScAddress", "[B", AccessFlags = 1)]
public sbyte[] EncodedScAddress;
/// <java-name>
/// encodedMessage
/// </java-name>
[Dot42.DexImport("encodedMessage", "[B", AccessFlags = 1)]
public sbyte[] EncodedMessage;
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public SubmitPdu() /* MethodBuilder.Create */
{
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
}
/// <java-name>
/// android/telephony/gsm/SmsMessage$MessageClass
/// </java-name>
[Dot42.DexImport("android/telephony/gsm/SmsMessage$MessageClass", AccessFlags = 16409, Signature = "Ljava/lang/Enum<Landroid/telephony/gsm/SmsMessage$MessageClass;>;")]
public sealed class MessageClass
/* scope: __dot42__ */
{
/// <java-name>
/// CLASS_0
/// </java-name>
[Dot42.DexImport("CLASS_0", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)]
public static readonly MessageClass CLASS_0;
/// <java-name>
/// CLASS_1
/// </java-name>
[Dot42.DexImport("CLASS_1", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)]
public static readonly MessageClass CLASS_1;
/// <java-name>
/// CLASS_2
/// </java-name>
[Dot42.DexImport("CLASS_2", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)]
public static readonly MessageClass CLASS_2;
/// <java-name>
/// CLASS_3
/// </java-name>
[Dot42.DexImport("CLASS_3", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)]
public static readonly MessageClass CLASS_3;
/// <java-name>
/// UNKNOWN
/// </java-name>
[Dot42.DexImport("UNKNOWN", "Landroid/telephony/gsm/SmsMessage$MessageClass;", AccessFlags = 16409)]
public static readonly MessageClass UNKNOWN;
private MessageClass() /* TypeBuilder.AddPrivateDefaultCtor */
{
}
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Avalonia.Input;
using Avalonia.Layout;
namespace Avalonia.Controls
{
/// <summary>
/// A panel that displays child controls at arbitrary locations.
/// </summary>
/// <remarks>
/// Unlike other <see cref="Panel"/> implementations, the <see cref="Canvas"/> doesn't lay out
/// its children in any particular layout. Instead, the positioning of each child control is
/// defined by the <code>Canvas.Left</code>, <code>Canvas.Top</code>, <code>Canvas.Right</code>
/// and <code>Canvas.Bottom</code> attached properties.
/// </remarks>
public class Canvas : Panel, INavigableContainer
{
/// <summary>
/// Defines the Left attached property.
/// </summary>
public static readonly AttachedProperty<double> LeftProperty =
AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Left");
/// <summary>
/// Defines the Top attached property.
/// </summary>
public static readonly AttachedProperty<double> TopProperty =
AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Top");
/// <summary>
/// Defines the Right attached property.
/// </summary>
public static readonly AttachedProperty<double> RightProperty =
AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Right");
/// <summary>
/// Defines the Bottom attached property.
/// </summary>
public static readonly AttachedProperty<double> BottomProperty =
AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Bottom");
/// <summary>
/// Initializes static members of the <see cref="Canvas"/> class.
/// </summary>
static Canvas()
{
AffectsCanvasArrange(LeftProperty, TopProperty, RightProperty, BottomProperty);
}
/// <summary>
/// Gets the value of the Left attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's left coordinate.</returns>
public static double GetLeft(AvaloniaObject element)
{
return element.GetValue(LeftProperty);
}
/// <summary>
/// Sets the value of the Left attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The left value.</param>
public static void SetLeft(AvaloniaObject element, double value)
{
element.SetValue(LeftProperty, value);
}
/// <summary>
/// Gets the value of the Top attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's top coordinate.</returns>
public static double GetTop(AvaloniaObject element)
{
return element.GetValue(TopProperty);
}
/// <summary>
/// Sets the value of the Top attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The top value.</param>
public static void SetTop(AvaloniaObject element, double value)
{
element.SetValue(TopProperty, value);
}
/// <summary>
/// Gets the value of the Right attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's right coordinate.</returns>
public static double GetRight(AvaloniaObject element)
{
return element.GetValue(RightProperty);
}
/// <summary>
/// Sets the value of the Right attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The right value.</param>
public static void SetRight(AvaloniaObject element, double value)
{
element.SetValue(RightProperty, value);
}
/// <summary>
/// Gets the value of the Bottom attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's bottom coordinate.</returns>
public static double GetBottom(AvaloniaObject element)
{
return element.GetValue(BottomProperty);
}
/// <summary>
/// Sets the value of the Bottom attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The bottom value.</param>
public static void SetBottom(AvaloniaObject element, double value)
{
element.SetValue(BottomProperty, value);
}
/// <summary>
/// Gets the next control in the specified direction.
/// </summary>
/// <param name="direction">The movement direction.</param>
/// <param name="from">The control from which movement begins.</param>
/// <returns>The control.</returns>
IInputElement INavigableContainer.GetControl(NavigationDirection direction, IInputElement from)
{
// TODO: Implement this
return null;
}
/// <summary>
/// Measures the control.
/// </summary>
/// <param name="availableSize">The available size.</param>
/// <returns>The desired size of the control.</returns>
protected override Size MeasureOverride(Size availableSize)
{
availableSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
foreach (Control child in Children)
{
child.Measure(availableSize);
}
return new Size();
}
/// <summary>
/// Arranges the control's children.
/// </summary>
/// <param name="finalSize">The size allocated to the control.</param>
/// <returns>The space taken.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
foreach (Control child in Children)
{
double x = 0.0;
double y = 0.0;
double elementLeft = GetLeft(child);
if (!double.IsNaN(elementLeft))
{
x = elementLeft;
}
else
{
// Arrange with right.
double elementRight = GetRight(child);
if (!double.IsNaN(elementRight))
{
x = finalSize.Width - child.DesiredSize.Width - elementRight;
}
}
double elementTop = GetTop(child);
if (!double.IsNaN(elementTop) )
{
y = elementTop;
}
else
{
double elementBottom = GetBottom(child);
if (!double.IsNaN(elementBottom))
{
y = finalSize.Height - child.DesiredSize.Height - elementBottom;
}
}
child.Arrange(new Rect(new Point(x, y), child.DesiredSize));
}
return finalSize;
}
/// <summary>
/// Marks a property on a child as affecting the canvas' arrangement.
/// </summary>
/// <param name="properties">The properties.</param>
private static void AffectsCanvasArrange(params AvaloniaProperty[] properties)
{
foreach (var property in properties)
{
property.Changed.Subscribe(AffectsCanvasArrangeInvalidate);
}
}
/// <summary>
/// Calls <see cref="Layoutable.InvalidateArrange"/> on the parent of the control whose
/// property changed, if that parent is a canvas.
/// </summary>
/// <param name="e">The event args.</param>
private static void AffectsCanvasArrangeInvalidate(AvaloniaPropertyChangedEventArgs e)
{
var control = e.Sender as IControl;
var canvas = control?.VisualParent as Canvas;
canvas?.InvalidateArrange();
}
}
}
| |
/// Copyright (C) 2012-2014 Soomla 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;
using System.Collections;
using System.Collections.Generic;
using System;
namespace Soomla {
public class Schedule {
private static string TAG = "SOOMLA Schedule";
public enum Recurrence {
EVERY_MONTH,
EVERY_WEEK,
EVERY_DAY,
EVERY_HOUR,
NONE
}
public class DateTimeRange {
public DateTime Start;
public DateTime End;
public DateTimeRange(DateTime start, DateTime end) {
Start = start;
End = end;
}
}
public Recurrence RequiredRecurrence;
public List<DateTimeRange> TimeRanges;
public int ActivationLimit;
public static Schedule AnyTimeOnce() {
return new Schedule(1);
}
public static Schedule AnyTimeLimited(int activationLimit) {
return new Schedule(activationLimit);
}
public static Schedule AnyTimeUnLimited() {
return new Schedule(0);
}
public Schedule(int activationLimit) :
this(null, Recurrence.NONE, activationLimit)
{
}
public Schedule(DateTime startTime, DateTime endTime, Recurrence recurrence, int activationLimit) :
this(new List<DateTimeRange> { new DateTimeRange(startTime, endTime) }, recurrence, activationLimit)
{
}
public Schedule(List<DateTimeRange> timeRanges, Recurrence recurrence, int activationLimit)
{
TimeRanges = timeRanges;
RequiredRecurrence = recurrence;
ActivationLimit = activationLimit;
}
public Schedule(JSONObject jsonSched)
{
if(jsonSched[JSONConsts.SOOM_SCHE_REC]) {
RequiredRecurrence = (Recurrence) jsonSched[JSONConsts.SOOM_SCHE_REC].n;
} else {
RequiredRecurrence = Recurrence.NONE;
}
ActivationLimit = (int)Math.Ceiling(jsonSched[JSONConsts.SOOM_SCHE_APPROVALS].n);
TimeRanges = new List<DateTimeRange>();
if (jsonSched[JSONConsts.SOOM_SCHE_RANGES]) {
List<JSONObject> RangesObjs = jsonSched[JSONConsts.SOOM_SCHE_RANGES].list;
foreach(JSONObject RangeObj in RangesObjs) {
TimeSpan tmpTime = TimeSpan.FromMilliseconds((long)RangeObj[JSONConsts.SOOM_SCHE_RANGE_START].n);
DateTime start = new DateTime(tmpTime.Ticks);
tmpTime = TimeSpan.FromMilliseconds((long)RangeObj[JSONConsts.SOOM_SCHE_RANGE_END].n);
DateTime end = new DateTime(tmpTime.Ticks);
TimeRanges.Add(new DateTimeRange(start, end));
}
}
}
public JSONObject toJSONObject() {
JSONObject obj = new JSONObject(JSONObject.Type.OBJECT);
obj.AddField(JSONConsts.SOOM_CLASSNAME, SoomlaUtils.GetClassName(this));
obj.AddField(JSONConsts.SOOM_SCHE_REC, (int)RequiredRecurrence);
obj.AddField(JSONConsts.SOOM_SCHE_APPROVALS, ActivationLimit);
JSONObject rangesObj = new JSONObject(JSONObject.Type.ARRAY);
if (TimeRanges != null)
{
foreach(DateTimeRange dtr in TimeRanges)
{
long startMillis = dtr.Start.Ticks / TimeSpan.TicksPerMillisecond;
long endMillis = dtr.End.Ticks / TimeSpan.TicksPerMillisecond;
JSONObject singleRange = new JSONObject(JSONObject.Type.OBJECT);
singleRange.AddField(JSONConsts.SOOM_CLASSNAME, SoomlaUtils.GetClassName(dtr));
singleRange.AddField(JSONConsts.SOOM_SCHE_RANGE_START, startMillis);
singleRange.AddField(JSONConsts.SOOM_SCHE_RANGE_END, endMillis);
rangesObj.Add(singleRange);
}
}
obj.AddField(JSONConsts.SOOM_SCHE_RANGES, rangesObj);
return obj;
}
public bool Approve(int activationTimes) {
DateTime now = DateTime.Now;
if (ActivationLimit < 1 && (TimeRanges == null || TimeRanges.Count == 0)) {
SoomlaUtils.LogDebug(TAG, "There's no activation limit and no TimeRanges. APPROVED!");
return true;
}
if (ActivationLimit>0 && activationTimes >= ActivationLimit) {
SoomlaUtils.LogDebug(TAG, "Activation limit exceeded.");
return false;
}
if ((TimeRanges == null || TimeRanges.Count == 0)) {
SoomlaUtils.LogDebug(TAG, "We have an activation limit that was not reached. Also, we don't have any time ranges. APPROVED!");
return true;
}
// NOTE: From this point on ... we know that we didn't reach the activation limit AND we have TimeRanges.
// We'll just make sure the time ranges and the Recurrence copmlies.
foreach(DateTimeRange dtr in TimeRanges) {
if (now >= dtr.Start && now <= dtr.End) {
SoomlaUtils.LogDebug(TAG, "We are just in one of the time spans, it can't get any better then that. APPROVED!");
return true;
}
}
// we don't need to continue if RequiredRecurrence is NONE
if (RequiredRecurrence == Recurrence.NONE) {
return false;
}
foreach(DateTimeRange dtr in TimeRanges) {
if (now.Minute >= dtr.Start.Minute && now.Minute <= dtr.End.Minute) {
SoomlaUtils.LogDebug(TAG, "Now is in one of the time ranges' minutes span.");
if (RequiredRecurrence == Recurrence.EVERY_HOUR) {
SoomlaUtils.LogDebug(TAG, "It's a EVERY_HOUR recurrence. APPROVED!");
return true;
}
if (now.Hour >= dtr.Start.Hour && now.Hour <= dtr.End.Hour) {
SoomlaUtils.LogDebug(TAG, "Now is in one of the time ranges' hours span.");
if (RequiredRecurrence == Recurrence.EVERY_DAY) {
SoomlaUtils.LogDebug(TAG, "It's a EVERY_DAY recurrence. APPROVED!");
return true;
}
if (now.DayOfWeek >= dtr.Start.DayOfWeek && now.DayOfWeek <= dtr.End.DayOfWeek) {
SoomlaUtils.LogDebug(TAG, "Now is in one of the time ranges' day-of-week span.");
if (RequiredRecurrence == Recurrence.EVERY_WEEK) {
SoomlaUtils.LogDebug(TAG, "It's a EVERY_WEEK recurrence. APPROVED!");
return true;
}
if (now.Day >= dtr.Start.Day && now.Day <= dtr.End.Day) {
SoomlaUtils.LogDebug(TAG, "Now is in one of the time ranges' days span.");
if (RequiredRecurrence == Recurrence.EVERY_MONTH) {
SoomlaUtils.LogDebug(TAG, "It's a EVERY_MONTH recurrence. APPROVED!");
return true;
}
}
}
}
}
}
return false;
}
}
}
| |
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Serialization;
using System.Linq;
namespace Newtonsoft.Json.Schema
{
/// <summary>
/// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>.
/// </summary>
public class JsonSchemaGenerator
{
/// <summary>
/// Gets or sets how undefined schemas are handled by the serializer.
/// </summary>
public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; }
private IContractResolver _contractResolver;
/// <summary>
/// Gets or sets the contract resolver.
/// </summary>
/// <value>The contract resolver.</value>
public IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
return DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
private class TypeSchema
{
public Type Type { get; private set; }
public JsonSchema Schema { get; private set;}
public TypeSchema(Type type, JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(schema, "schema");
Type = type;
Schema = schema;
}
}
private JsonSchemaResolver _resolver;
private readonly IList<TypeSchema> _stack = new List<TypeSchema>();
private JsonSchema _currentSchema;
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
private void Push(TypeSchema typeSchema)
{
_currentSchema = typeSchema.Schema;
_stack.Add(typeSchema);
_resolver.LoadedSchemas.Add(typeSchema.Schema);
}
private TypeSchema Pop()
{
TypeSchema popped = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
TypeSchema newValue = _stack.LastOrDefault();
if (newValue != null)
{
_currentSchema = newValue.Schema;
}
else
{
_currentSchema = null;
}
return popped;
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type)
{
return Generate(type, new JsonSchemaResolver(), false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
{
return Generate(type, resolver, false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, bool rootSchemaNullable)
{
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
_resolver = resolver;
return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false);
}
private string GetTitle(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
return containerAttribute.Title;
return null;
}
private string GetDescription(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
return containerAttribute.Description;
return null;
}
private string GetTypeId(Type type, bool explicitOnly)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id))
return containerAttribute.Id;
if (explicitOnly)
return null;
switch (UndefinedSchemaIdHandling)
{
case UndefinedSchemaIdHandling.UseTypeName:
return type.FullName;
case UndefinedSchemaIdHandling.UseAssemblyQualifiedName:
return type.AssemblyQualifiedName;
default:
return null;
}
}
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
{
ValidationUtils.ArgumentNotNull(type, "type");
string resolvedId = GetTypeId(type, false);
string explicitId = GetTypeId(type, true);
if (!string.IsNullOrEmpty(resolvedId))
{
JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
if (resolvedSchema != null)
{
// resolved schema is not null but referencing member allows nulls
// change resolved schema to allow nulls. hacky but what are ya gonna do?
if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null))
resolvedSchema.Type |= JsonSchemaType.Null;
if (required && resolvedSchema.Required != true)
resolvedSchema.Required = true;
return resolvedSchema;
}
}
// test for unresolved circular reference
if (_stack.Any(tc => tc.Type == type))
{
throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
}
JsonContract contract = ContractResolver.ResolveContract(type);
JsonConverter converter;
if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null)
{
JsonSchema converterSchema = converter.GetSchema();
if (converterSchema != null)
return converterSchema;
}
Push(new TypeSchema(type, new JsonSchema()));
if (explicitId != null)
CurrentSchema.Id = explicitId;
if (required)
CurrentSchema.Required = true;
CurrentSchema.Title = GetTitle(type);
CurrentSchema.Description = GetDescription(type);
if (converter != null)
{
// todo: Add GetSchema to JsonConverter and use here?
CurrentSchema.Type = JsonSchemaType.Any;
}
else
{
switch (contract.ContractType)
{
case JsonContractType.Object:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateObjectSchema(type, (JsonObjectContract) contract);
break;
case JsonContractType.Array:
CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute;
bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems);
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
if (collectionItemType != null)
{
CurrentSchema.Items = new List<JsonSchema>();
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false));
}
break;
case JsonContractType.Primitive:
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof (FlagsAttribute), true))
{
CurrentSchema.Enum = new List<JToken>();
EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type);
foreach (EnumValue<long> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
}
}
break;
case JsonContractType.String:
JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType))
? JsonSchemaType.String
: AddNullType(JsonSchemaType.String, valueRequired);
CurrentSchema.Type = schemaType;
break;
case JsonContractType.Dictionary:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
Type keyType;
Type valueType;
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
if (keyType != null)
{
JsonContract keyContract = ContractResolver.ResolveContract(keyType);
// can be converted to a string
if (keyContract.ContractType == JsonContractType.Primitive)
{
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
}
}
break;
case JsonContractType.Dynamic:
case JsonContractType.Linq:
CurrentSchema.Type = JsonSchemaType.Any;
break;
default:
throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
}
}
return Pop().Schema;
}
private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired)
{
if (valueRequired != Required.Always)
return type | JsonSchemaType.Null;
return type;
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private void GenerateObjectSchema(Type type, JsonObjectContract contract)
{
CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
foreach (JsonProperty property in contract.Properties)
{
if (!property.Ignored)
{
bool optional = property.NullValueHandling == NullValueHandling.Ignore ||
HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) ||
property.ShouldSerialize != null ||
property.GetIsSpecified != null;
JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional);
if (property.DefaultValue != null)
propertySchema.Default = JToken.FromObject(property.DefaultValue);
CurrentSchema.Properties.Add(property.PropertyName, propertySchema);
}
}
if (type.IsSealed())
CurrentSchema.AllowAdditionalProperties = false;
}
internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
{
// default value is Any
if (value == null)
return true;
bool match = ((value & flag) == flag);
if (match)
return true;
// integer is a subset of float
if (flag == JsonSchemaType.Integer && (value & JsonSchemaType.Float) == JsonSchemaType.Float)
return true;
return false;
}
private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired)
{
JsonSchemaType schemaType = JsonSchemaType.None;
if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type))
{
schemaType = JsonSchemaType.Null;
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
}
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type);
switch (typeCode)
{
case PrimitiveTypeCode.Empty:
case PrimitiveTypeCode.Object:
return schemaType | JsonSchemaType.String;
case PrimitiveTypeCode.Boolean:
return schemaType | JsonSchemaType.Boolean;
case PrimitiveTypeCode.Char:
return schemaType | JsonSchemaType.String;
case PrimitiveTypeCode.SByte:
case PrimitiveTypeCode.Byte:
case PrimitiveTypeCode.Int16:
case PrimitiveTypeCode.UInt16:
case PrimitiveTypeCode.Int32:
case PrimitiveTypeCode.UInt32:
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt64:
case PrimitiveTypeCode.BigInteger:
return schemaType | JsonSchemaType.Integer;
case PrimitiveTypeCode.Single:
case PrimitiveTypeCode.Double:
case PrimitiveTypeCode.Decimal:
return schemaType | JsonSchemaType.Float;
// convert to string?
case PrimitiveTypeCode.DateTime:
case PrimitiveTypeCode.DateTimeOffset:
return schemaType | JsonSchemaType.String;
case PrimitiveTypeCode.String:
case PrimitiveTypeCode.Uri:
case PrimitiveTypeCode.Guid:
case PrimitiveTypeCode.TimeSpan:
case PrimitiveTypeCode.Bytes:
return schemaType | JsonSchemaType.String;
default:
throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
}
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
internal class TestApp
{
private static unsafe long test_1(B* pb)
{
return pb->m_bval;
}
private static unsafe long test_8(B[] ab, long i)
{
fixed (B* pb = &ab[i])
{
return pb->m_bval;
}
}
private static unsafe long test_15(B* pb)
{
return (pb += 6)->m_bval;
}
private static unsafe long test_22(B* pb, long[,,] i, long ii)
{
return (&pb[++i[--ii, 0, 0]])->m_bval;
}
private static unsafe long test_29(AA* px)
{
return ((B*)AA.get_pb_i(px))->m_bval;
}
private static unsafe long test_36(byte diff, A* pa)
{
return ((B*)(((byte*)pa) + diff))->m_bval;
}
private static unsafe long test_43()
{
AA loc_x = new AA(0, 100);
return (&loc_x.m_b)[0].m_bval;
}
private static unsafe long test_50(B[][] ab, long i, long j)
{
fixed (B* pb = &ab[i][j])
{
return pb[0].m_bval;
}
}
private static unsafe long test_57(B* pb1, long i)
{
B* pb;
return (pb = (B*)(((byte*)pb1) + i * sizeof(B)))[0].m_bval;
}
private static unsafe long test_64(B* pb, long[,,] i, long ii, byte jj)
{
return (&pb[i[ii - jj, 0, ii - jj] = ii - 1])[0].m_bval;
}
private static unsafe long test_71(ulong ub, byte lb)
{
return ((B*)(ub | lb))[0].m_bval;
}
private static unsafe long test_78(long p, long s)
{
return ((B*)((p >> 4) | s))[0].m_bval;
}
private static unsafe long test_85(B[] ab)
{
fixed (B* pb = &ab[0])
{
return AA.get_bv1(pb);
}
}
private static unsafe long test_92(B* pb)
{
return AA.get_bv1((++pb));
}
private static unsafe long test_99(B* pb, long[] i, long ii)
{
return AA.get_bv1((&pb[i[ii]]));
}
private static unsafe long test_106(AA* px)
{
return AA.get_bv1((AA.get_pb_1(px) + 1));
}
private static unsafe long test_113(long pb)
{
return AA.get_bv1(((B*)checked(((long)pb) + 1)));
}
private static unsafe long test_120(B* pb)
{
return AA.get_bv2(*(pb--));
}
private static unsafe long test_127(AA[,] ab, long i)
{
long j = 0;
fixed (B* pb = &ab[--i, ++j].m_b)
{
return AA.get_bv2(*pb);
}
}
private static unsafe long test_134(B* pb1, long i)
{
B* pb;
return AA.get_bv2(*(pb = pb1 + i));
}
private static unsafe long test_141(B* pb1, B* pb2)
{
return AA.get_bv2(*(pb1 > pb2 ? pb2 : null));
}
private static unsafe long test_148(long pb)
{
return AA.get_bv2(*((B*)pb));
}
private static unsafe long test_155(double* pb, long i)
{
return AA.get_bv2(*((B*)(pb + i)));
}
private static unsafe long test_162(ref B b)
{
fixed (B* pb = &b)
{
return AA.get_bv3(ref *pb);
}
}
private static unsafe long test_169(B* pb)
{
return AA.get_bv3(ref *(--pb));
}
private static unsafe long test_176(B* pb, long i)
{
return AA.get_bv3(ref *(&pb[-(i << (int)i)]));
}
private static unsafe long test_183(AA* px)
{
return AA.get_bv3(ref *AA.get_pb(px));
}
private static unsafe long test_190(long pb)
{
return AA.get_bv3(ref *((B*)checked((long)pb)));
}
private static unsafe long test_197(B* pb)
{
return (pb++)->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_204(B[,] ab, long i, long j)
{
fixed (B* pb = &ab[i, j])
{
return pb->m_bval == 100 ? 100 : 101;
}
}
private static unsafe long test_211(B* pb1)
{
B* pb;
return (pb = pb1 - 8)->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_218(B* pb, B* pb1, B* pb2)
{
return (pb = pb + (pb2 - pb1))->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_225(B* pb1, bool trig)
{
fixed (B* pb = &AA.s_x.m_b)
{
return (trig ? pb : pb1)->m_bval == 100 ? 100 : 101;
}
}
private static unsafe long test_232(byte* pb)
{
return ((B*)(pb + 7))->m_bval == 100 ? 100 : 101;
}
private static unsafe long test_239(B b)
{
return AA.get_i1(&(&b)->m_bval);
}
private static unsafe long test_246()
{
fixed (B* pb = &AA.s_x.m_b)
{
return AA.get_i1(&pb->m_bval);
}
}
private static unsafe long test_253(B* pb, long i)
{
return AA.get_i1(&(&pb[i * 2])->m_bval);
}
private static unsafe long test_260(B* pb1, B* pb2)
{
return AA.get_i1(&(pb1 >= pb2 ? pb1 : null)->m_bval);
}
private static unsafe long test_267(long pb)
{
return AA.get_i1(&((B*)pb)->m_bval);
}
private static unsafe long test_274(B* pb)
{
return AA.get_i2(pb->m_bval);
}
private static unsafe long test_281(B[] ab, long i)
{
fixed (B* pb = &ab[i])
{
return AA.get_i2(pb->m_bval);
}
}
private static unsafe long test_288(B* pb)
{
return AA.get_i2((pb += 6)->m_bval);
}
private static unsafe long test_295(B* pb, long[,,] i, long ii)
{
return AA.get_i2((&pb[++i[--ii, 0, 0]])->m_bval);
}
private static unsafe long test_302(AA* px)
{
return AA.get_i2(((B*)AA.get_pb_i(px))->m_bval);
}
private static unsafe long test_309(byte diff, A* pa)
{
return AA.get_i2(((B*)(((byte*)pa) + diff))->m_bval);
}
private static unsafe long test_316()
{
AA loc_x = new AA(0, 100);
return AA.get_i3(ref (&loc_x.m_b)->m_bval);
}
private static unsafe long test_323(B[][] ab, long i, long j)
{
fixed (B* pb = &ab[i][j])
{
return AA.get_i3(ref pb->m_bval);
}
}
private static unsafe long test_330(B* pb1, long i)
{
B* pb;
return AA.get_i3(ref (pb = (B*)(((byte*)pb1) + i * sizeof(B)))->m_bval);
}
private static unsafe long test_337(B* pb, long[,,] i, long ii, byte jj)
{
return AA.get_i3(ref (&pb[i[ii - jj, 0, ii - jj] = ii - 1])->m_bval);
}
private static unsafe long test_344(ulong ub, byte lb)
{
return AA.get_i3(ref ((B*)(ub | lb))->m_bval);
}
private static unsafe long test_351(long p, long s)
{
return AA.get_i3(ref ((B*)((p >> 4) | s))->m_bval);
}
private static unsafe long test_358(B[] ab)
{
fixed (B* pb = &ab[0])
{
return AA.get_bv1(pb) != 100 ? 99 : 100;
}
}
private static unsafe long test_365(B* pb)
{
return AA.get_bv1((++pb)) != 100 ? 99 : 100;
}
private static unsafe long test_372(B* pb, long[] i, long ii)
{
return AA.get_bv1((&pb[i[ii]])) != 100 ? 99 : 100;
}
private static unsafe long test_379(AA* px)
{
return AA.get_bv1((AA.get_pb_1(px) + 1)) != 100 ? 99 : 100;
}
private static unsafe long test_386(long pb)
{
return AA.get_bv1(((B*)checked(((long)pb) + 1))) != 100 ? 99 : 100;
}
private static unsafe long test_393(B* pb)
{
return pb + 1 > pb ? 100 : 101;
}
private static unsafe int Main()
{
AA loc_x = new AA(0, 100);
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_1(&loc_x.m_b) != 100)
{
Console.WriteLine("test_1() failed.");
return 101;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_8(new B[] { new B(), new B(), loc_x.m_b }, 2) != 100)
{
Console.WriteLine("test_8() failed.");
return 108;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_15(&loc_x.m_b - 6) != 100)
{
Console.WriteLine("test_15() failed.");
return 115;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_22(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2) != 100)
{
Console.WriteLine("test_22() failed.");
return 122;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_29(&loc_x) != 100)
{
Console.WriteLine("test_29() failed.");
return 129;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_36((byte)(((long)&loc_x.m_b) - ((long)&loc_x.m_a)), &loc_x.m_a) != 100)
{
Console.WriteLine("test_36() failed.");
return 136;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_43() != 100)
{
Console.WriteLine("test_43() failed.");
return 143;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_50(new B[][] { new B[] { new B(), new B() }, new B[] { new B(), loc_x.m_b } }, 1, 1) != 100)
{
Console.WriteLine("test_50() failed.");
return 150;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_57(&loc_x.m_b - 8, 8) != 100)
{
Console.WriteLine("test_57() failed.");
return 157;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_64(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2, 2) != 100)
{
Console.WriteLine("test_64() failed.");
return 164;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_71(((ulong)&loc_x.m_b) & (~(ulong)0xff), unchecked((byte)&loc_x.m_b)) != 100)
{
Console.WriteLine("test_71() failed.");
return 171;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_78(((long)(&loc_x.m_b)) << 4, ((long)(&loc_x.m_b)) & 0xff000000) != 100)
{
Console.WriteLine("test_78() failed.");
return 178;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_85(new B[] { loc_x.m_b }) != 100)
{
Console.WriteLine("test_85() failed.");
return 185;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_92(&loc_x.m_b - 1) != 100)
{
Console.WriteLine("test_92() failed.");
return 192;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_99(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100)
{
Console.WriteLine("test_99() failed.");
return 199;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_106(&loc_x) != 100)
{
Console.WriteLine("test_106() failed.");
return 206;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_113((long)(((long)&loc_x.m_b) - 1)) != 100)
{
Console.WriteLine("test_113() failed.");
return 213;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_120(&loc_x.m_b) != 100)
{
Console.WriteLine("test_120() failed.");
return 220;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_127(new AA[,] { { new AA(), new AA() }, { new AA(), loc_x } }, 2) != 100)
{
Console.WriteLine("test_127() failed.");
return 227;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_134(&loc_x.m_b - 8, 8) != 100)
{
Console.WriteLine("test_134() failed.");
return 234;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_141(&loc_x.m_b + 1, &loc_x.m_b) != 100)
{
Console.WriteLine("test_141() failed.");
return 241;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_148((long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_148() failed.");
return 248;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_155(((double*)(&loc_x.m_b)) - 4, 4) != 100)
{
Console.WriteLine("test_155() failed.");
return 255;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_162(ref loc_x.m_b) != 100)
{
Console.WriteLine("test_162() failed.");
return 262;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_169(&loc_x.m_b + 1) != 100)
{
Console.WriteLine("test_169() failed.");
return 269;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_176(&loc_x.m_b + 2, 1) != 100)
{
Console.WriteLine("test_176() failed.");
return 276;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_183(&loc_x) != 100)
{
Console.WriteLine("test_183() failed.");
return 283;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_190((long)(long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_190() failed.");
return 290;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_197(&loc_x.m_b) != 100)
{
Console.WriteLine("test_197() failed.");
return 297;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_204(new B[,] { { new B(), new B() }, { new B(), loc_x.m_b } }, 1, 1) != 100)
{
Console.WriteLine("test_204() failed.");
return 304;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_211(&loc_x.m_b + 8) != 100)
{
Console.WriteLine("test_211() failed.");
return 311;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_218(&loc_x.m_b - 2, &loc_x.m_b - 1, &loc_x.m_b + 1) != 100)
{
Console.WriteLine("test_218() failed.");
return 318;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_225(&loc_x.m_b, true) != 100)
{
Console.WriteLine("test_225() failed.");
return 325;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_232(((byte*)(&loc_x.m_b)) - 7) != 100)
{
Console.WriteLine("test_232() failed.");
return 332;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_239(loc_x.m_b) != 100)
{
Console.WriteLine("test_239() failed.");
return 339;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_246() != 100)
{
Console.WriteLine("test_246() failed.");
return 346;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_253(&loc_x.m_b - 2, 1) != 100)
{
Console.WriteLine("test_253() failed.");
return 353;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_260(&loc_x.m_b, &loc_x.m_b) != 100)
{
Console.WriteLine("test_260() failed.");
return 360;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_267((long)&loc_x.m_b) != 100)
{
Console.WriteLine("test_267() failed.");
return 367;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_274(&loc_x.m_b) != 100)
{
Console.WriteLine("test_274() failed.");
return 374;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_281(new B[] { new B(), new B(), loc_x.m_b }, 2) != 100)
{
Console.WriteLine("test_281() failed.");
return 381;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_288(&loc_x.m_b - 6) != 100)
{
Console.WriteLine("test_288() failed.");
return 388;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_295(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2) != 100)
{
Console.WriteLine("test_295() failed.");
return 395;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_302(&loc_x) != 100)
{
Console.WriteLine("test_302() failed.");
return 402;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_309((byte)(((long)&loc_x.m_b) - ((long)&loc_x.m_a)), &loc_x.m_a) != 100)
{
Console.WriteLine("test_309() failed.");
return 409;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_316() != 100)
{
Console.WriteLine("test_316() failed.");
return 416;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_323(new B[][] { new B[] { new B(), new B() }, new B[] { new B(), loc_x.m_b } }, 1, 1) != 100)
{
Console.WriteLine("test_323() failed.");
return 423;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_330(&loc_x.m_b - 8, 8) != 100)
{
Console.WriteLine("test_330() failed.");
return 430;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_337(&loc_x.m_b - 1, new long[,,] { { { 0 } }, { { 0 } } }, 2, 2) != 100)
{
Console.WriteLine("test_337() failed.");
return 437;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_344(((ulong)&loc_x.m_b) & (~(ulong)0xff), unchecked((byte)&loc_x.m_b)) != 100)
{
Console.WriteLine("test_344() failed.");
return 444;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_351(((long)(&loc_x.m_b)) << 4, ((long)(&loc_x.m_b)) & 0xff000000) != 100)
{
Console.WriteLine("test_351() failed.");
return 451;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_358(new B[] { loc_x.m_b }) != 100)
{
Console.WriteLine("test_358() failed.");
return 458;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_365(&loc_x.m_b - 1) != 100)
{
Console.WriteLine("test_365() failed.");
return 465;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_372(&loc_x.m_b - 1, new long[] { 0, 1 }, 1) != 100)
{
Console.WriteLine("test_372() failed.");
return 472;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_379(&loc_x) != 100)
{
Console.WriteLine("test_379() failed.");
return 479;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_386((long)(((long)&loc_x.m_b) - 1)) != 100)
{
Console.WriteLine("test_386() failed.");
return 486;
}
AA.init_all(0);
loc_x = new AA(0, 100);
if (test_393((B*)1) != 100)
{
Console.WriteLine("test_393() failed.");
return 493;
}
Console.WriteLine("All tests passed.");
return 100;
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Configuration;
using System.Web;
using System.Web.Configuration;
using System.Web.Routing;
using System.Web.Security;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Security;
namespace Umbraco.Core.Configuration
{
//NOTE: Do not expose this class ever until we cleanup all configuration including removal of static classes, etc...
// we have this two tasks logged:
// http://issues.umbraco.org/issue/U4-58
// http://issues.umbraco.org/issue/U4-115
//TODO: Replace checking for if the app settings exist and returning an empty string, instead return the defaults!
/// <summary>
/// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information from web.config appsettings
/// </summary>
internal class GlobalSettings
{
#region Private static fields
private static readonly object Locker = new object();
//make this volatile so that we can ensure thread safety with a double check lock
private static volatile string _reservedUrlsCache;
private static string _reservedPathsCache;
private static HashSet<string> _reservedList = new HashSet<string>();
private static string _reservedPaths;
private static string _reservedUrls;
//ensure the built on (non-changeable) reserved paths are there at all times
private const string StaticReservedPaths = "~/app_plugins/,~/install/,";
private const string StaticReservedUrls = "~/config/splashes/booting.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,";
#endregion
/// <summary>
/// Used in unit testing to reset all config items that were set with property setters (i.e. did not come from config)
/// </summary>
private static void ResetInternal()
{
_reservedUrlsCache = null;
_reservedPaths = null;
_reservedUrls = null;
HasSmtpServer = null;
}
/// <summary>
/// Resets settings that were set programmatically, to their initial values.
/// </summary>
/// <remarks>To be used in unit tests.</remarks>
internal static void Reset()
{
ResetInternal();
}
public static bool HasSmtpServerConfigured(string appPath)
{
if (HasSmtpServer.HasValue) return HasSmtpServer.Value;
var config = WebConfigurationManager.OpenWebConfiguration(appPath);
var settings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");
// note: "noreply@example.com" is/was the sample SMTP from email - we'll regard that as "not configured"
if (settings == null || settings.Smtp == null || "noreply@example.com".Equals(settings.Smtp.From, StringComparison.OrdinalIgnoreCase)) return false;
if (settings.Smtp.SpecifiedPickupDirectory != null && string.IsNullOrEmpty(settings.Smtp.SpecifiedPickupDirectory.PickupDirectoryLocation) == false)
return true;
if (settings.Smtp.Network != null && string.IsNullOrEmpty(settings.Smtp.Network.Host) == false)
return true;
return false;
}
/// <summary>
/// For testing only
/// </summary>
internal static bool? HasSmtpServer { get; set; }
/// <summary>
/// Gets the reserved urls from web.config.
/// </summary>
/// <value>The reserved urls.</value>
public static string ReservedUrls
{
get
{
if (_reservedUrls == null)
{
var urls = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedUrls")
? ConfigurationManager.AppSettings["umbracoReservedUrls"]
: string.Empty;
//ensure the built on (non-changeable) reserved paths are there at all times
_reservedUrls = StaticReservedUrls + urls;
}
return _reservedUrls;
}
internal set { _reservedUrls = value; }
}
/// <summary>
/// Gets the reserved paths from web.config
/// </summary>
/// <value>The reserved paths.</value>
public static string ReservedPaths
{
get
{
if (_reservedPaths == null)
{
var reservedPaths = StaticReservedPaths;
//always add the umbraco path to the list
if (ConfigurationManager.AppSettings.ContainsKey("umbracoPath")
&& !ConfigurationManager.AppSettings["umbracoPath"].IsNullOrWhiteSpace())
{
reservedPaths += ConfigurationManager.AppSettings["umbracoPath"].EnsureEndsWith(',');
}
var allPaths = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedPaths")
? ConfigurationManager.AppSettings["umbracoReservedPaths"]
: string.Empty;
_reservedPaths = reservedPaths + allPaths;
}
return _reservedPaths;
}
internal set { _reservedPaths = value; }
}
/// <summary>
/// Gets the name of the content XML file.
/// </summary>
/// <value>The content XML.</value>
/// <remarks>
/// Defaults to ~/App_Data/umbraco.config
/// </remarks>
public static string ContentXmlFile
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoContentXML")
? ConfigurationManager.AppSettings["umbracoContentXML"]
: "~/App_Data/umbraco.config";
}
}
/// <summary>
/// Gets the path to the storage directory (/data by default).
/// </summary>
/// <value>The storage directory.</value>
public static string StorageDirectory
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoStorageDirectory")
? ConfigurationManager.AppSettings["umbracoStorageDirectory"]
: "~/App_Data";
}
}
/// <summary>
/// Gets the path to umbraco's root directory (/umbraco by default).
/// </summary>
/// <value>The path.</value>
public static string Path
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoPath")
? IOHelper.ResolveUrl(ConfigurationManager.AppSettings["umbracoPath"])
: string.Empty;
}
}
/// <summary>
/// This returns the string of the MVC Area route.
/// </summary>
/// <remarks>
/// THIS IS TEMPORARY AND SHOULD BE REMOVED WHEN WE MIGRATE/UPDATE THE CONFIG SETTINGS TO BE A REAL CONFIG SECTION
/// AND SHOULD PROBABLY BE HANDLED IN A MORE ROBUST WAY.
///
/// This will return the MVC area that we will route all custom routes through like surface controllers, etc...
/// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin
/// we will convert the '/' to '-' and use that as the path. its a bit lame but will work.
///
/// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something
/// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco".
/// </remarks>
public static string UmbracoMvcArea
{
get
{
if (Path.IsNullOrWhiteSpace())
{
throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified");
}
var path = Path;
if (path.StartsWith(SystemDirectories.Root)) // beware of TrimStart, see U4-2518
path = path.Substring(SystemDirectories.Root.Length);
return path.TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower();
}
}
/// <summary>
/// Gets the path to umbraco's client directory (/umbraco_client by default).
/// This is a relative path to the Umbraco Path as it always must exist beside the 'umbraco'
/// folder since the CSS paths to images depend on it.
/// </summary>
/// <value>The path.</value>
public static string ClientPath
{
get
{
return Path + "/../umbraco_client";
}
}
/// <summary>
/// Gets the database connection string
/// </summary>
/// <value>The database connection string.</value>
[Obsolete("Use System.Configuration.ConfigurationManager.ConnectionStrings[\"umbracoDbDSN\"] instead")]
public static string DbDsn
{
get
{
var settings = ConfigurationManager.ConnectionStrings[Constants.System.UmbracoConnectionName];
var connectionString = string.Empty;
if (settings != null)
{
connectionString = settings.ConnectionString;
// The SqlCe connectionString is formatted slightly differently, so we need to update it
if (settings.ProviderName.Contains("SqlServerCe"))
connectionString = string.Format("datalayer=SQLCE4Umbraco.SqlCEHelper,SQLCE4Umbraco;{0}", connectionString);
}
return connectionString;
}
set
{
if (DbDsn != value)
{
if (value.ToLower().Contains("SQLCE4Umbraco.SqlCEHelper".ToLower()))
{
ApplicationContext.Current.DatabaseContext.ConfigureEmbeddedDatabaseConnection();
}
else
{
ApplicationContext.Current.DatabaseContext.ConfigureDatabaseConnection(value);
}
}
}
}
/// <summary>
/// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance.
/// </summary>
/// <value>The configuration status.</value>
public static string ConfigurationStatus
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoConfigurationStatus")
? ConfigurationManager.AppSettings["umbracoConfigurationStatus"]
: string.Empty;
}
set
{
SaveSetting("umbracoConfigurationStatus", value);
}
}
/// <summary>
/// Gets or sets the Umbraco members membership providers' useLegacyEncoding state. This will return a boolean
/// </summary>
/// <value>The useLegacyEncoding status.</value>
public static bool UmbracoMembershipProviderLegacyEncoding
{
get
{
return IsConfiguredMembershipProviderUsingLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName);
}
set
{
SetMembershipProvidersLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName, value);
}
}
/// <summary>
/// Gets or sets the Umbraco users membership providers' useLegacyEncoding state. This will return a boolean
/// </summary>
/// <value>The useLegacyEncoding status.</value>
public static bool UmbracoUsersMembershipProviderLegacyEncoding
{
get
{
return IsConfiguredMembershipProviderUsingLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider);
}
set
{
SetMembershipProvidersLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider, value);
}
}
/// <summary>
/// Saves a setting into the configuration file.
/// </summary>
/// <param name="key">Key of the setting to be saved.</param>
/// <param name="value">Value of the setting to be saved.</param>
internal static void SaveSetting(string key, string value)
{
var fileName = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root));
var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single();
// Update appSetting if it exists, or else create a new appSetting for the given key and value
var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key);
if (setting == null)
appSettings.Add(new XElement("add", new XAttribute("key", key), new XAttribute("value", value)));
else
setting.Attribute("value").Value = value;
xml.Save(fileName, SaveOptions.DisableFormatting);
ConfigurationManager.RefreshSection("appSettings");
}
/// <summary>
/// Removes a setting from the configuration file.
/// </summary>
/// <param name="key">Key of the setting to be removed.</param>
internal static void RemoveSetting(string key)
{
var fileName = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root));
var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace);
var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single();
var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key);
if (setting != null)
{
setting.Remove();
xml.Save(fileName, SaveOptions.DisableFormatting);
ConfigurationManager.RefreshSection("appSettings");
}
}
private static void SetMembershipProvidersLegacyEncoding(string providerName, bool useLegacyEncoding)
{
//check if this can even be configured.
var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase;
if (membershipProvider == null)
{
return;
}
if (membershipProvider.GetType().Namespace == "umbraco.providers.members")
{
//its the legacy one, this cannot be changed
return;
}
var webConfigFilename = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root));
var webConfigXml = XDocument.Load(webConfigFilename, LoadOptions.PreserveWhitespace);
var membershipConfigs = webConfigXml.XPathSelectElements("configuration/system.web/membership/providers/add").ToList();
if (membershipConfigs.Any() == false)
return;
var provider = membershipConfigs.SingleOrDefault(c => c.Attribute("name") != null && c.Attribute("name").Value == providerName);
if (provider == null)
return;
provider.SetAttributeValue("useLegacyEncoding", useLegacyEncoding);
webConfigXml.Save(webConfigFilename, SaveOptions.DisableFormatting);
}
private static bool IsConfiguredMembershipProviderUsingLegacyEncoding(string providerName)
{
//check if this can even be configured.
var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase;
if (membershipProvider == null)
{
return false;
}
return membershipProvider.UseLegacyEncoding;
}
/// <summary>
/// Gets the full path to root.
/// </summary>
/// <value>The fullpath to root.</value>
public static string FullpathToRoot
{
get { return IOHelper.GetRootDirectorySafe(); }
}
/// <summary>
/// Gets a value indicating whether umbraco is running in [debug mode].
/// </summary>
/// <value><c>true</c> if [debug mode]; otherwise, <c>false</c>.</value>
public static bool DebugMode
{
get
{
try
{
if (HttpContext.Current != null)
{
return HttpContext.Current.IsDebuggingEnabled;
}
//go and get it from config directly
var section = ConfigurationManager.GetSection("system.web/compilation") as CompilationSection;
return section != null && section.Debug;
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets a value indicating whether the current version of umbraco is configured.
/// </summary>
/// <value><c>true</c> if configured; otherwise, <c>false</c>.</value>
[Obsolete("Do not use this, it is no longer in use and will be removed from the codebase in future versions")]
internal static bool Configured
{
get
{
try
{
string configStatus = ConfigurationStatus;
string currentVersion = UmbracoVersion.GetSemanticVersion().ToSemanticString();
if (currentVersion != configStatus)
{
LogHelper.Debug<GlobalSettings>("CurrentVersion different from configStatus: '" + currentVersion + "','" + configStatus + "'");
}
return (configStatus == currentVersion);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the time out in minutes.
/// </summary>
/// <value>The time out in minutes.</value>
public static int TimeOutInMinutes
{
get
{
try
{
return int.Parse(ConfigurationManager.AppSettings["umbracoTimeOutInMinutes"]);
}
catch
{
return 20;
}
}
}
/// <summary>
/// Gets a value indicating whether umbraco uses directory urls.
/// </summary>
/// <value><c>true</c> if umbraco uses directory urls; otherwise, <c>false</c>.</value>
public static bool UseDirectoryUrls
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoUseDirectoryUrls"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Returns the number of days that should take place between version checks.
/// </summary>
/// <value>The version check period in days (0 = never).</value>
public static int VersionCheckPeriod
{
get
{
try
{
return int.Parse(ConfigurationManager.AppSettings["umbracoVersionCheckPeriod"]);
}
catch
{
return 7;
}
}
}
/// <summary>
/// Returns a string value to determine if umbraco should disbable xslt extensions
/// </summary>
/// <value><c>"true"</c> if version xslt extensions are disabled, otherwise, <c>"false"</c></value>
[Obsolete("This is no longer used and will be removed from the codebase in future releases")]
public static string DisableXsltExtensions
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoDisableXsltExtensions")
? ConfigurationManager.AppSettings["umbracoDisableXsltExtensions"]
: "false";
}
}
internal static bool ContentCacheXmlStoredInCodeGen
{
get { return LocalTempStorageLocation == LocalTempStorage.AspNetTemp; }
}
/// <summary>
/// This is the location type to store temporary files such as cache files or other localized files for a given machine
/// </summary>
/// <remarks>
/// Currently used for the xml cache file and the plugin cache files
/// </remarks>
internal static LocalTempStorage LocalTempStorageLocation
{
get
{
//there's a bunch of backwards compat config checks here....
//This is the current one
if (ConfigurationManager.AppSettings.ContainsKey("umbracoLocalTempStorage"))
{
return Enum<LocalTempStorage>.Parse(ConfigurationManager.AppSettings["umbracoLocalTempStorage"]);
}
//This one is old
if (ConfigurationManager.AppSettings.ContainsKey("umbracoContentXMLStorage"))
{
return Enum<LocalTempStorage>.Parse(ConfigurationManager.AppSettings["umbracoContentXMLStorage"]);
}
//This one is older
if (ConfigurationManager.AppSettings.ContainsKey("umbracoContentXMLUseLocalTemp"))
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoContentXMLUseLocalTemp"])
? LocalTempStorage.AspNetTemp
: LocalTempStorage.Default;
}
return LocalTempStorage.Default;
}
}
/// <summary>
/// Returns a string value to determine if umbraco should use Xhtml editing mode in the wysiwyg editor
/// </summary>
/// <value><c>"true"</c> if Xhtml mode is enable, otherwise, <c>"false"</c></value>
[Obsolete("This is no longer used and will be removed from the codebase in future releases")]
public static string EditXhtmlMode
{
get { return "true"; }
}
/// <summary>
/// Gets the default UI language.
/// </summary>
/// <value>The default UI language.</value>
public static string DefaultUILanguage
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoDefaultUILanguage")
? ConfigurationManager.AppSettings["umbracoDefaultUILanguage"]
: string.Empty;
}
}
/// <summary>
/// Gets the profile URL.
/// </summary>
/// <value>The profile URL.</value>
public static string ProfileUrl
{
get
{
//the default will be 'profiler'
return ConfigurationManager.AppSettings.ContainsKey("umbracoProfileUrl")
? ConfigurationManager.AppSettings["umbracoProfileUrl"]
: "profiler";
}
}
/// <summary>
/// Gets a value indicating whether umbraco should hide top level nodes from generated urls.
/// </summary>
/// <value>
/// <c>true</c> if umbraco hides top level nodes from urls; otherwise, <c>false</c>.
/// </value>
public static bool HideTopLevelNodeFromPath
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoHideTopLevelNodeFromPath"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the current version.
/// </summary>
/// <value>The current version.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static string CurrentVersion
{
get { return UmbracoVersion.GetSemanticVersion().ToSemanticString(); }
}
/// <summary>
/// Gets the major version number.
/// </summary>
/// <value>The major version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionMajor
{
get
{
return UmbracoVersion.Current.Major;
}
}
/// <summary>
/// Gets the minor version number.
/// </summary>
/// <value>The minor version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionMinor
{
get
{
return UmbracoVersion.Current.Minor;
}
}
/// <summary>
/// Gets the patch version number.
/// </summary>
/// <value>The patch version number.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static int VersionPatch
{
get
{
return UmbracoVersion.Current.Build;
}
}
/// <summary>
/// Gets the version comment (like beta or RC).
/// </summary>
/// <value>The version comment.</value>
[Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)]
public static string VersionComment
{
get
{
return Umbraco.Core.Configuration.UmbracoVersion.CurrentComment;
}
}
/// <summary>
/// Gets the ClientDependency handler path. Backoffice needs it to be in the same domain,
/// in case that the global CD uses some CD DNS name.
/// </summary>
public static string ClientDependencyBackOfficePath
{
get
{
return ConfigurationManager.AppSettings.ContainsKey("umbracoClientDependencyPath")
? ConfigurationManager.AppSettings["umbracoClientDependencyPath"]
: null;
}
}
/// <summary>
/// Requests the is in umbraco application directory structure.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public static bool RequestIsInUmbracoApplication(HttpContext context)
{
return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1;
}
public static bool RequestIsInUmbracoApplication(HttpContextBase context)
{
return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1;
}
/// <summary>
/// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice.
/// </summary>
/// <value><c>true</c> if [use SSL]; otherwise, <c>false</c>.</value>
public static bool UseSSL
{
get
{
try
{
return bool.Parse(ConfigurationManager.AppSettings["umbracoUseSSL"]);
}
catch
{
return false;
}
}
}
/// <summary>
/// Gets the umbraco license.
/// </summary>
/// <value>The license.</value>
public static string License
{
get
{
string license =
"<A href=\"http://umbraco.org/redir/license\" target=\"_blank\">the open source license MIT</A>. The umbraco UI is freeware licensed under the umbraco license.";
var versionDoc = new XmlDocument();
var versionReader = new XmlTextReader(IOHelper.MapPath(SystemDirectories.Umbraco + "/version.xml"));
versionDoc.Load(versionReader);
versionReader.Close();
// check for license
try
{
string licenseUrl =
versionDoc.SelectSingleNode("/version/licensing/licenseUrl").FirstChild.Value;
string licenseValidation =
versionDoc.SelectSingleNode("/version/licensing/licenseValidation").FirstChild.Value;
string licensedTo =
versionDoc.SelectSingleNode("/version/licensing/licensedTo").FirstChild.Value;
if (licensedTo != "" && licenseUrl != "")
{
license = "umbraco Commercial License<br/><b>Registered to:</b><br/>" +
licensedTo.Replace("\n", "<br/>") + "<br/><b>For use with domain:</b><br/>" +
licenseUrl;
}
}
catch
{
}
return license;
}
}
/// <summary>
/// Determines whether the current request is reserved based on the route table and
/// whether the specified URL is reserved or is inside a reserved path.
/// </summary>
/// <param name="url"></param>
/// <param name="httpContext"></param>
/// <param name="routes">The route collection to lookup the request in</param>
/// <returns></returns>
public static bool IsReservedPathOrUrl(string url, HttpContextBase httpContext, RouteCollection routes)
{
if (httpContext == null) throw new ArgumentNullException("httpContext");
if (routes == null) throw new ArgumentNullException("routes");
//check if the current request matches a route, if so then it is reserved.
var route = routes.GetRouteData(httpContext);
if (route != null)
return true;
//continue with the standard ignore routine
return IsReservedPathOrUrl(url);
}
/// <summary>
/// Determines whether the specified URL is reserved or is inside a reserved path.
/// </summary>
/// <param name="url">The URL to check.</param>
/// <returns>
/// <c>true</c> if the specified URL is reserved; otherwise, <c>false</c>.
/// </returns>
public static bool IsReservedPathOrUrl(string url)
{
if (_reservedUrlsCache == null)
{
lock (Locker)
{
if (_reservedUrlsCache == null)
{
// store references to strings to determine changes
_reservedPathsCache = GlobalSettings.ReservedPaths;
_reservedUrlsCache = GlobalSettings.ReservedUrls;
// add URLs and paths to a new list
var newReservedList = new HashSet<string>();
foreach (var reservedUrlTrimmed in _reservedUrlsCache
.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim().ToLowerInvariant())
.Where(x => x.IsNullOrWhiteSpace() == false)
.Select(reservedUrl => IOHelper.ResolveUrl(reservedUrl).Trim().EnsureStartsWith("/"))
.Where(reservedUrlTrimmed => reservedUrlTrimmed.IsNullOrWhiteSpace() == false))
{
newReservedList.Add(reservedUrlTrimmed);
}
foreach (var reservedPathTrimmed in _reservedPathsCache
.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim().ToLowerInvariant())
.Where(x => x.IsNullOrWhiteSpace() == false)
.Select(reservedPath => IOHelper.ResolveUrl(reservedPath).Trim().EnsureStartsWith("/").EnsureEndsWith("/"))
.Where(reservedPathTrimmed => reservedPathTrimmed.IsNullOrWhiteSpace() == false))
{
newReservedList.Add(reservedPathTrimmed);
}
// use the new list from now on
_reservedList = newReservedList;
}
}
}
//The url should be cleaned up before checking:
// * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/'
// * We shouldn't be comparing the query at all
var pathPart = url.Split(new[] {'?'}, StringSplitOptions.RemoveEmptyEntries)[0].ToLowerInvariant();
if (pathPart.Contains(".") == false)
{
pathPart = pathPart.EnsureEndsWith('/');
}
// return true if url starts with an element of the reserved list
return _reservedList.Any(x => pathPart.InvariantStartsWith(x));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.