context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Referensi_Status_List : System.Web.UI.Page
{
public int NoKe = 0;
protected string dsReportSessionName = "dsListRefStatus";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["StatusManagement"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
else
{
btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddStatus");
}
btnSearch.Text = Resources.GetString("", "Search");
ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif";
ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif";
ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif";
ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif";
UpdateDataView(true);
}
}
#region .Update View Data
//////////////////////////////////////////////////////////////////////
// PhysicalDataRead
// ------------------------------------------------------------------
/// <summary>
/// This function is responsible for loading data from database.
/// </summary>
/// <returns>DataSet</returns>
public DataSet PhysicalDataRead()
{
// Local variables
DataSet oDS = new DataSet();
// Get Data
SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status();
DataTable myData = myObj.SelectAll();
oDS.Tables.Add(myData);
return oDS;
}
/// <summary>
/// This function is responsible for binding data to Datagrid.
/// </summary>
/// <param name="dv"></param>
private void BindData(DataView dv)
{
// Sets the sorting order
dv.Sort = DataGridList.Attributes["SortField"];
if (DataGridList.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
DataGridList.ShowFooter = false;
int intRowCount = dv.Count;
int intPageSaze = DataGridList.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (DataGridList.CurrentPageIndex >= intPageCount)
DataGridList.CurrentPageIndex = intPageCount - 1;
}
else
{
DataGridList.ShowFooter = true;
DataGridList.CurrentPageIndex = 0;
}
// Re-binds the grid
NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex;
DataGridList.DataSource = dv;
DataGridList.DataBind();
int CurrentPage = DataGridList.CurrentPageIndex + 1;
lblCurrentPage.Text = CurrentPage.ToString();
lblTotalPage.Text = DataGridList.PageCount.ToString();
lblTotalRecord.Text = dv.Count.ToString();
}
/// <summary>
/// This function is responsible for loading data from database and store to Session.
/// </summary>
/// <param name="strDataSessionName"></param>
public void DataFromSourceToMemory(String strDataSessionName)
{
// Gets rows from the data source
DataSet oDS = PhysicalDataRead();
// Stores it in the session cache
Session[strDataSessionName] = oDS;
}
/// <summary>
/// This function is responsible for update data view from datagrid.
/// </summary>
/// <param name="requery">true = get data from database, false= get data from session</param>
public void UpdateDataView(bool requery)
{
// Retrieves the data
if ((Session[dsReportSessionName] == null) || (requery))
{
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString());
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
public void UpdateDataView()
{
// Retrieves the data
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
#endregion
#region .Event DataGridList
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// HANDLERs //
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGridList.CurrentPageIndex = e.NewPageIndex;
DataGridList.SelectedIndex = -1;
UpdateDataView();
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="nPageIndex"></param>
public void GoToPage(Object sender, int nPageIndex)
{
DataGridPageChangedEventArgs evPage;
evPage = new DataGridPageChangedEventArgs(sender, nPageIndex);
PageChanged(sender, evPage);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a first page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToFirst(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, 0);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a previous page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToPrev(Object sender, ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex > 0)
{
GoToPage(sender, DataGridList.CurrentPageIndex - 1);
}
else
{
GoToPage(sender, 0);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a next page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1))
{
GoToPage(sender, DataGridList.CurrentPageIndex + 1);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a last page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToLast(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, DataGridList.PageCount - 1);
}
/// <summary>
/// This function is invoked when you click on a column's header to
/// sort by that. It just saves the current sort field name and
/// refreshes the grid.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SortByColumn(Object sender, DataGridSortCommandEventArgs e)
{
String strSortBy = DataGridList.Attributes["SortField"];
String strSortAscending = DataGridList.Attributes["SortAscending"];
// Sets the new sorting field
DataGridList.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
DataGridList.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
OnClearSelection(null, null);
UpdateDataView();
}
/// <summary>
/// The function gets invoked when a new item is being created in
/// the datagrid. This applies to pager, header, footer, regular
/// and alternating items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageItemCreated(Object sender, DataGridItemEventArgs e)
{
// Get the newly created item
ListItemType itemType = e.Item.ItemType;
//////////////////////////////////////////////////////////
// Is it the HEADER?
if (itemType == ListItemType.Header)
{
for (int i = 0; i < DataGridList.Columns.Count; i++)
{
// draw to reflect sorting
if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression)
{
//////////////////////////////////////////////
// Should be much easier this way:
// ------------------------------------------
// TableCell cell = e.Item.Cells[i];
// Label lblSorted = new Label();
// lblSorted.Font = "webdings";
// lblSorted.Text = strOrder;
// cell.Controls.Add(lblSorted);
//
// but it seems it doesn't work <g>
//////////////////////////////////////////////
// Add a non-clickable triangle to mean desc or asc.
// The </a> ensures that what follows is non-clickable
TableCell cell = e.Item.Cells[i];
LinkButton lb = (LinkButton)cell.Controls[0];
//lb.Text += "</a> <span style=font-family:webdings;>" + GetOrderSymbol() + "</span>";
lb.Text += "</a> <img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >";
}
}
}
//////////////////////////////////////////////////////////
// Is it the PAGER?
if (itemType == ListItemType.Pager)
{
// There's just one control in the list...
TableCell pager = (TableCell)e.Item.Controls[0];
// Enumerates all the items in the pager...
for (int i = 0; i < pager.Controls.Count; i += 2)
{
// It can be either a Label or a Link button
try
{
Label l = (Label)pager.Controls[i];
l.Text = "Hal " + l.Text;
l.CssClass = "CurrentPage";
}
catch
{
LinkButton h = (LinkButton)pager.Controls[i];
h.Text = "[ " + h.Text + " ]";
h.CssClass = "HotLink";
}
}
}
}
/// <summary>
/// Verifies whether the current sort is ascending or descending and
/// returns an appropriate display text (i.e., a webding)
/// </summary>
/// <returns></returns>
private String GetOrderSymbol()
{
bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no");
//return (bDescending ? " 6" : " 5");
return (bDescending ? "downbr.gif" : "upbr.gif");
}
/// <summary>
/// When clicked clears the current selection if any
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnClearSelection(Object sender, EventArgs e)
{
DataGridList.SelectedIndex = -1;
}
#endregion
#region .Event Button
/// <summary>
/// When clicked, redirect to form add for inserts a new record to the database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnNewRecord(Object sender, EventArgs e)
{
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("Add.aspx?CurrentPage=" + CurrentPage);
}
/// <summary>
/// When clicked, filter data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSearch(Object sender, System.EventArgs e)
{
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
DataView dv = ds.Tables[0].DefaultView;
if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Nama")
dv.RowFilter = " Nama LIKE '%" + txtSearch.Text + "%'";
else if (cmbFilterBy.Items[cmbFilterBy.SelectedIndex].Value == "Keterangan")
dv.RowFilter = " Keterangan LIKE '%" + txtSearch.Text + "%'";
else
dv.RowFilter = "";
BindData(dv);
}
#endregion
#region .Update Link Item Butom
/// <summary>
/// The function is responsible for get link button form.
/// </summary>
/// <param name="szId"></param>
/// <param name="CurrentPage"></param>
/// <returns></returns>
public string GetLinkButton(string Id, string Nama, string CurrentPage)
{
string szResult = "";
if (Session["StatusManagement"] != null)
{
szResult += "<a class=\"toolbar\" href=\"Edit.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Edit") + "</a>";
if (int.Parse(Id) > 23)
{
szResult += "<a class=\"toolbar\" href=\"Delete.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Delete") + "</a>";
}
}
return szResult;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace DocDBAPIRest.Models
{
/// <summary>
/// A permission is an authorization token associated with a user for authorized access to a specific resource.
/// </summary>
public class Permission : IEquatable<Permission>
{
/// <summary>
/// This is a user settable property. It is the unique name that identifies the permission, i.e. no two permissions
/// will share the same id within a user. The id must not exceed 255 characters.
/// </summary>
/// <value>
/// This is a user settable property. It is the unique name that identifies the permission, i.e. no two permissions
/// will share the same id within a user. The id must not exceed 255 characters.
/// </value>
public string Id { get; set; }
/// <summary>
/// The access mode on the resource for the user: All or Read. All provides read, write, and delete access to a
/// resource. Read restricts the user to read access on the resource.
/// </summary>
/// <value>
/// The access mode on the resource for the user: All or Read. All provides read, write, and delete access to a
/// resource. Read restricts the user to read access on the resource.
/// </value>
public List<string> PermissionMode { get; set; }
/// <summary>
/// The full addressable path of the resource associated with the permission. For example,
/// dbs/ruJjAA==/colls/ruJjAM9UnAA=/.
/// </summary>
/// <value>
/// The full addressable path of the resource associated with the permission. For example,
/// dbs/ruJjAA==/colls/ruJjAM9UnAA=/.
/// </value>
public string Resource { get; set; }
/// <summary>
/// This is a system generated property.
/// </summary>
/// <value>This is a system generated property.</value>
public string Rid { get; set; }
/// <summary>
/// This is a system generated property. It specifies the last updated timestamp of the resource. The value is a
/// timestamp
/// </summary>
/// <value>
/// This is a system generated property. It specifies the last updated timestamp of the resource. The value is a
/// timestamp
/// </value>
public string Ts { get; set; }
/// <summary>
/// This is a system generated property.
/// </summary>
/// <value>This is a system generated property.</value>
public string Self { get; set; }
/// <summary>
/// This is a system generated property that specifies the resource etag required for optimistic concurrency control.
/// </summary>
/// <value>
/// This is a system generated property that specifies the resource etag required for optimistic concurrency
/// control.
/// </value>
public string Etag { get; set; }
/// <summary>
/// This is a system generated resource token for the particular resource and user.
/// </summary>
/// <value>This is a system generated resource token for the particular resource and user.</value>
public string Token { get; set; }
/// <summary>
/// Returns true if Permission instances are equal
/// </summary>
/// <param name="other">Instance of Permission to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Permission other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
Id == other.Id ||
Id != null &&
Id.Equals(other.Id)
) &&
(
PermissionMode == other.PermissionMode ||
PermissionMode != null &&
PermissionMode.SequenceEqual(other.PermissionMode)
) &&
(
Resource == other.Resource ||
Resource != null &&
Resource.Equals(other.Resource)
) &&
(
Rid == other.Rid ||
Rid != null &&
Rid.Equals(other.Rid)
) &&
(
Ts == other.Ts ||
Ts != null &&
Ts.Equals(other.Ts)
) &&
(
Self == other.Self ||
Self != null &&
Self.Equals(other.Self)
) &&
(
Etag == other.Etag ||
Etag != null &&
Etag.Equals(other.Etag)
) &&
(
Token == other.Token ||
Token != null &&
Token.Equals(other.Token)
);
}
/// <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 Permission {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" PermissionMode: ").Append(PermissionMode).Append("\n");
sb.Append(" Resource: ").Append(Resource).Append("\n");
sb.Append(" Rid: ").Append(Rid).Append("\n");
sb.Append(" Ts: ").Append(Ts).Append("\n");
sb.Append(" Self: ").Append(Self).Append("\n");
sb.Append(" Etag: ").Append(Etag).Append("\n");
sb.Append(" Token: ").Append(Token).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 Equals(obj as Permission);
}
/// <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
{
var hash = 41;
// Suitable nullity checks etc, of course :)
if (Id != null)
hash = hash*57 + Id.GetHashCode();
if (PermissionMode != null)
hash = hash*57 + PermissionMode.GetHashCode();
if (Resource != null)
hash = hash*57 + Resource.GetHashCode();
if (Rid != null)
hash = hash*57 + Rid.GetHashCode();
if (Ts != null)
hash = hash*57 + Ts.GetHashCode();
if (Self != null)
hash = hash*57 + Self.GetHashCode();
if (Etag != null)
hash = hash*57 + Etag.GetHashCode();
if (Token != null)
hash = hash*57 + Token.GetHashCode();
return hash;
}
}
}
}
| |
//
// System.Xml.DeserializationTests
//
// Author:
// Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
//
// (C) 2003 Atsushi Enomoto
//
//
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using NUnit.Framework;
using MonoTests.System.Xml.TestClasses;
namespace MonoTests.System.XmlSerialization
{
public class Sample
{
public string Text;
public string [] ArrayText;
}
[TestFixture]
public class DeserializationTests
{
object result;
private object Deserialize (Type t, string xml)
{
StringReader sr = new StringReader (xml);
XmlReader xr = new XmlTextReader (sr);
return Deserialize (t, xr);
}
private object DeserializeEncoded (Type t, string xml)
{
StringReader sr = new StringReader (xml);
XmlReader xr = new XmlTextReader (sr);
return DeserializeEncoded (t, xr);
}
private object Deserialize (Type t, XmlReader xr)
{
XmlSerializer ser = new XmlSerializer (t);
result = ser.Deserialize (xr);
return result;
}
private object DeserializeEncoded (Type t, XmlReader xr)
{
SoapReflectionImporter im = new SoapReflectionImporter ();
XmlTypeMapping tm = im.ImportTypeMapping (t);
XmlSerializer ser = new XmlSerializer (tm);
result = ser.Deserialize (xr);
return result;
}
[Test]
public void SimpleDeserialize ()
{
Deserialize (typeof (Sample), "<Sample><Text>Test.</Text></Sample>");
Assertion.AssertEquals (typeof (Sample), result.GetType ());
Sample sample = result as Sample;
Assertion.AssertEquals ("Test.", sample.Text);
}
[Test]
public void DeserializeInt ()
{
Deserialize (typeof (int), "<int>10</int>");
Assertion.AssertEquals (typeof (int), result.GetType ());
Assertion.AssertEquals (10, result);
}
[Test]
public void DeserializeSimpleArray ()
{
Deserialize (typeof (Sample), "<Sample><ArrayText><string>Test1</string><string>Test2</string></ArrayText></Sample>");
Assertion.AssertEquals (typeof (Sample), result.GetType ());
Sample sample = result as Sample;
Assertion.AssertEquals ("Test1", sample.ArrayText [0]);
Assertion.AssertEquals ("Test2", sample.ArrayText [1]);
}
[Test]
public void DeserializeEmptyEnum ()
{
Field f = Deserialize (typeof (Field), "<field modifiers=\"\" />") as Field;
Assertion.AssertEquals (MapModifiers.Public, f.Modifiers);
}
[Test]
public void DeserializePrivateCollection ()
{
MemoryStream ms = new MemoryStream ();
Container c = new Container();
c.Items.Add(1);
XmlSerializer serializer = new XmlSerializer(typeof(Container));
serializer.Serialize(ms, c);
ms.Position = 0;
c = (Container) serializer.Deserialize (ms);
Assertion.AssertEquals (1, c.Items[0]);
}
[Test]
[Category("NotDotNet")]
[ExpectedException (typeof (InvalidOperationException))]
public void DeserializeEmptyPrivateCollection ()
{
MemoryStream ms = new MemoryStream ();
Container2 c = new Container2(true);
c.Items.Add(1);
XmlSerializer serializer = new XmlSerializer(typeof(Container2));
serializer.Serialize(ms, c);
ms.Position = 0;
c = (Container2) serializer.Deserialize (ms);
}
[Test]
[Category("NotDotNet")]
public void DeserializeArrayReferences ()
{
string s = "<Sample xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">";
s += "<ArrayText xmlns:n3=\"http://schemas.xmlsoap.org/soap/encoding/\" xsi:type=\"n3:Array\" n3:arrayType=\"xsd:string[2]\">";
s += "<item href=\"#id-606830706\"></item>";
s += "<item xsi:type=\"xsd:string\">Hola</item>";
s += "</ArrayText>";
s += "<string id=\"id-606830706\" xsi:type=\"xsd:string\">Adeu</string>";
s += "</Sample>";
DeserializeEncoded (typeof(Sample), s);
}
[Test]
public void TestDeserializeXmlNodeArray ()
{
object ob = Deserialize (typeof(object), "<anyType at=\"1\"><elem1/><elem2/></anyType>");
Assertion.Assert ("Is node array", ob is XmlNode[]);
XmlNode[] nods = (XmlNode[]) ob;
Assertion.AssertEquals ("lengh", 3, nods.Length);
Assertion.Assert ("#1", nods[0] is XmlAttribute);
Assertion.AssertEquals ("#2", "at", ((XmlAttribute)nods[0]).LocalName);
Assertion.AssertEquals ("#3", "1", ((XmlAttribute)nods[0]).Value);
Assertion.Assert ("#4", nods[1] is XmlElement);
Assertion.AssertEquals ("#5", "elem1", ((XmlElement)nods[1]).LocalName);
Assertion.Assert ("#6", nods[2] is XmlElement);
Assertion.AssertEquals ("#7", "elem2", ((XmlElement)nods[2]).LocalName);
}
[Test]
public void TestDeserializeXmlElement ()
{
object ob = Deserialize (typeof(XmlElement), "<elem/>");
Assertion.Assert ("#1", ob is XmlElement);
Assertion.AssertEquals ("#2", "elem", ((XmlElement)ob).LocalName);
}
[Test]
public void TestDeserializeXmlCDataSection ()
{
CDataContainer c = (CDataContainer) Deserialize (typeof(CDataContainer), "<CDataContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><cdata><![CDATA[data section contents]]></cdata></CDataContainer>");
Assertion.AssertNotNull ("#1", c.cdata);
Assertion.AssertEquals ("#2", "data section contents", c.cdata.Value);
}
[Test]
public void TestDeserializeXmlNode ()
{
NodeContainer c = (NodeContainer) Deserialize (typeof(NodeContainer), "<NodeContainer xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><node>text</node></NodeContainer>");
Assertion.Assert ("#1", c.node is XmlText);
Assertion.AssertEquals ("#2", "text", c.node.Value);
}
[Test]
public void TestDeserializeChoices ()
{
Choices ch = (Choices) Deserialize (typeof(Choices), "<Choices><ChoiceZero>choice text</ChoiceZero></Choices>");
Assertion.AssertEquals ("#1", "choice text", ch.MyChoice);
Assertion.AssertEquals ("#2", ItemChoiceType.ChoiceZero, ch.ItemType);
ch = (Choices) Deserialize (typeof(Choices), "<Choices><ChoiceOne>choice text</ChoiceOne></Choices>");
Assertion.AssertEquals ("#1", "choice text", ch.MyChoice);
Assertion.AssertEquals ("#2", ItemChoiceType.StrangeOne, ch.ItemType);
ch = (Choices) Deserialize (typeof(Choices), "<Choices><ChoiceTwo>choice text</ChoiceTwo></Choices>");
Assertion.AssertEquals ("#1", "choice text", ch.MyChoice);
Assertion.AssertEquals ("#2", ItemChoiceType.ChoiceTwo, ch.ItemType);
}
[Test]
public void TestDeserializeNamesWithSpaces ()
{
TestSpace ts = (TestSpace) Deserialize (typeof(TestSpace), "<Type_x0020_with_x0020_space xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' Attribute_x0020_with_x0020_space='5'><Element_x0020_with_x0020_space>4</Element_x0020_with_x0020_space></Type_x0020_with_x0020_space>");
Assertion.AssertEquals ("#1", 4, ts.elem);
Assertion.AssertEquals ("#2", 5, ts.attr);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Diagnostics;
using System.Globalization;
using System.Security;
using System.Xml.Schema;
namespace System.Xml
{
// XmlReaderSettings class specifies basic features of an XmlReader.
public sealed class XmlReaderSettings
{
//
// Fields
//
private bool _useAsync;
// Nametable
private XmlNameTable _nameTable;
// XmlResolver
private XmlResolver _xmlResolver = null;
// Text settings
private int _lineNumberOffset;
private int _linePositionOffset;
// Conformance settings
private ConformanceLevel _conformanceLevel;
private bool _checkCharacters;
private long _maxCharactersInDocument;
private long _maxCharactersFromEntities;
// Filtering settings
private bool _ignoreWhitespace;
private bool _ignorePIs;
private bool _ignoreComments;
// security settings
private DtdProcessing _dtdProcessing;
//Validation settings
private ValidationType _validationType;
private XmlSchemaValidationFlags _validationFlags;
private XmlSchemaSet _schemas;
private ValidationEventHandler _valEventHandler;
// other settings
private bool _closeInput;
// read-only flag
private bool _isReadOnly;
// Creation of validating readers is hidden behind a delegate which is only initialized if the ValidationType
// property is set. This is for AOT builds where the tree shaker can reduce the validating readers away
// if nobody calls the ValidationType setter. Might also help with non-AOT build when ILLinker is used.
delegate XmlReader AddValidationFunc(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper);
private AddValidationFunc _addValidationFunc;
//
// Constructor
//
public XmlReaderSettings()
{
Initialize();
}
//
// Properties
//
public bool Async
{
get
{
return _useAsync;
}
set
{
CheckReadOnly("Async");
_useAsync = value;
}
}
// Nametable
public XmlNameTable NameTable
{
get
{
return _nameTable;
}
set
{
CheckReadOnly("NameTable");
_nameTable = value;
}
}
// XmlResolver
internal bool IsXmlResolverSet
{
get;
set; // keep set internal as we need to call it from the schema validation code
}
public XmlResolver XmlResolver
{
set
{
CheckReadOnly("XmlResolver");
_xmlResolver = value;
IsXmlResolverSet = true;
}
}
internal XmlResolver GetXmlResolver()
{
return _xmlResolver;
}
//This is used by get XmlResolver in Xsd.
//Check if the config set to prohibit default resovler
//notice we must keep GetXmlResolver() to avoid dead lock when init System.Config.ConfigurationManager
internal XmlResolver GetXmlResolver_CheckConfig()
{
if (!LocalAppContextSwitches.AllowDefaultResolver && !IsXmlResolverSet)
return null;
else
return _xmlResolver;
}
// Text settings
public int LineNumberOffset
{
get
{
return _lineNumberOffset;
}
set
{
CheckReadOnly("LineNumberOffset");
_lineNumberOffset = value;
}
}
public int LinePositionOffset
{
get
{
return _linePositionOffset;
}
set
{
CheckReadOnly("LinePositionOffset");
_linePositionOffset = value;
}
}
// Conformance settings
public ConformanceLevel ConformanceLevel
{
get
{
return _conformanceLevel;
}
set
{
CheckReadOnly("ConformanceLevel");
if ((uint)value > (uint)ConformanceLevel.Document)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_conformanceLevel = value;
}
}
public bool CheckCharacters
{
get
{
return _checkCharacters;
}
set
{
CheckReadOnly("CheckCharacters");
_checkCharacters = value;
}
}
public long MaxCharactersInDocument
{
get
{
return _maxCharactersInDocument;
}
set
{
CheckReadOnly("MaxCharactersInDocument");
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_maxCharactersInDocument = value;
}
}
public long MaxCharactersFromEntities
{
get
{
return _maxCharactersFromEntities;
}
set
{
CheckReadOnly("MaxCharactersFromEntities");
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_maxCharactersFromEntities = value;
}
}
// Filtering settings
public bool IgnoreWhitespace
{
get
{
return _ignoreWhitespace;
}
set
{
CheckReadOnly("IgnoreWhitespace");
_ignoreWhitespace = value;
}
}
public bool IgnoreProcessingInstructions
{
get
{
return _ignorePIs;
}
set
{
CheckReadOnly("IgnoreProcessingInstructions");
_ignorePIs = value;
}
}
public bool IgnoreComments
{
get
{
return _ignoreComments;
}
set
{
CheckReadOnly("IgnoreComments");
_ignoreComments = value;
}
}
[Obsolete("Use XmlReaderSettings.DtdProcessing property instead.")]
public bool ProhibitDtd
{
get
{
return _dtdProcessing == DtdProcessing.Prohibit;
}
set
{
CheckReadOnly("ProhibitDtd");
_dtdProcessing = value ? DtdProcessing.Prohibit : DtdProcessing.Parse;
}
}
public DtdProcessing DtdProcessing
{
get
{
return _dtdProcessing;
}
set
{
CheckReadOnly("DtdProcessing");
if ((uint)value > (uint)DtdProcessing.Parse)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dtdProcessing = value;
}
}
public bool CloseInput
{
get
{
return _closeInput;
}
set
{
CheckReadOnly("CloseInput");
_closeInput = value;
}
}
public ValidationType ValidationType
{
get
{
return _validationType;
}
set
{
CheckReadOnly("ValidationType");
// This introduces a dependency on the validation readers and along with that
// on XmlSchema and so on. For AOT builds this brings in a LOT of code
// which we would like to avoid unless it's needed. So the first approximation
// is to only reference this method when somebody explicitly sets the ValidationType.
_addValidationFunc = AddValidationInternal;
if ((uint)value > (uint)ValidationType.Schema)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_validationType = value;
}
}
public XmlSchemaValidationFlags ValidationFlags
{
get
{
return _validationFlags;
}
set
{
CheckReadOnly("ValidationFlags");
if ((uint)value > (uint)(XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.AllowXmlAttributes))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_validationFlags = value;
}
}
public XmlSchemaSet Schemas
{
get
{
if (_schemas == null)
{
_schemas = new XmlSchemaSet();
}
return _schemas;
}
set
{
CheckReadOnly("Schemas");
_schemas = value;
}
}
public event ValidationEventHandler ValidationEventHandler
{
add
{
CheckReadOnly("ValidationEventHandler");
_valEventHandler += value;
}
remove
{
CheckReadOnly("ValidationEventHandler");
_valEventHandler -= value;
}
}
//
// Public methods
//
public void Reset()
{
CheckReadOnly("Reset");
Initialize();
}
public XmlReaderSettings Clone()
{
XmlReaderSettings clonedSettings = this.MemberwiseClone() as XmlReaderSettings;
clonedSettings.ReadOnly = false;
return clonedSettings;
}
//
// Internal methods
//
internal ValidationEventHandler GetEventHandler()
{
return _valEventHandler;
}
internal XmlReader CreateReader(String inputUri, XmlParserContext inputContext)
{
if (inputUri == null)
{
throw new ArgumentNullException(nameof(inputUri));
}
if (inputUri.Length == 0)
{
throw new ArgumentException(SR.XmlConvert_BadUri, nameof(inputUri));
}
// resolve and open the url
XmlResolver tmpResolver = this.GetXmlResolver();
if (tmpResolver == null)
{
tmpResolver = CreateDefaultResolver();
}
// create text XML reader
XmlReader reader = new XmlTextReaderImpl(inputUri, this, inputContext, tmpResolver);
// wrap with validating reader
if (this.ValidationType != ValidationType.None)
{
reader = AddValidation(reader);
}
if (_useAsync)
{
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
internal XmlReader CreateReader(Stream input, Uri baseUri, string baseUriString, XmlParserContext inputContext)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (baseUriString == null)
{
if (baseUri == null)
{
baseUriString = string.Empty;
}
else
{
baseUriString = baseUri.ToString();
}
}
// create text XML reader
XmlReader reader = new XmlTextReaderImpl(input, null, 0, this, baseUri, baseUriString, inputContext, _closeInput);
// wrap with validating reader
if (this.ValidationType != ValidationType.None)
{
reader = AddValidation(reader);
}
if (_useAsync)
{
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
internal XmlReader CreateReader(TextReader input, string baseUriString, XmlParserContext inputContext)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (baseUriString == null)
{
baseUriString = string.Empty;
}
// create xml text reader
XmlReader reader = new XmlTextReaderImpl(input, this, baseUriString, inputContext);
// wrap with validating reader
if (this.ValidationType != ValidationType.None)
{
reader = AddValidation(reader);
}
if (_useAsync)
{
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
internal XmlReader CreateReader(XmlReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
return AddValidationAndConformanceWrapper(reader);
}
internal bool ReadOnly
{
get
{
return _isReadOnly;
}
set
{
_isReadOnly = value;
}
}
private void CheckReadOnly(string propertyName)
{
if (_isReadOnly)
{
throw new XmlException(SR.Xml_ReadOnlyProperty, this.GetType().Name + '.' + propertyName);
}
}
//
// Private methods
//
private void Initialize()
{
Initialize(null);
}
private void Initialize(XmlResolver resolver)
{
_nameTable = null;
_xmlResolver = resolver;
// limit the entity resolving to 10 million character. the caller can still
// override it to any other value or set it to zero for unlimiting it
_maxCharactersFromEntities = (long)1e7;
_lineNumberOffset = 0;
_linePositionOffset = 0;
_checkCharacters = true;
_conformanceLevel = ConformanceLevel.Document;
_ignoreWhitespace = false;
_ignorePIs = false;
_ignoreComments = false;
_dtdProcessing = DtdProcessing.Prohibit;
_closeInput = false;
_maxCharactersInDocument = 0;
_schemas = null;
_validationType = ValidationType.None;
_validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints;
_validationFlags |= XmlSchemaValidationFlags.AllowXmlAttributes;
_useAsync = false;
_isReadOnly = false;
IsXmlResolverSet = false;
}
private static XmlResolver CreateDefaultResolver()
{
return new XmlUrlResolver();
}
internal XmlReader AddValidation(XmlReader reader)
{
XmlResolver resolver = null;
if (_validationType == ValidationType.Schema)
{
resolver = GetXmlResolver_CheckConfig();
if (resolver == null &&
!this.IsXmlResolverSet)
{
resolver = new XmlUrlResolver();
}
}
return AddValidationAndConformanceInternal(reader, resolver, addConformanceWrapper: false);
}
private XmlReader AddValidationAndConformanceWrapper(XmlReader reader)
{
XmlResolver resolver = null;
if (_validationType == ValidationType.Schema)
{
resolver = GetXmlResolver_CheckConfig();
}
return AddValidationAndConformanceInternal(reader, resolver, addConformanceWrapper: true);
}
private XmlReader AddValidationAndConformanceInternal(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper)
{
// We have to avoid calling the _addValidationFunc delegate if there's no validation to setup
// since it would not be initialized (to allow AOT compilers to reduce it away).
// So if that's the case and we still need conformance wrapper add it here directly.
// This is a slight code duplication, but it's necessary due to ordering constrains
// of the reader wrapping as described in AddValidationInternal.
if (_validationType == ValidationType.None)
{
if (addConformanceWrapper)
{
reader = AddConformanceWrapper(reader);
}
}
else
{
reader = _addValidationFunc(reader, resolver, addConformanceWrapper);
}
return reader;
}
private XmlReader AddValidationInternal(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper)
{
// wrap with DTD validating reader
if (_validationType == ValidationType.DTD)
{
reader = CreateDtdValidatingReader(reader);
}
if (addConformanceWrapper)
{
// add conformance checking (must go after DTD validation because XmlValidatingReader works only on XmlTextReader),
// but before XSD validation because of typed value access
reader = AddConformanceWrapper(reader);
}
if (_validationType == ValidationType.Schema)
{
reader = new XsdValidatingReader(reader, GetXmlResolver_CheckConfig(), this);
}
return reader;
}
private XmlValidatingReaderImpl CreateDtdValidatingReader(XmlReader baseReader)
{
return new XmlValidatingReaderImpl(baseReader, this.GetEventHandler(), (this.ValidationFlags & XmlSchemaValidationFlags.ProcessIdentityConstraints) != 0);
}
internal XmlReader AddConformanceWrapper(XmlReader baseReader)
{
XmlReaderSettings baseReaderSettings = baseReader.Settings;
bool checkChars = false;
bool noWhitespace = false;
bool noComments = false;
bool noPIs = false;
DtdProcessing dtdProc = (DtdProcessing)(-1);
bool needWrap = false;
if (baseReaderSettings == null)
{
#pragma warning disable 618
if (_conformanceLevel != ConformanceLevel.Auto && _conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader))
{
throw new InvalidOperationException(SR.Format(SR.Xml_IncompatibleConformanceLevel, _conformanceLevel.ToString()));
}
// get the V1 XmlTextReader ref
XmlTextReader v1XmlTextReader = baseReader as XmlTextReader;
if (v1XmlTextReader == null)
{
XmlValidatingReader vr = baseReader as XmlValidatingReader;
if (vr != null)
{
v1XmlTextReader = (XmlTextReader)vr.Reader;
}
}
// assume the V1 readers already do all conformance checking;
// wrap only if IgnoreWhitespace, IgnoreComments, IgnoreProcessingInstructions or ProhibitDtd is true;
if (_ignoreWhitespace)
{
WhitespaceHandling wh = WhitespaceHandling.All;
// special-case our V1 readers to see if whey already filter whitespace
if (v1XmlTextReader != null)
{
wh = v1XmlTextReader.WhitespaceHandling;
}
if (wh == WhitespaceHandling.All)
{
noWhitespace = true;
needWrap = true;
}
}
if (_ignoreComments)
{
noComments = true;
needWrap = true;
}
if (_ignorePIs)
{
noPIs = true;
needWrap = true;
}
// DTD processing
DtdProcessing baseDtdProcessing = DtdProcessing.Parse;
if (v1XmlTextReader != null)
{
baseDtdProcessing = v1XmlTextReader.DtdProcessing;
}
if ((_dtdProcessing == DtdProcessing.Prohibit && baseDtdProcessing != DtdProcessing.Prohibit) ||
(_dtdProcessing == DtdProcessing.Ignore && baseDtdProcessing == DtdProcessing.Parse))
{
dtdProc = _dtdProcessing;
needWrap = true;
}
#pragma warning restore 618
}
else
{
if (_conformanceLevel != baseReaderSettings.ConformanceLevel && _conformanceLevel != ConformanceLevel.Auto)
{
throw new InvalidOperationException(SR.Format(SR.Xml_IncompatibleConformanceLevel, _conformanceLevel.ToString()));
}
if (_checkCharacters && !baseReaderSettings.CheckCharacters)
{
checkChars = true;
needWrap = true;
}
if (_ignoreWhitespace && !baseReaderSettings.IgnoreWhitespace)
{
noWhitespace = true;
needWrap = true;
}
if (_ignoreComments && !baseReaderSettings.IgnoreComments)
{
noComments = true;
needWrap = true;
}
if (_ignorePIs && !baseReaderSettings.IgnoreProcessingInstructions)
{
noPIs = true;
needWrap = true;
}
if ((_dtdProcessing == DtdProcessing.Prohibit && baseReaderSettings.DtdProcessing != DtdProcessing.Prohibit) ||
(_dtdProcessing == DtdProcessing.Ignore && baseReaderSettings.DtdProcessing == DtdProcessing.Parse))
{
dtdProc = _dtdProcessing;
needWrap = true;
}
}
if (needWrap)
{
IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver;
if (readerAsNSResolver != null)
{
return new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc);
}
else
{
return new XmlCharCheckingReader(baseReader, checkChars, noWhitespace, noComments, noPIs, dtdProc);
}
}
else
{
return baseReader;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Xml.Linq;
using NuGet;
using Orchard.Environment;
using Orchard.Environment.Configuration;
using Orchard.Environment.Extensions.Models;
using Orchard.FileSystems.AppData;
using Orchard.Localization;
using Orchard.Modules.Services;
using Orchard.Mvc.Extensions;
using Orchard.Packaging.Extensions;
using Orchard.Packaging.Services;
using Orchard.Packaging.ViewModels;
using Orchard.Recipes.Models;
using Orchard.Recipes.Services;
using Orchard.Security;
using Orchard.Themes;
using Orchard.UI.Admin;
using Orchard.UI.Notify;
using IPackageManager = Orchard.Packaging.Services.IPackageManager;
using PackageBuilder = Orchard.Packaging.Services.PackageBuilder;
namespace Orchard.Packaging.Controllers {
[Themed, Admin]
public class PackagingServicesController : Controller {
private readonly ShellSettings _shellSettings;
private readonly IPackageManager _packageManager;
private readonly IPackagingSourceManager _packagingSourceManager;
private readonly IAppDataFolderRoot _appDataFolderRoot;
private readonly IModuleService _moduleService;
private readonly IHostEnvironment _hostEnvironment;
private readonly IRecipeHarvester _recipeHarvester;
private readonly IRecipeManager _recipeManager;
public PackagingServicesController(
ShellSettings shellSettings,
IPackageManager packageManager,
IPackagingSourceManager packagingSourceManager,
IAppDataFolderRoot appDataFolderRoot,
IOrchardServices services,
IModuleService moduleService,
IHostEnvironment hostEnvironment)
: this(shellSettings, packageManager, packagingSourceManager, appDataFolderRoot, services, moduleService, hostEnvironment, null, null) {
}
public PackagingServicesController(
ShellSettings shellSettings,
IPackageManager packageManager,
IPackagingSourceManager packagingSourceManager,
IAppDataFolderRoot appDataFolderRoot,
IOrchardServices services,
IModuleService moduleService,
IHostEnvironment hostEnvironment,
IRecipeHarvester recipeHarvester,
IRecipeManager recipeManager) {
_shellSettings = shellSettings;
_packageManager = packageManager;
_appDataFolderRoot = appDataFolderRoot;
_moduleService = moduleService;
_hostEnvironment = hostEnvironment;
_recipeHarvester = recipeHarvester;
_recipeManager = recipeManager;
_packagingSourceManager = packagingSourceManager;
Services = services;
T = NullLocalizer.Instance;
Logger = Logging.NullLogger.Instance;
}
public Localizer T { get; set; }
public IOrchardServices Services { get; set; }
public Logging.ILogger Logger { get; set; }
public ActionResult AddTheme(string returnUrl) {
if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to add themes")))
return new HttpUnauthorizedResult();
return View();
}
[HttpPost, ActionName("UninstallTheme")]
public ActionResult UninstallThemePost(string themeId, string returnUrl, string retryUrl) {
if (String.IsNullOrEmpty(themeId)) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to remove themes")))
return new HttpUnauthorizedResult();
return UninstallPackage(PackageBuilder.BuildPackageId(themeId, DefaultExtensionTypes.Theme), returnUrl, retryUrl);
}
[HttpPost, ActionName("UninstallModule")]
public ActionResult UninstallModulePost(string moduleId, string returnUrl, string retryUrl) {
if (String.IsNullOrEmpty(moduleId)) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to remove modules")))
return new HttpUnauthorizedResult();
return UninstallPackage(PackageBuilder.BuildPackageId(moduleId, DefaultExtensionTypes.Module), returnUrl, retryUrl);
}
public ActionResult AddModule(string returnUrl) {
if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to add modules")))
return new HttpUnauthorizedResult();
return View();
}
public ActionResult InstallGallery(string packageId, string version, int sourceId, string redirectUrl) {
if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to add sources")))
return new HttpUnauthorizedResult();
var source = _packagingSourceManager.GetSources().FirstOrDefault(s => s.Id == sourceId);
if (source == null) {
return HttpNotFound();
}
try {
PackageInfo packageInfo = _packageManager.Install(packageId, version, source.FeedUrl, MapAppRoot());
if (DefaultExtensionTypes.IsTheme(packageInfo.ExtensionType)) {
Services.Notifier.Information(T("The theme has been successfully installed. It can be enabled in the \"Themes\" page accessible from the menu."));
}
else if (DefaultExtensionTypes.IsModule(packageInfo.ExtensionType)) {
Services.Notifier.Information(T("The module has been successfully installed."));
IPackageRepository packageRepository = PackageRepositoryFactory.Default.CreateRepository(new PackageSource(source.FeedUrl, "Default"));
IPackage package = packageRepository.FindPackage(packageId);
ExtensionDescriptor extensionDescriptor = package.GetExtensionDescriptor(packageInfo.ExtensionType);
return InstallPackageDetails(extensionDescriptor, redirectUrl);
}
}
catch (OrchardException e) {
Services.Notifier.Error(T("Package installation failed: {0}", e.Message));
return View("InstallPackageFailed");
}
catch (Exception) {
Services.Notifier.Error(T("Package installation failed."));
return View("InstallPackageFailed");
}
return Redirect(redirectUrl);
}
public ActionResult InstallLocally(string redirectUrl) {
if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to install packages")))
return new HttpUnauthorizedResult();
var httpPostedFileBase = Request.Files.Get(0);
if (httpPostedFileBase == null
|| Request.Files.Count == 0
|| string.IsNullOrWhiteSpace(httpPostedFileBase.FileName)) {
throw new OrchardException(T("Select a file to upload."));
}
try {
string fullFileName = Path.Combine(_appDataFolderRoot.RootFolder, Path.GetFileName(httpPostedFileBase.FileName)).Replace(Path.DirectorySeparatorChar, '/');
httpPostedFileBase.SaveAs(fullFileName);
var package = new ZipPackage(fullFileName);
PackageInfo packageInfo = _packageManager.Install(package, _appDataFolderRoot.RootFolder, MapAppRoot());
ExtensionDescriptor extensionDescriptor = package.GetExtensionDescriptor(packageInfo.ExtensionType);
System.IO.File.Delete(fullFileName);
if (DefaultExtensionTypes.IsTheme(extensionDescriptor.ExtensionType)) {
Services.Notifier.Information(T("The theme has been successfully installed. It can be enabled in the \"Themes\" page accessible from the menu."));
}
else if (DefaultExtensionTypes.IsModule(extensionDescriptor.ExtensionType)) {
Services.Notifier.Information(T("The module has been successfully installed."));
return InstallPackageDetails(extensionDescriptor, redirectUrl);
}
}
catch (OrchardException e) {
Services.Notifier.Error(T("Package uploading and installation failed: {0}", e.Message));
return View("InstallPackageFailed");
}
catch (Exception) {
Services.Notifier.Error(T("Package uploading and installation failed."));
return View("InstallPackageFailed");
}
return Redirect(redirectUrl);
}
private ActionResult InstallPackageDetails(ExtensionDescriptor extensionDescriptor, string redirectUrl) {
if (DefaultExtensionTypes.IsModule(extensionDescriptor.ExtensionType)) {
List<PackagingInstallFeatureViewModel> features = extensionDescriptor.Features
.Where(featureDescriptor => !DefaultExtensionTypes.IsTheme(featureDescriptor.Extension.ExtensionType))
.Select(featureDescriptor => new PackagingInstallFeatureViewModel {
Enable = true, // by default all features are enabled
FeatureDescriptor = featureDescriptor
}).ToList();
List<PackagingInstallRecipeViewModel> recipes = null;
if (_recipeHarvester != null) {
recipes = _recipeHarvester.HarvestRecipes(extensionDescriptor.Id)
.Select(recipe => new PackagingInstallRecipeViewModel {
Execute = false, // by default no recipes are executed
Recipe = recipe
}).ToList();
}
if (features.Count > 0) {
return View("InstallModuleDetails", new PackagingInstallViewModel {
Features = features,
Recipes = recipes,
ExtensionDescriptor = extensionDescriptor
});
}
}
return Redirect(redirectUrl);
}
[HttpPost, ActionName("InstallPackageDetails")]
public ActionResult InstallPackageDetailsPOST(PackagingInstallViewModel packagingInstallViewModel, string redirectUrl) {
if (_shellSettings.Name != ShellSettings.DefaultName || !Services.Authorizer.Authorize(StandardPermissions.SiteOwner, T("Not authorized to add sources")))
return new HttpUnauthorizedResult();
try {
if (_recipeHarvester != null && _recipeManager != null) {
IEnumerable<Recipe> recipes = _recipeHarvester.HarvestRecipes(packagingInstallViewModel.ExtensionDescriptor.Id)
.Where(loadedRecipe => packagingInstallViewModel.Recipes.FirstOrDefault(recipeViewModel => recipeViewModel.Execute && recipeViewModel.Recipe.Name.Equals(loadedRecipe.Name)) != null);
foreach (Recipe recipe in recipes) {
try {
_recipeManager.Execute(recipe);
}
catch {
Services.Notifier.Error(T("Recipes contains {0} unsupported module installation steps.", recipe.Name));
}
}
}
// Enable selected features
if (packagingInstallViewModel.Features.Count > 0) {
IEnumerable<string> featureIds = packagingInstallViewModel.Features
.Where(feature => feature.Enable)
.Select(feature => feature.FeatureDescriptor.Id);
// Enable the features and its dependencies using recipes, so that they are run after the module's recipes
var recipe = new Recipe {
RecipeSteps = featureIds.Select(
x => new RecipeStep {
Name = "Feature",
Step = new XElement("Feature", new XAttribute("enable", x))
})
};
_recipeManager.Execute(recipe);
}
} catch (Exception exception) {
Services.Notifier.Error(T("Post installation steps failed with error: {0}", exception.Message));
}
return Redirect(redirectUrl);
}
private ActionResult UninstallPackage(string id, string returnUrl, string retryUrl) {
try {
_packageManager.Uninstall(id, MapAppRoot());
}
catch (Exception exception) {
Services.Notifier.Error(T("Uninstall failed: {0}", exception.Message));
return Redirect(!String.IsNullOrEmpty(retryUrl) ? retryUrl : returnUrl);
}
Services.Notifier.Information(T("Uninstalled package \"{0}\"", id));
return this.RedirectLocal(returnUrl, "~/");
}
private string MapAppRoot() {
return _hostEnvironment.MapPath("~/");
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System;
using System.Collections.Generic;
using System.Threading;
namespace NUnit.Framework.Internal.Execution
{
/// <summary>
/// ParallelWorkItemDispatcher handles execution of work items by
/// queuing them for worker threads to process.
/// </summary>
public class ParallelWorkItemDispatcher : IWorkItemDispatcher
{
private static readonly Logger log = InternalTrace.GetLogger("Dispatcher");
private const int WAIT_FOR_FORCED_TERMINATION = 5000;
private WorkItem _topLevelWorkItem;
private readonly Stack<WorkItem> _savedWorkItems = new Stack<WorkItem>();
private readonly List<CompositeWorkItem> _activeWorkItems = new List<CompositeWorkItem>();
#region Events
/// <summary>
/// Event raised whenever a shift is starting.
/// </summary>
public event ShiftChangeEventHandler ShiftStarting;
/// <summary>
/// Event raised whenever a shift has ended.
/// </summary>
public event ShiftChangeEventHandler ShiftFinished;
#endregion
#region Constructor
/// <summary>
/// Construct a ParallelWorkItemDispatcher
/// </summary>
/// <param name="levelOfParallelism">Number of workers to use</param>
public ParallelWorkItemDispatcher(int levelOfParallelism)
{
log.Info("Initializing with {0} workers", levelOfParallelism);
LevelOfParallelism = levelOfParallelism;
InitializeShifts();
}
private void InitializeShifts()
{
foreach (var shift in Shifts)
shift.EndOfShift += OnEndOfShift;
// Assign queues to shifts
ParallelShift.AddQueue(ParallelQueue);
ParallelShift.AddQueue(ParallelSTAQueue);
NonParallelShift.AddQueue(NonParallelQueue);
NonParallelSTAShift.AddQueue(NonParallelSTAQueue);
// Create workers and assign to shifts and queues
// TODO: Avoid creating all the workers till needed
for (int i = 1; i <= LevelOfParallelism; i++)
{
string name = string.Format("ParallelWorker#" + i.ToString());
ParallelShift.Assign(new TestWorker(ParallelQueue, name));
}
ParallelShift.Assign(new TestWorker(ParallelSTAQueue, "ParallelSTAWorker"));
var worker = new TestWorker(NonParallelQueue, "NonParallelWorker");
worker.Busy += OnStartNonParallelWorkItem;
NonParallelShift.Assign(worker);
worker = new TestWorker(NonParallelSTAQueue, "NonParallelSTAWorker");
worker.Busy += OnStartNonParallelWorkItem;
NonParallelSTAShift.Assign(worker);
}
private void OnStartNonParallelWorkItem(TestWorker worker, WorkItem work)
{
// This captures the startup of TestFixtures and SetUpFixtures,
// but not their teardown items, which are not composite items
if (work.IsolateChildTests)
IsolateQueues(work);
}
#endregion
#region Properties
/// <summary>
/// Number of parallel worker threads
/// </summary>
public int LevelOfParallelism { get; }
/// <summary>
/// Enumerates all the shifts supported by the dispatcher
/// </summary>
public IEnumerable<WorkShift> Shifts
{
get
{
yield return ParallelShift;
yield return NonParallelShift;
yield return NonParallelSTAShift;
}
}
/// <summary>
/// Enumerates all the Queues supported by the dispatcher
/// </summary>
public IEnumerable<WorkItemQueue> Queues
{
get
{
yield return ParallelQueue;
yield return ParallelSTAQueue;
yield return NonParallelQueue;
yield return NonParallelSTAQueue;
}
}
// WorkShifts - Dispatcher processes tests in three non-overlapping shifts.
// See comment in Workshift.cs for a more detailed explanation.
private WorkShift ParallelShift { get; } = new WorkShift("Parallel");
private WorkShift NonParallelShift { get; } = new WorkShift("NonParallel");
private WorkShift NonParallelSTAShift { get; } = new WorkShift("NonParallelSTA");
// WorkItemQueues
private WorkItemQueue ParallelQueue { get; } = new WorkItemQueue("ParallelQueue", true, ApartmentState.MTA);
private WorkItemQueue ParallelSTAQueue { get; } = new WorkItemQueue("ParallelSTAQueue", true, ApartmentState.STA);
private WorkItemQueue NonParallelQueue { get; } = new WorkItemQueue("NonParallelQueue", false, ApartmentState.MTA);
private WorkItemQueue NonParallelSTAQueue { get; } = new WorkItemQueue("NonParallelSTAQueue", false, ApartmentState.STA);
#endregion
#region IWorkItemDispatcher Members
/// <summary>
/// Start execution, setting the top level work,
/// enqueuing it and starting a shift to execute it.
/// </summary>
public void Start(WorkItem topLevelWorkItem)
{
_topLevelWorkItem = topLevelWorkItem;
Dispatch(topLevelWorkItem, InitialExecutionStrategy(topLevelWorkItem));
var shift = SelectNextShift();
ShiftStarting?.Invoke(shift);
shift.Start();
}
// Initial strategy for the top level item is solely determined
// by the ParallelScope of that item. While other approaches are
// possible, this one gives the user a predictable result.
private static ParallelExecutionStrategy InitialExecutionStrategy(WorkItem workItem)
{
return workItem.ParallelScope == ParallelScope.Default || workItem.ParallelScope == ParallelScope.None
? ParallelExecutionStrategy.NonParallel
: ParallelExecutionStrategy.Parallel;
}
/// <summary>
/// Dispatch a single work item for execution. The first
/// work item dispatched is saved as the top-level
/// work item and used when stopping the run.
/// </summary>
/// <param name="work">The item to dispatch</param>
public void Dispatch(WorkItem work)
{
Dispatch(work, work.ExecutionStrategy);
}
// Separate method so it can be used by Start
private void Dispatch(WorkItem work, ParallelExecutionStrategy strategy)
{
log.Debug("Using {0} strategy for {1}", strategy, work.Name);
// Currently, we only track CompositeWorkItems - this could be expanded
var composite = work as CompositeWorkItem;
if (composite != null)
lock (_activeWorkItems)
{
_activeWorkItems.Add(composite);
composite.Completed += OnWorkItemCompletion;
}
switch (strategy)
{
default:
case ParallelExecutionStrategy.Direct:
work.Execute();
break;
case ParallelExecutionStrategy.Parallel:
if (work.TargetApartment == ApartmentState.STA)
ParallelSTAQueue.Enqueue(work);
else
ParallelQueue.Enqueue(work);
break;
case ParallelExecutionStrategy.NonParallel:
if (work.TargetApartment == ApartmentState.STA)
NonParallelSTAQueue.Enqueue(work);
else
NonParallelQueue.Enqueue(work);
break;
}
}
/// <summary>
/// Cancel the ongoing run completely.
/// If no run is in process, the call has no effect.
/// </summary>
public void CancelRun(bool force)
{
foreach (var shift in Shifts)
shift.Cancel(force);
if (force)
{
SpinWait.SpinUntil(() => _topLevelWorkItem.State == WorkItemState.Complete, WAIT_FOR_FORCED_TERMINATION);
// Notify termination of any remaining in-process suites
lock (_activeWorkItems)
{
int index = _activeWorkItems.Count;
while (index > 0)
{
var work = _activeWorkItems[--index];
if (work.State == WorkItemState.Running)
new CompositeWorkItem.OneTimeTearDownWorkItem(work).WorkItemCancelled();
}
}
}
}
private readonly object _queueLock = new object();
private int _isolationLevel = 0;
/// <summary>
/// Save the state of the queues and create a new isolated set
/// </summary>
internal void IsolateQueues(WorkItem work)
{
log.Info("Saving Queue State for {0}", work.Name);
lock (_queueLock)
{
foreach (WorkItemQueue queue in Queues)
queue.Save();
_savedWorkItems.Push(_topLevelWorkItem);
_topLevelWorkItem = work;
_isolationLevel++;
}
}
/// <summary>
/// Try to remove isolated queues and restore old ones
/// </summary>
private void TryRestoreQueues()
{
// Keep lock until we can remove for both methods
lock (_queueLock)
{
if (_isolationLevel <= 0)
{
log.Debug("Ignoring call to restore Queue State");
return;
}
log.Info("Restoring Queue State");
foreach (WorkItemQueue queue in Queues)
queue.Restore();
_topLevelWorkItem = _savedWorkItems.Pop();
_isolationLevel--;
}
}
#endregion
#region Helper Methods
private void OnWorkItemCompletion(object sender, EventArgs args)
{
var work = (CompositeWorkItem)sender;
lock (_activeWorkItems)
{
_activeWorkItems.Remove(work);
work.Completed -= OnWorkItemCompletion;
}
}
private void OnEndOfShift(WorkShift endingShift)
{
ShiftFinished?.Invoke(endingShift);
WorkShift nextShift = null;
while (true)
{
// Shift has ended but all work may not yet be done
while (_topLevelWorkItem.State != WorkItemState.Complete)
{
// This will return null if all queues are empty.
nextShift = SelectNextShift();
if (nextShift != null)
{
ShiftStarting?.Invoke(nextShift);
nextShift.Start();
return;
}
}
// If the shift has ended for an isolated queue, restore
// the queues and keep trying. Otherwise, we are done.
if (_isolationLevel > 0)
TryRestoreQueues();
else
break;
}
// All done - shutdown all shifts
foreach (var shift in Shifts)
shift.ShutDown();
}
private WorkShift SelectNextShift()
{
foreach (var shift in Shifts)
if (shift.HasWork)
return shift;
return null;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using ServiceStack.Common.Utils;
using ServiceStack.Common.Web;
using ServiceStack.Logging;
using ServiceStack.ServiceHost;
using ServiceStack.Text;
namespace ServiceStack.WebHost.Endpoints.Extensions
{
/**
*
Input: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?q=item#fragment
Some HttpRequest path and URL properties:
Request.ApplicationPath: /Cambia3
Request.CurrentExecutionFilePath: /Cambia3/Temp/Test.aspx
Request.FilePath: /Cambia3/Temp/Test.aspx
Request.Path: /Cambia3/Temp/Test.aspx/path/info
Request.PathInfo: /path/info
Request.PhysicalApplicationPath: D:\Inetpub\wwwroot\CambiaWeb\Cambia3\
Request.QueryString: /Cambia3/Temp/Test.aspx/path/info?query=arg
Request.Url.AbsolutePath: /Cambia3/Temp/Test.aspx/path/info
Request.Url.AbsoluteUri: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?query=arg
Request.Url.Fragment:
Request.Url.Host: localhost
Request.Url.LocalPath: /Cambia3/Temp/Test.aspx/path/info
Request.Url.PathAndQuery: /Cambia3/Temp/Test.aspx/path/info?query=arg
Request.Url.Port: 96
Request.Url.Query: ?query=arg
Request.Url.Scheme: http
Request.Url.Segments: /
Cambia3/
Temp/
Test.aspx/
path/
info
* */
public static class HttpRequestExtensions
{
private static readonly ILog Log = LogManager.GetLogger(typeof(HttpRequestExtensions));
private static string WebHostDirectoryName = "";
static HttpRequestExtensions()
{
WebHostDirectoryName = Path.GetFileName("~".MapHostAbsolutePath());
}
public static string GetOperationName(this HttpRequest request)
{
var pathInfo = request.GetLastPathInfo();
return GetOperationNameFromLastPathInfo(pathInfo);
}
public static string GetOperationNameFromLastPathInfo(string lastPathInfo)
{
if (string.IsNullOrEmpty(lastPathInfo)) return null;
var operationName = lastPathInfo.Substring("/".Length);
return operationName;
}
private static string GetLastPathInfoFromRawUrl(string rawUrl)
{
var pathInfo = rawUrl.IndexOf("?") != -1
? rawUrl.Substring(0, rawUrl.IndexOf("?"))
: rawUrl;
pathInfo = pathInfo.Substring(pathInfo.LastIndexOf("/"));
return pathInfo;
}
public static string GetLastPathInfo(this HttpRequest request)
{
var pathInfo = request.PathInfo;
if (string.IsNullOrEmpty(pathInfo))
{
pathInfo = GetLastPathInfoFromRawUrl(request.RawUrl);
}
//Log.DebugFormat("Request.PathInfo: {0}, Request.RawUrl: {1}, pathInfo:{2}",
// request.PathInfo, request.RawUrl, pathInfo);
return pathInfo;
}
public static string GetUrlHostName(this HttpRequest request)
{
//TODO: Fix bug in mono fastcgi, when trying to get 'Request.Url.Host'
try
{
return request.Url.Host;
}
catch (Exception ex)
{
Log.ErrorFormat("Error trying to get 'Request.Url.Host'", ex);
return request.UserHostName;
}
}
// http://localhost/ServiceStack.Examples.Host.Web/Public/Public/Soap12/Wsdl =>
// http://localhost/ServiceStack.Examples.Host.Web/Public/Soap12/
public static string GetParentBaseUrl(this HttpRequest request)
{
var rawUrl = request.RawUrl; // /Cambia3/Temp/Test.aspx/path/info
var endpointsPath = rawUrl.Substring(0, rawUrl.LastIndexOf('/') + 1); // /Cambia3/Temp/Test.aspx/path
return GetAuthority(request) + endpointsPath;
}
public static string GetBaseUrl(this HttpRequest request)
{
return GetAuthority(request) + request.RawUrl;
}
//=> http://localhost:96 ?? ex=> http://localhost
private static string GetAuthority(HttpRequest request)
{
try
{
return request.Url.GetLeftPart(UriPartial.Authority);
}
catch (Exception ex)
{
Log.Error("Error trying to get: request.Url.GetLeftPart(UriPartial.Authority): " + ex.Message, ex);
return "http://" + request.UserHostName;
}
}
public static string GetOperationName(this HttpListenerRequest request)
{
return request.Url.Segments[request.Url.Segments.Length - 1];
}
public static string GetLastPathInfo(this HttpListenerRequest request)
{
return GetLastPathInfoFromRawUrl(request.RawUrl);
}
public static string GetPathInfo(this HttpRequest request)
{
if (!string.IsNullOrEmpty(request.PathInfo)) return request.PathInfo.TrimEnd('/');
var mode = EndpointHost.Config.ServiceStackHandlerFactoryPath;
var appPath = string.IsNullOrEmpty(request.ApplicationPath)
? WebHostDirectoryName
: request.ApplicationPath.TrimStart('/');
//mod_mono: /CustomPath35/api//default.htm
var path = Env.IsMono ? request.Path.Replace("//", "/") : request.Path;
return GetPathInfo(path, mode, appPath);
}
public static string GetPathInfo(string fullPath, string mode, string appPath)
{
var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
if (!string.IsNullOrEmpty(pathInfo)) return pathInfo;
//Wildcard mode relies on this to find work out the handlerPath
pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
if (!string.IsNullOrEmpty(pathInfo)) return pathInfo;
return fullPath;
}
public static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
{
var sbPathInfo = new StringBuilder();
var fullPathParts = fullPath.Split('/');
var pathRootFound = false;
foreach (var fullPathPart in fullPathParts)
{
if (pathRootFound)
{
sbPathInfo.Append("/" + fullPathPart);
}
else
{
pathRootFound = string.Equals(fullPathPart, mappedPathRoot, StringComparison.InvariantCultureIgnoreCase);
}
}
if (!pathRootFound) return null;
var path = sbPathInfo.ToString();
return path.Length > 1 ? path.TrimEnd('/') : "/";
}
public static bool IsContentType(this IHttpRequest request, string contentType)
{
return request.ContentType.StartsWith(contentType, StringComparison.InvariantCultureIgnoreCase);
}
public static bool HasAnyOfContentTypes(this IHttpRequest request, params string[] contentTypes)
{
if (contentTypes == null || request.ContentType == null) return false;
foreach (var contentType in contentTypes)
{
if (IsContentType(request, contentType)) return true;
}
return false;
}
public static IHttpRequest GetHttpRequest(this HttpRequest request)
{
return new HttpRequestWrapper(null, request);
}
public static IHttpRequest GetHttpRequest(this HttpListenerRequest request)
{
return new HttpListenerRequestWrapper(null, request);
}
public static Dictionary<string, string> GetRequestParams(this IHttpRequest request)
{
var map = new Dictionary<string, string>();
foreach (var name in request.QueryString.AllKeys)
{
map[name] = request.QueryString[name];
}
if ((request.HttpMethod == HttpMethods.Post || request.HttpMethod == HttpMethods.Put)
&& request.FormData != null)
{
foreach (var name in request.FormData.AllKeys)
{
if (name == null) continue; //thank you ASP.NET
map[name] = request.FormData[name];
}
}
return map;
}
public static string GetQueryStringContentType(this IHttpRequest httpReq)
{
var callback = httpReq.QueryString["callback"];
if (!string.IsNullOrEmpty(callback)) return ContentType.Json;
var format = httpReq.QueryString["format"];
if (format == null)
{
const int formatMaxLength = 4;
var pi = httpReq.PathInfo;
if (pi == null || pi.Length <= formatMaxLength) return null;
if (pi[0] == '/') pi = pi.Substring(1);
format = pi.SplitOnFirst('/')[0];
if (format.Length > formatMaxLength) return null;
}
format = format.SplitOnFirst('.')[0].ToLower();
if (format.Contains("json")) return ContentType.Json;
if (format.Contains("xml")) return ContentType.Xml;
if (format.Contains("jsv")) return ContentType.Jsv;
string contentType;
EndpointHost.ContentTypeFilter.ContentTypeFormats.TryGetValue(format, out contentType);
return contentType;
}
public static string[] PreferredContentTypes = new[] {
ContentType.Html, ContentType.Json, ContentType.Xml, ContentType.Jsv
};
/// <summary>
/// Use this to treat Request.Items[] as a cache by returning pre-computed items to save
/// calculating them multiple times.
/// </summary>
public static object ResolveItem(this IHttpRequest httpReq,
string itemKey, Func<IHttpRequest, object> resolveFn)
{
object cachedItem;
if (httpReq.Items.TryGetValue(itemKey, out cachedItem))
return cachedItem;
var item = resolveFn(httpReq);
httpReq.Items[itemKey] = item;
return item;
}
public static string GetResponseContentType(this IHttpRequest httpReq)
{
var specifiedContentType = GetQueryStringContentType(httpReq);
if (!string.IsNullOrEmpty(specifiedContentType)) return specifiedContentType;
var acceptContentTypes = httpReq.AcceptTypes;
var defaultContentType = httpReq.ContentType;
if (httpReq.HasAnyOfContentTypes(ContentType.FormUrlEncoded, ContentType.MultiPartFormData))
{
defaultContentType = EndpointHost.Config.DefaultContentType;
}
var customContentTypes = EndpointHost.ContentTypeFilter.ContentTypeFormats.Values;
var acceptsAnything = false;
var hasDefaultContentType = !string.IsNullOrEmpty(defaultContentType);
if (acceptContentTypes != null)
{
var hasPreferredContentTypes = new bool[PreferredContentTypes.Length];
foreach (var contentType in acceptContentTypes)
{
acceptsAnything = acceptsAnything || contentType == "*/*";
for (var i = 0; i < PreferredContentTypes.Length; i++)
{
if (hasPreferredContentTypes[i]) continue;
var preferredContentType = PreferredContentTypes[i];
hasPreferredContentTypes[i] = contentType.StartsWith(preferredContentType);
//Prefer Request.ContentType if it is also a preferredContentType
if (hasPreferredContentTypes[i] && preferredContentType == defaultContentType)
return preferredContentType;
}
}
for (var i = 0; i < PreferredContentTypes.Length; i++)
{
if (hasPreferredContentTypes[i]) return PreferredContentTypes[i];
}
if (acceptsAnything && hasDefaultContentType) return defaultContentType;
foreach (var contentType in acceptContentTypes)
{
foreach (var customContentType in customContentTypes)
{
if (contentType.StartsWith(customContentType)) return customContentType;
}
}
}
//We could also send a '406 Not Acceptable', but this is allowed also
return EndpointHost.Config.DefaultContentType;
}
}
}
| |
using EnvDTE;
using Microsoft.Build.Evaluation;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Project;
using Microsoft.VisualStudio.Project.Designers;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using VSLangProj;
using VsWebSite;
using MsBuildProject = Microsoft.Build.Evaluation.Project;
using Project = EnvDTE.Project;
using ProjectItem = EnvDTE.ProjectItem;
#if VS14
using Microsoft.VisualStudio.ProjectSystem.Interop;
#endif
namespace NuGet.VisualStudio
{
public static class ProjectExtensions
{
private const string WebConfig = "web.config";
private const string AppConfig = "app.config";
private const string BinFolder = "Bin";
private static readonly Dictionary<string, string> _knownNestedFiles = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
{ "web.debug.config", "web.config" },
{ "web.release.config", "web.config" }
};
private static readonly HashSet<string> _unsupportedProjectTypes = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
VsConstants.LightSwitchProjectTypeGuid,
VsConstants.InstallShieldLimitedEditionTypeGuid
};
private static readonly IEnumerable<string> _fileKinds = new[] { VsConstants.VsProjectItemKindPhysicalFile, VsConstants.VsProjectItemKindSolutionItem };
private static readonly IEnumerable<string> _folderKinds = new[] { VsConstants.VsProjectItemKindPhysicalFolder };
// List of project types that cannot have references added to them
private static readonly string[] _unsupportedProjectTypesForAddingReferences = new[]
{
VsConstants.WixProjectTypeGuid,
VsConstants.CppProjectTypeGuid,
};
// List of project types that cannot have binding redirects added
private static readonly string[] _unsupportedProjectTypesForBindingRedirects = new[]
{
VsConstants.WixProjectTypeGuid,
VsConstants.JsProjectTypeGuid,
VsConstants.NemerleProjectTypeGuid,
VsConstants.CppProjectTypeGuid,
VsConstants.SynergexProjectTypeGuid,
VsConstants.NomadForVisualStudioProjectTypeGuid,
VsConstants.DxJsProjectTypeGuid
};
private static readonly char[] PathSeparatorChars = new[] { Path.DirectorySeparatorChar };
/// <summary>
/// Determines if NuGet is used in the project. Currently, it is determined by checking if packages.config is part of the project
/// </summary>
/// <param name="project">The project which is checked to see if NuGet is used in it</param>
public static bool IsNuGetInUse(this Project project)
{
return project.IsSupported() && project.ContainsFile(Constants.PackageReferenceFile);
}
// Get the ProjectItems for a folder path
public static ProjectItems GetProjectItems(this Project project, string folderPath, bool createIfNotExists = false)
{
if (String.IsNullOrEmpty(folderPath))
{
return project.ProjectItems;
}
// Traverse the path to get at the directory
string[] pathParts = folderPath.Split(PathSeparatorChars, StringSplitOptions.RemoveEmptyEntries);
// 'cursor' can contain a reference to either a Project instance or ProjectItem instance.
// Both types have the ProjectItems property that we want to access.
object cursor = project;
string fullPath = project.GetFullPath();
string folderRelativePath = String.Empty;
foreach (string part in pathParts)
{
fullPath = Path.Combine(fullPath, part);
folderRelativePath = Path.Combine(folderRelativePath, part);
cursor = GetOrCreateFolder(project, cursor, fullPath, folderRelativePath, part, createIfNotExists);
if (cursor == null)
{
return null;
}
}
return GetProjectItems(cursor);
}
public static ProjectItem GetProjectItem(this Project project, string path)
{
string folderPath = Path.GetDirectoryName(path);
string itemName = Path.GetFileName(path);
ProjectItems container = GetProjectItems(project, folderPath);
ProjectItem projectItem;
// If we couldn't get the folder, or the child item doesn't exist, return null
if (container == null ||
(!container.TryGetFile(itemName, out projectItem) &&
!container.TryGetFolder(itemName, out projectItem)))
{
return null;
}
return projectItem;
}
/// <summary>
/// Recursively retrieves all supported child projects of a virtual folder.
/// </summary>
/// <param name="project">The root container project</param>
public static IEnumerable<Project> GetSupportedChildProjects(this Project project)
{
if (!project.IsSolutionFolder())
{
yield break;
}
var containerProjects = new Queue<Project>();
containerProjects.Enqueue(project);
while (containerProjects.Any())
{
var containerProject = containerProjects.Dequeue();
foreach (ProjectItem item in containerProject.ProjectItems)
{
var nestedProject = item.SubProject;
if (nestedProject == null)
{
continue;
}
else if (nestedProject.IsSupported())
{
yield return nestedProject;
}
else if (nestedProject.IsSolutionFolder())
{
containerProjects.Enqueue(nestedProject);
}
}
}
}
public static bool DeleteProjectItem(this Project project, string path)
{
ProjectItem projectItem = GetProjectItem(project, path);
if (projectItem == null)
{
return false;
}
projectItem.Delete();
return true;
}
public static bool TryGetFolder(this ProjectItems projectItems, string name, out ProjectItem projectItem)
{
projectItem = GetProjectItem(projectItems, name, _folderKinds);
return projectItem != null;
}
public static bool TryGetFile(this ProjectItems projectItems, string name, out ProjectItem projectItem)
{
projectItem = GetProjectItem(projectItems, name, _fileKinds);
if (projectItem == null)
{
// Try to get the nested project item
return TryGetNestedFile(projectItems, name, out projectItem);
}
return projectItem != null;
}
public static bool ContainsFile(this Project project, string path)
{
if (string.Equals(project.Kind, VsConstants.WixProjectTypeGuid, StringComparison.OrdinalIgnoreCase) ||
string.Equals(project.Kind, VsConstants.NemerleProjectTypeGuid, StringComparison.OrdinalIgnoreCase) ||
string.Equals(project.Kind, VsConstants.FsharpProjectTypeGuid, StringComparison.OrdinalIgnoreCase))
{
// For Wix and Nemerle projects, IsDocumentInProject() returns not found
// even though the file is in the project. So we use GetProjectItem()
// instead. Nemerle is a high-level statically typed programming language for .NET platform
// Note that pszMkDocument, the document moniker, passed to IsDocumentInProject(), must be a path to the file
// for certain file-based project systems such as F#. And, not just a filename. For these project systems as well,
// do the following
ProjectItem item = project.GetProjectItem(path);
return item != null;
}
else
{
IVsProject vsProject = (IVsProject)project.ToVsHierarchy();
if (vsProject == null)
{
return false;
}
int pFound;
uint itemId;
int hr = vsProject.IsDocumentInProject(path, out pFound, new VSDOCUMENTPRIORITY[0], out itemId);
return ErrorHandler.Succeeded(hr) && pFound == 1;
}
}
/// <summary>
/// If we didn't find the project item at the top level, then we look one more level down.
/// In VS files can have other nested files like foo.aspx and foo.aspx.cs or web.config and web.debug.config.
/// These are actually top level files in the file system but are represented as nested project items in VS.
/// </summary>
private static bool TryGetNestedFile(ProjectItems projectItems, string name, out ProjectItem projectItem)
{
string parentFileName;
if (!_knownNestedFiles.TryGetValue(name, out parentFileName))
{
parentFileName = Path.GetFileNameWithoutExtension(name);
}
// If it's not one of the known nested files then we're going to look up prefixes backwards
// i.e. if we're looking for foo.aspx.cs then we look for foo.aspx then foo.aspx.cs as a nested file
ProjectItem parentProjectItem = GetProjectItem(projectItems, parentFileName, _fileKinds);
if (parentProjectItem != null)
{
// Now try to find the nested file
projectItem = GetProjectItem(parentProjectItem.ProjectItems, name, _fileKinds);
}
else
{
projectItem = null;
}
return projectItem != null;
}
public static bool SupportsConfig(this Project project)
{
return !IsClassLibrary(project);
}
public static string GetUniqueName(this Project project)
{
if (project.IsWixProject())
{
// Wix project doesn't offer UniqueName property
return project.FullName;
}
try
{
return project.UniqueName;
}
catch (COMException)
{
return project.FullName;
}
}
private static bool IsClassLibrary(this Project project)
{
if (project.IsWebSite())
{
return false;
}
// Consider class libraries projects that have one project type guid and an output type of project library.
var outputType = project.GetPropertyValue<prjOutputType>("OutputType");
return project.GetProjectTypeGuids().Length == 1 &&
outputType == prjOutputType.prjOutputTypeLibrary;
}
public static bool IsJavaScriptProject(this Project project)
{
return project != null && VsConstants.JsProjectTypeGuid.Equals(project.Kind, StringComparison.OrdinalIgnoreCase);
}
public static bool IsXnaWindowsPhoneProject(this Project project)
{
// XNA projects will have this property set
const string xnaPropertyValue = "Microsoft.Xna.GameStudio.CodeProject.WindowsPhoneProjectPropertiesExtender.XnaRefreshLevel";
return project != null &&
"Windows Phone OS 7.1".Equals(project.GetPropertyValue<string>(xnaPropertyValue), StringComparison.OrdinalIgnoreCase);
}
public static bool IsNativeProject(this Project project)
{
return project != null && VsConstants.CppProjectTypeGuid.Equals(project.Kind, StringComparison.OrdinalIgnoreCase);
}
// TODO: Return null for library projects
public static string GetConfigurationFile(this Project project)
{
return project.IsWebProject() ? WebConfig : AppConfig;
}
private static ProjectItem GetProjectItem(this ProjectItems projectItems, string name, IEnumerable<string> allowedItemKinds)
{
try
{
ProjectItem projectItem = projectItems.Item(name);
if (projectItem != null && allowedItemKinds.Contains(projectItem.Kind, StringComparer.OrdinalIgnoreCase))
{
return projectItem;
}
}
catch
{
}
return null;
}
public static IEnumerable<ProjectItem> GetChildItems(this Project project, string path, string filter, string desiredKind)
{
ProjectItems projectItems = GetProjectItems(project, path);
if (projectItems == null)
{
return Enumerable.Empty<ProjectItem>();
}
Regex matcher = filter.Equals("*.*", StringComparison.OrdinalIgnoreCase) ? null : GetFilterRegex(filter);
return from ProjectItem p in projectItems
where desiredKind.Equals(p.Kind, StringComparison.OrdinalIgnoreCase) &&
(matcher == null || matcher.IsMatch(p.Name))
select p;
}
public static string GetFullPath(this Project project)
{
return VsUtility.GetFullPath(project);
}
public static string GetTargetFramework(this Project project)
{
if (project == null)
{
return null;
}
if (project.IsJavaScriptProject())
{
// JavaScript apps do not have a TargetFrameworkMoniker property set.
// We read the TargetPlatformIdentifier and TargetPlatformVersion instead
string platformIdentifier = project.GetPropertyValue<string>("TargetPlatformIdentifier");
string platformVersion = project.GetPropertyValue<string>("TargetPlatformVersion");
// use the default values for JS if they were not given
if (String.IsNullOrEmpty(platformVersion))
platformVersion = "0.0";
if (String.IsNullOrEmpty(platformIdentifier))
platformIdentifier = "Windows";
return String.Format(CultureInfo.InvariantCulture, "{0}, Version={1}", platformIdentifier, platformVersion);
}
if (project.IsNativeProject())
{
// The C++ project does not have a TargetFrameworkMoniker property set.
// We hard-code the return value to Native.
return "Native, Version=0.0";
}
string targetFramework = project.GetPropertyValue<string>("TargetFrameworkMoniker");
// XNA project lies about its true identity, reporting itself as a normal .NET 4.0 project.
// We detect it and changes its target framework to Silverlight4-WindowsPhone71
if (".NETFramework,Version=v4.0".Equals(targetFramework, StringComparison.OrdinalIgnoreCase) &&
project.IsXnaWindowsPhoneProject())
{
return "Silverlight,Version=v4.0,Profile=WindowsPhone71";
}
return targetFramework;
}
public static FrameworkName GetTargetFrameworkName(this Project project)
{
string targetFrameworkMoniker = project.GetTargetFramework();
if (targetFrameworkMoniker != null)
{
return new FrameworkName(targetFrameworkMoniker);
}
return null;
}
public static T GetPropertyValue<T>(this Project project, string propertyName)
{
return VsUtility.GetPropertyValue<T>(project, propertyName);
}
internal static Regex GetFilterRegex(string wildcard)
{
string pattern = String.Join(String.Empty, wildcard.Split('.').Select(GetPattern));
return new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
}
private static string GetPattern(string token)
{
return token == "*" ? @"(.*)" : @"(" + token + ")";
}
// 'parentItem' can be either a Project or ProjectItem
private static ProjectItem GetOrCreateFolder(
Project project,
object parentItem,
string fullPath,
string folderRelativePath,
string folderName,
bool createIfNotExists)
{
if (parentItem == null)
{
return null;
}
ProjectItem subFolder;
ProjectItems projectItems = GetProjectItems(parentItem);
if (projectItems.TryGetFolder(folderName, out subFolder))
{
// Get the sub folder
return subFolder;
}
else if (createIfNotExists)
{
// The JS Metro project system has a bug whereby calling AddFolder() to an existing folder that
// does not belong to the project will throw. To work around that, we have to manually include
// it into our project.
if (project.IsJavaScriptProject() && Directory.Exists(fullPath))
{
bool succeeded = IncludeExistingFolderToProject(project, folderRelativePath);
if (succeeded)
{
// IMPORTANT: after including the folder into project, we need to get
// a new ProjectItems snapshot from the parent item. Otherwise, reusing
// the old snapshot from above won't have access to the added folder.
projectItems = GetProjectItems(parentItem);
if (projectItems.TryGetFolder(folderName, out subFolder))
{
// Get the sub folder
return subFolder;
}
}
return null;
}
try
{
return projectItems.AddFromDirectory(fullPath);
}
catch (NotImplementedException)
{
// This is the case for F#'s project system, we can't add from directory so we fall back
// to this impl
return projectItems.AddFolder(folderName);
}
}
return null;
}
private static ProjectItems GetProjectItems(object parent)
{
var project = parent as Project;
if (project != null)
{
return project.ProjectItems;
}
var projectItem = parent as ProjectItem;
if (projectItem != null)
{
return projectItem.ProjectItems;
}
return null;
}
private static bool IncludeExistingFolderToProject(Project project, string folderRelativePath)
{
IVsUIHierarchy projectHierarchy = (IVsUIHierarchy)project.ToVsHierarchy();
uint itemId;
int hr = projectHierarchy.ParseCanonicalName(folderRelativePath, out itemId);
if (!ErrorHandler.Succeeded(hr))
{
return false;
}
// Execute command to include the existing folder into project. Must do this on UI thread.
hr = ThreadHelper.Generic.Invoke(() =>
projectHierarchy.ExecCommand(
itemId,
ref VsMenus.guidStandardCommandSet2K,
(int)VSConstants.VSStd2KCmdID.INCLUDEINPROJECT,
0,
IntPtr.Zero,
IntPtr.Zero));
return ErrorHandler.Succeeded(hr);
}
public static bool IsWebProject(this Project project)
{
string[] types = project.GetProjectTypeGuids();
return types.Contains(VsConstants.WebSiteProjectTypeGuid, StringComparer.OrdinalIgnoreCase) ||
types.Contains(VsConstants.WebApplicationProjectTypeGuid, StringComparer.OrdinalIgnoreCase);
}
public static bool IsWebSite(this Project project)
{
return project.Kind != null && project.Kind.Equals(VsConstants.WebSiteProjectTypeGuid, StringComparison.OrdinalIgnoreCase);
}
public static bool IsWindowsStoreApp(this Project project)
{
string[] types = project.GetProjectTypeGuids();
return types.Contains(VsConstants.WindowsStoreProjectTypeGuid, StringComparer.OrdinalIgnoreCase);
}
public static bool IsWixProject(this Project project)
{
return project.Kind != null && project.Kind.Equals(VsConstants.WixProjectTypeGuid, StringComparison.OrdinalIgnoreCase);
}
public static bool IsSupported(this Project project)
{
return VsUtility.IsSupported(project);
}
public static bool SupportsINuGetProjectSystem(this Project project)
{
#if VS14
return project.ToNuGetProjectSystem() != null;
#else
return false;
#endif
}
#if VS14
public static INuGetPackageManager ToNuGetProjectSystem(this Project project)
{
var vsProject = project.ToVsHierarchy() as IVsProject;
if (vsProject == null)
{
return null;
}
Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider;
int hr = vsProject.GetItemContext(
(uint)VSConstants.VSITEMID.Root,
out serviceProvider);
if (hr < 0)
{
return null;
}
using (var sp = new ServiceProvider(serviceProvider))
{
var retValue = sp.GetService(typeof(INuGetPackageManager));
if (retValue == null)
{
return null;
}
var properties = retValue.GetType().GetProperties().Where(p => p.Name == "Value");
if (properties.Count() != 1)
{
return null;
}
var v = properties.First().GetValue(retValue) as INuGetPackageManager;
return v as INuGetPackageManager;
}
}
#endif
public static bool IsExplicitlyUnsupported(this Project project)
{
return project.Kind == null || _unsupportedProjectTypes.Contains(project.Kind);
}
public static bool IsSolutionFolder(this Project project)
{
return project.Kind != null && project.Kind.Equals(VsConstants.VsProjectItemKindSolutionFolder, StringComparison.OrdinalIgnoreCase);
}
public static bool IsTopLevelSolutionFolder(this Project project)
{
return IsSolutionFolder(project) && project.ParentProjectItem == null;
}
public static bool SupportsReferences(this Project project)
{
return project.Kind != null &&
!_unsupportedProjectTypesForAddingReferences.Contains(project.Kind, StringComparer.OrdinalIgnoreCase);
}
public static bool SupportsBindingRedirects(this Project project)
{
return (project.Kind != null & !_unsupportedProjectTypesForBindingRedirects.Contains(project.Kind, StringComparer.OrdinalIgnoreCase)) &&
!project.IsWindowsStoreApp();
}
public static bool IsUnloaded(this Project project)
{
return VsConstants.UnloadedProjectTypeGuid.Equals(project.Kind, StringComparison.OrdinalIgnoreCase);
}
public static string GetOutputPath(this Project project)
{
// For Websites the output path is the bin folder
string outputPath = project.IsWebSite() ? BinFolder : project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString();
return Path.Combine(project.GetFullPath(), outputPath);
}
public static IVsHierarchy ToVsHierarchy(this Project project)
{
IVsHierarchy hierarchy;
// Get the vs solution
IVsSolution solution = ServiceLocator.GetInstance<IVsSolution>();
int hr = solution.GetProjectOfUniqueName(project.GetUniqueName(), out hierarchy);
if (hr != VsConstants.S_OK)
{
Marshal.ThrowExceptionForHR(hr);
}
return hierarchy;
}
public static IVsProjectBuildSystem ToVsProjectBuildSystem(this Project project)
{
if (project == null)
{
throw new ArgumentNullException("project");
}
// Convert the project to an IVsHierarchy and see if it implements IVsProjectBuildSystem
return project.ToVsHierarchy() as IVsProjectBuildSystem;
}
public static bool IsCompatible(this Project project, IPackage package)
{
if (package == null)
{
return true;
}
// if there is any file under content/lib which has no target framework, we consider the package
// compatible with any project, because that file will be the fallback if no supported frameworks matches the project's.
// REVIEW: what about install.ps1 and uninstall.ps1?
if (package.HasFileWithNullTargetFramework())
{
return true;
}
FrameworkName frameworkName = project.GetTargetFrameworkName();
// if the target framework cannot be determined the frameworkName becomes null (for example, for WiX projects).
// indicate it as compatible, because we cannot determine that ourselves. Offer the capability to the end-user.
if (frameworkName == null)
{
return true;
}
return VersionUtility.IsCompatible(frameworkName, package.GetSupportedFrameworks());
}
public static string[] GetProjectTypeGuids(this Project project)
{
// Get the vs hierarchy as an IVsAggregatableProject to get the project type guids
var hierarchy = project.ToVsHierarchy();
var aggregatableProject = hierarchy as IVsAggregatableProject;
if (aggregatableProject != null)
{
string projectTypeGuids;
int hr = aggregatableProject.GetAggregateProjectTypeGuids(out projectTypeGuids);
if (hr != VsConstants.S_OK)
{
Marshal.ThrowExceptionForHR(hr);
}
return projectTypeGuids.Split(';');
}
else if (!String.IsNullOrEmpty(project.Kind))
{
return new[] { project.Kind };
}
else
{
return new string[0];
}
}
public static string GetAllProjectTypeGuid(this Project project)
{
// Get the vs hierarchy as an IVsAggregatableProject to get the project type guids
var hierarchy = project.ToVsHierarchy();
var aggregatableProject = hierarchy as IVsAggregatableProject;
if (aggregatableProject != null)
{
string projectTypeGuids;
int hr = aggregatableProject.GetAggregateProjectTypeGuids(out projectTypeGuids);
if (hr != VsConstants.S_OK)
{
return null;
}
return projectTypeGuids;
}
else if (!String.IsNullOrEmpty(project.Kind))
{
return project.Kind;
}
else
{
return null;
}
}
internal static IList<Project> GetReferencedProjects(this Project project)
{
if (project.IsWebSite())
{
return GetWebsiteReferencedProjects(project);
}
var projects = new List<Project>();
References references;
try
{
references = project.GetReferences();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
{
//References property doesn't exist, project does not have references
references = null;
}
if (references != null)
{
foreach (Reference reference in references)
{
// Get the referenced project from the reference if any
if (reference.SourceProject != null)
{
projects.Add(reference.SourceProject);
}
}
}
return projects;
}
internal static HashSet<string> GetAssemblyClosure(this Project project, IFileSystemProvider projectFileSystemProvider, IDictionary<string, HashSet<string>> visitedProjects)
{
HashSet<string> assemblies;
if (visitedProjects.TryGetValue(project.UniqueName, out assemblies))
{
return assemblies;
}
assemblies = new HashSet<string>(PathComparer.Default);
assemblies.AddRange(GetLocalProjectAssemblies(project, projectFileSystemProvider));
assemblies.AddRange(project.GetReferencedProjects().SelectMany(p => GetAssemblyClosure(p, projectFileSystemProvider, visitedProjects)));
visitedProjects.Add(project.UniqueName, assemblies);
return assemblies;
}
private static IList<Project> GetWebsiteReferencedProjects(Project project)
{
var projects = new List<Project>();
AssemblyReferences references = project.GetAssemblyReferences();
foreach (AssemblyReference reference in references)
{
if (reference.ReferencedProject != null)
{
projects.Add(reference.ReferencedProject);
}
}
return projects;
}
private static HashSet<string> GetLocalProjectAssemblies(Project project, IFileSystemProvider projectFileSystemProvider)
{
if (project.IsWebSite())
{
return GetWebsiteLocalAssemblies(project, projectFileSystemProvider);
}
var assemblies = new HashSet<string>(PathComparer.Default);
References references;
try
{
references = project.GetReferences();
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
{
//References property doesn't exist, project does not have references
references = null;
}
if (references != null)
{
foreach (Reference reference in references)
{
// Get the referenced project from the reference if any
if (reference.SourceProject == null &&
reference.CopyLocal &&
File.Exists(reference.Path))
{
assemblies.Add(reference.Path);
}
}
}
return assemblies;
}
private static HashSet<string> GetWebsiteLocalAssemblies(Project project, IFileSystemProvider projectFileSystemProvider)
{
var assemblies = new HashSet<string>(PathComparer.Default);
AssemblyReferences references = project.GetAssemblyReferences();
foreach (AssemblyReference reference in references)
{
// For websites only include bin assemblies
if (reference.ReferencedProject == null &&
reference.ReferenceKind == AssemblyReferenceType.AssemblyReferenceBin &&
File.Exists(reference.FullPath))
{
assemblies.Add(reference.FullPath);
}
}
// For website projects, we always add .refresh files that point to the corresponding binaries in packages. In the event of bin deployed assemblies that are also GACed,
// the ReferenceKind is not AssemblyReferenceBin. Consequently, we work around this by looking for any additional assembly declarations specified via .refresh files.
string projectPath = project.GetFullPath();
var fileSystem = projectFileSystemProvider.GetFileSystem(projectPath);
assemblies.AddRange(fileSystem.ResolveRefreshPaths());
return assemblies;
}
public static MsBuildProject AsMSBuildProject(this Project project)
{
return ProjectCollection.GlobalProjectCollection.GetLoadedProjects(project.FullName).FirstOrDefault() ??
ProjectCollection.GlobalProjectCollection.LoadProject(project.FullName);
}
/// <summary>
/// Returns the unique name of the specified project including all solution folder names containing it.
/// </summary>
/// <remarks>
/// This is different from the DTE Project.UniqueName property, which is the absolute path to the project file.
/// </remarks>
public static string GetCustomUniqueName(this Project project)
{
if (project.IsWebSite())
{
// website projects always have unique name
return project.Name;
}
else
{
Stack<string> nameParts = new Stack<string>();
Project cursor = project;
nameParts.Push(cursor.GetName());
// walk up till the solution root
while (cursor.ParentProjectItem != null && cursor.ParentProjectItem.ContainingProject != null)
{
cursor = cursor.ParentProjectItem.ContainingProject;
nameParts.Push(cursor.GetName());
}
return String.Join("\\", nameParts);
}
}
public static void Save(this Project project, IFileSystem fileSystem)
{
fileSystem.MakeFileWritable(project.FullName);
project.Save();
}
public static void AddImportStatement(this Project project, string targetsPath, ProjectImportLocation location)
{
NuGet.MSBuildProjectUtility.AddImportStatement(project.AsMSBuildProject(), targetsPath, location);
}
public static void RemoveImportStatement(this Project project, string targetsPath)
{
NuGet.MSBuildProjectUtility.RemoveImportStatement(project.AsMSBuildProject(), targetsPath);
}
/// <summary>
/// DO NOT delete this. This method is only called from PowerShell functional test.
/// </summary>
public static void RemoveProject(string projectName)
{
if (String.IsNullOrEmpty(projectName))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "projectName");
}
var solutionManager = (ISolutionManager)ServiceLocator.GetInstance<ISolutionManager>();
if (solutionManager != null)
{
var project = solutionManager.GetProject(projectName);
if (project == null)
{
throw new InvalidOperationException();
}
var dte = ServiceLocator.GetGlobalService<SDTE, DTE>();
dte.Solution.Remove(project);
}
}
// This method should only be called in VS 2012
[MethodImpl(MethodImplOptions.NoInlining)]
public static void DoWorkInWriterLock(this Project project, Action<MsBuildProject> action)
{
IVsBrowseObjectContext context = project.Object as IVsBrowseObjectContext;
if (context == null)
{
IVsHierarchy hierarchy = project.ToVsHierarchy();
context = hierarchy as IVsBrowseObjectContext;
}
if (context != null)
{
var service = context.UnconfiguredProject.ProjectService.Services.DirectAccessService;
if (service != null)
{
// This has to run on Main thread, otherwise it will dead-lock (for C++ projects at least)
ThreadHelper.Generic.Invoke(() =>
service.Write(
context.UnconfiguredProject.FullPath,
dwa =>
{
MsBuildProject buildProject = dwa.GetProject(context.UnconfiguredProject.Services.SuggestedConfiguredProject);
action(buildProject);
},
ProjectAccess.Read | ProjectAccess.Write)
);
}
}
}
public static bool IsParentProjectExplicitlyUnsupported(this Project project)
{
if (project.ParentProjectItem == null || project.ParentProjectItem.ContainingProject == null)
{
// this project is not a child of another project
return false;
}
Project parentProject = project.ParentProjectItem.ContainingProject;
return parentProject.IsExplicitlyUnsupported();
}
public static References GetReferences(this Project project)
{
dynamic projectObj = project.Object;
var references = (References)projectObj.References;
projectObj = null;
return references;
}
public static AssemblyReferences GetAssemblyReferences(this Project project)
{
dynamic projectObj = project.Object;
var references = (AssemblyReferences)projectObj.References;
projectObj = null;
return references;
}
public static void EnsureCheckedOutIfExists(this Project project, IFileSystem fileSystem, string path)
{
var fullPath = fileSystem.GetFullPath(path);
if (fileSystem.FileExists(path))
{
fileSystem.MakeFileWritable(path);
if (project.DTE.SourceControl != null &&
project.DTE.SourceControl.IsItemUnderSCC(fullPath) &&
!project.DTE.SourceControl.IsItemCheckedOut(fullPath))
{
// Check out the item
project.DTE.SourceControl.CheckOutItem(fullPath);
}
}
}
/// <summary>
/// This method truncates Website projects into the VS-format, e.g. C:\..\WebSite1
/// This is used for displaying in the projects combo box.
/// </summary>
public static string GetDisplayName(this Project project, ISolutionManager solutionManager)
{
return GetDisplayName(project, solutionManager.GetProjectSafeName);
}
/// <summary>
/// This method truncates Website projects into the VS-format, e.g. C:\..\WebSite1, but it uses Name instead of SafeName from Solution Manager.
/// </summary>
public static string GetDisplayName(this Project project)
{
return GetDisplayName(project, p => p.Name);
}
private static string GetDisplayName(this Project project, Func<Project, string> nameSelector)
{
string name = nameSelector(project);
if (project.IsWebSite())
{
name = PathHelper.SmartTruncate(name, 40);
}
return name;
}
private class PathComparer : IEqualityComparer<string>
{
public static readonly PathComparer Default = new PathComparer();
public bool Equals(string x, string y)
{
return Path.GetFileName(x).Equals(Path.GetFileName(y));
}
public int GetHashCode(string obj)
{
return Path.GetFileName(obj).GetHashCode();
}
}
/// <summary>
/// Check if the project has the SharedAssetsProject capability. This is true
/// for shared projects in universal apps.
/// </summary>
public static bool IsSharedProject(this Project project)
{
bool isShared = false;
var hier = project.ToVsHierarchy();
// VSHPROPID_ProjectCapabilities is a space delimited list of capabilities (Dev11+)
object capObj;
if (ErrorHandler.Succeeded(hier.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID5.VSHPROPID_ProjectCapabilities, out capObj)) && capObj != null)
{
string cap = capObj as string;
if (!String.IsNullOrEmpty(cap))
{
isShared = cap.Split(' ').Any(s => StringComparer.OrdinalIgnoreCase.Equals("SharedAssetsProject", s));
}
}
return isShared;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Marten.NodaTime.Testing.TestData;
using Marten.Testing.Events.Projections;
using Marten.Testing.Harness;
using NodaTime;
using Shouldly;
using Xunit;
namespace Marten.NodaTime.Testing.Acceptance
{
[Collection("noda_time_integration")]
public class noda_time_acceptance: OneOffConfigurationsContext
{
public void noda_time_default_setup()
{
// SAMPLE: noda_time_default_setup
var store = DocumentStore.For(_ =>
{
_.Connection(ConnectionSource.ConnectionString);
// sets up NodaTime handling
_.UseNodaTime();
});
// ENDSAMPLE
}
public void noda_time_setup_without_json_net_serializer_configuration()
{
// SAMPLE: noda_time_setup_without_json_net_serializer_configuration
var store = DocumentStore.For(_ =>
{
_.Connection(ConnectionSource.ConnectionString);
_.Serializer<CustomJsonSerializer>();
// sets up NodaTime handling
_.UseNodaTime(shouldConfigureJsonNetSerializer: false);
});
// ENDSAMPLE
}
[Fact]
public void can_insert_document()
{
StoreOptions(_ => _.UseNodaTime());
var testDoc = TargetWithDates.Generate();
using (var session = theStore.OpenSession())
{
session.Insert(testDoc);
session.SaveChanges();
}
using (var query = theStore.QuerySession())
{
var docFromDb = query.Query<TargetWithDates>().FirstOrDefault(d => d.Id == testDoc.Id);
docFromDb.ShouldNotBeNull();
docFromDb.Equals(testDoc).ShouldBeTrue();
}
}
[Fact]
public void can_query_document_with_noda_time_types()
{
StoreOptions(_ =>
{
_.UseNodaTime();
_.DatabaseSchemaName = "NodaTime";
});
var dateTime = DateTime.UtcNow;
var localDateTime = LocalDateTime.FromDateTime(dateTime);
var instantUTC = Instant.FromDateTimeUtc(dateTime.ToUniversalTime());
var testDoc = TargetWithDates.Generate(dateTime);
using (var session = theStore.OpenSession())
{
session.Insert(testDoc);
session.SaveChanges();
}
using (var query = theStore.QuerySession())
{
var results = new List<TargetWithDates>
{
// LocalDate
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDate == localDateTime.Date),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDate < localDateTime.Date.PlusDays(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDate <= localDateTime.Date.PlusDays(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDate > localDateTime.Date.PlusDays(-1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDate >= localDateTime.Date.PlusDays(-1)),
//// Nullable LocalDate
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate == localDateTime.Date),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate < localDateTime.Date.PlusDays(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate <= localDateTime.Date.PlusDays(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate > localDateTime.Date.PlusDays(-1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDate >= localDateTime.Date.PlusDays(-1)),
//// LocalDateTime
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDateTime == localDateTime),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDateTime < localDateTime.PlusSeconds(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDateTime <= localDateTime.PlusSeconds(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDateTime > localDateTime.PlusSeconds(-1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.LocalDateTime >= localDateTime.PlusSeconds(-1)),
//// Nullable LocalDateTime
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime == localDateTime),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime < localDateTime.PlusSeconds(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime <= localDateTime.PlusSeconds(1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime > localDateTime.PlusSeconds(-1)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableLocalDateTime >= localDateTime.PlusSeconds(-1)),
//// Instant UTC
query.Query<TargetWithDates>().FirstOrDefault(d => d.InstantUTC == instantUTC),
query.Query<TargetWithDates>().FirstOrDefault(d => d.InstantUTC < instantUTC.PlusTicks(1000)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.InstantUTC <= instantUTC.PlusTicks(1000)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.InstantUTC > instantUTC.PlusTicks(-1000)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.InstantUTC >= instantUTC.PlusTicks(-1000)),
// Nullable Instant UTC
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC == instantUTC),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC < instantUTC.PlusTicks(1000)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC <= instantUTC.PlusTicks(1000)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC > instantUTC.PlusTicks(-1000)),
query.Query<TargetWithDates>().FirstOrDefault(d => d.NullableInstantUTC >= instantUTC.PlusTicks(-1000))
};
results.ShouldAllBe(x => x.Equals(testDoc));
}
}
[Fact]
public async Task can_append_and_query_events()
{
StoreOptions(_ => _.UseNodaTime());
var startDate = DateTime.UtcNow;
var streamId = Guid.NewGuid();
var @event = new MonsterSlayed()
{
QuestId = Guid.NewGuid(),
Name = "test"
};
using (var session = theStore.OpenSession())
{
session.Events.Append(streamId, @event);
session.SaveChanges();
var streamState = session.Events.FetchStreamState(streamId);
var streamState2 = await session.Events.FetchStreamStateAsync(streamId);
var streamState3 = session.Events.FetchStream(streamId, timestamp: startDate);
}
}
[Fact]
public void bug_1276_can_select_instant()
{
StoreOptions(_ => _.UseNodaTime());
var dateTime = DateTime.UtcNow;
var instantUTC = Instant.FromDateTimeUtc(dateTime.ToUniversalTime());
var testDoc = TargetWithDates.Generate(dateTime);
using (var session = theStore.OpenSession())
{
session.Insert(testDoc);
session.SaveChanges();
}
using (var query = theStore.QuerySession())
{
var resulta = query.Query<TargetWithDates>()
.Where(c => c.Id == testDoc.Id)
.Single();
var result = query.Query<TargetWithDates>()
.Where(c => c.Id == testDoc.Id)
.Select(c => new { c.Id, c.InstantUTC })
.Single();
result.ShouldNotBeNull();
result.Id.ShouldBe(testDoc.Id);
ShouldBeEqualWithDbPrecision(result.InstantUTC, instantUTC);
}
}
private class CustomJsonSerializer: ISerializer
{
public EnumStorage EnumStorage => throw new NotImplementedException();
public Casing Casing => throw new NotImplementedException();
public CollectionStorage CollectionStorage => throw new NotImplementedException();
public NonPublicMembersStorage NonPublicMembersStorage => throw new NotImplementedException();
public T FromJson<T>(TextReader reader)
{
throw new NotImplementedException();
}
public object FromJson(Type type, TextReader reader)
{
throw new NotImplementedException();
}
public string ToCleanJson(object document)
{
throw new NotImplementedException();
}
public void ToJson(object document, TextWriter writer)
{
throw new NotImplementedException();
}
public string ToJson(object document)
{
throw new NotImplementedException();
}
}
private static void ShouldBeEqualWithDbPrecision(Instant actual, Instant expected)
{
Instant toDbPrecision(Instant date) => Instant.FromUnixTimeMilliseconds(date.ToUnixTimeMilliseconds() / 100 * 100);
toDbPrecision(actual).ShouldBe(toDbPrecision(expected));
}
public noda_time_acceptance() : base("noda_time_integration")
{
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Linq;
using NServiceKit.Text.Json;
using NServiceKit.Text.Jsv;
namespace NServiceKit.Text.Common
{
/// <summary>The js writer.</summary>
public static class JsWriter
{
/// <summary>The type attribute.</summary>
public const string TypeAttr = "__type";
/// <summary>The map start character.</summary>
public const char MapStartChar = '{';
/// <summary>The map key seperator.</summary>
public const char MapKeySeperator = ':';
/// <summary>The item seperator.</summary>
public const char ItemSeperator = ',';
/// <summary>The map end character.</summary>
public const char MapEndChar = '}';
/// <summary>The map null value.</summary>
public const string MapNullValue = "\"\"";
/// <summary>The empty map.</summary>
public const string EmptyMap = "{}";
/// <summary>The list start character.</summary>
public const char ListStartChar = '[';
/// <summary>The list end character.</summary>
public const char ListEndChar = ']';
/// <summary>The return character.</summary>
public const char ReturnChar = '\r';
/// <summary>The line feed character.</summary>
public const char LineFeedChar = '\n';
/// <summary>The quote character.</summary>
public const char QuoteChar = '"';
/// <summary>The quote string.</summary>
public const string QuoteString = "\"";
/// <summary>The escaped quote string.</summary>
public const string EscapedQuoteString = "\\\"";
/// <summary>The item seperator string.</summary>
public const string ItemSeperatorString = ",";
/// <summary>The map key seperator string.</summary>
public const string MapKeySeperatorString = ":";
/// <summary>The CSV characters.</summary>
public static readonly char[] CsvChars = new[] { ItemSeperator, QuoteChar };
/// <summary>The escape characters.</summary>
public static readonly char[] EscapeChars = new[] { QuoteChar, MapKeySeperator, ItemSeperator, MapStartChar, MapEndChar, ListStartChar, ListEndChar, ReturnChar, LineFeedChar };
/// <summary>The length from largest character.</summary>
private const int LengthFromLargestChar = '}' + 1;
/// <summary>The escape character flags.</summary>
private static readonly bool[] EscapeCharFlags = new bool[LengthFromLargestChar];
/// <summary>Initializes static members of the NServiceKit.Text.Common.JsWriter class.</summary>
static JsWriter()
{
foreach (var escapeChar in EscapeChars)
{
EscapeCharFlags[escapeChar] = true;
}
var loadConfig = JsConfig.EmitCamelCaseNames; //force load
}
/// <summary>Writes a dynamic.</summary>
/// <param name="callback">The callback.</param>
public static void WriteDynamic(Action callback)
{
JsState.IsWritingDynamic = true;
try
{
callback();
}
finally
{
JsState.IsWritingDynamic = false;
}
}
/// <summary>micro optimizations: using flags instead of value.IndexOfAny(EscapeChars)</summary>
/// <param name="value">.</param>
/// <returns>true if any escape characters, false if not.</returns>
public static bool HasAnyEscapeChars(string value)
{
var len = value.Length;
for (var i = 0; i < len; i++)
{
var c = value[i];
if (c >= LengthFromLargestChar || !EscapeCharFlags[c]) continue;
return true;
}
return false;
}
/// <summary>Writes an item seperator if ran once.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="ranOnce">The ran once.</param>
internal static void WriteItemSeperatorIfRanOnce(TextWriter writer, ref bool ranOnce)
{
if (ranOnce)
writer.Write(ItemSeperator);
else
ranOnce = true;
}
/// <summary>Determine if we should use default to string method.</summary>
/// <param name="type">The type.</param>
/// <returns>true if it succeeds, false if it fails.</returns>
internal static bool ShouldUseDefaultToStringMethod(Type type)
{
return type == typeof(byte) || type == typeof(byte?)
|| type == typeof(short) || type == typeof(short?)
|| type == typeof(ushort) || type == typeof(ushort?)
|| type == typeof(int) || type == typeof(int?)
|| type == typeof(uint) || type == typeof(uint?)
|| type == typeof(long) || type == typeof(long?)
|| type == typeof(ulong) || type == typeof(ulong?)
|| type == typeof(bool) || type == typeof(bool?)
|| type == typeof(DateTime) || type == typeof(DateTime?)
|| type == typeof(Guid) || type == typeof(Guid?)
|| type == typeof(float) || type == typeof(float?)
|| type == typeof(double) || type == typeof(double?)
|| type == typeof(decimal) || type == typeof(decimal?);
}
/// <summary>Gets type serializer.</summary>
/// <exception cref="NotSupportedException">Thrown when the requested operation is not supported.</exception>
/// <typeparam name="TSerializer">Type of the serializer.</typeparam>
/// <returns>The type serializer.</returns>
internal static ITypeSerializer GetTypeSerializer<TSerializer>()
{
if (typeof(TSerializer) == typeof(JsvTypeSerializer))
return JsvTypeSerializer.Instance;
if (typeof(TSerializer) == typeof(JsonTypeSerializer))
return JsonTypeSerializer.Instance;
throw new NotSupportedException(typeof(TSerializer).Name);
}
#if NETFX_CORE
private static readonly Type[] knownTypes = new Type[] {
typeof(bool), typeof(char), typeof(sbyte), typeof(byte),
typeof(short), typeof(ushort), typeof(int), typeof(uint),
typeof(long), typeof(ulong), typeof(float), typeof(double),
typeof(decimal), typeof(string),
typeof(DateTime), typeof(TimeSpan), typeof(Guid), typeof(Uri),
typeof(byte[]), typeof(System.Type)};
private static readonly NServiceKitTypeCode[] knownCodes = new NServiceKitTypeCode[] {
NServiceKitTypeCode.Boolean, NServiceKitTypeCode.Char, NServiceKitTypeCode.SByte, NServiceKitTypeCode.Byte,
NServiceKitTypeCode.Int16, NServiceKitTypeCode.UInt16, NServiceKitTypeCode.Int32, NServiceKitTypeCode.UInt32,
NServiceKitTypeCode.Int64, NServiceKitTypeCode.UInt64, NServiceKitTypeCode.Single, NServiceKitTypeCode.Double,
NServiceKitTypeCode.Decimal, NServiceKitTypeCode.String,
NServiceKitTypeCode.DateTime, NServiceKitTypeCode.TimeSpan, NServiceKitTypeCode.Guid, NServiceKitTypeCode.Uri,
NServiceKitTypeCode.ByteArray, NServiceKitTypeCode.Type
};
internal enum NServiceKitTypeCode
{
Empty = 0,
Unknown = 1, // maps to TypeCode.Object
Boolean = 3,
Char = 4,
SByte = 5,
Byte = 6,
Int16 = 7,
UInt16 = 8,
Int32 = 9,
UInt32 = 10,
Int64 = 11,
UInt64 = 12,
Single = 13,
Double = 14,
Decimal = 15,
DateTime = 16,
String = 18,
// additions
TimeSpan = 100,
ByteArray = 101,
Guid = 102,
Uri = 103,
Type = 104
}
private static NServiceKitTypeCode GetTypeCode(Type type)
{
int idx = Array.IndexOf<Type>(knownTypes, type);
if (idx >= 0) return knownCodes[idx];
return type == null ? NServiceKitTypeCode.Empty : NServiceKitTypeCode.Unknown;
}
#endif
/// <summary>Writes an enum flags.</summary>
/// <param name="writer"> The writer.</param>
/// <param name="enumFlagValue">The enum flag value.</param>
public static void WriteEnumFlags(TextWriter writer, object enumFlagValue)
{
if (enumFlagValue == null) return;
#if NETFX_CORE
var typeCode = GetTypeCode(Enum.GetUnderlyingType(enumFlagValue.GetType()));
switch (typeCode)
{
case NServiceKitTypeCode.Byte:
writer.Write((byte)enumFlagValue);
break;
case NServiceKitTypeCode.Int16:
writer.Write((short)enumFlagValue);
break;
case NServiceKitTypeCode.UInt16:
writer.Write((ushort)enumFlagValue);
break;
case NServiceKitTypeCode.Int32:
writer.Write((int)enumFlagValue);
break;
case NServiceKitTypeCode.UInt32:
writer.Write((uint)enumFlagValue);
break;
case NServiceKitTypeCode.Int64:
writer.Write((long)enumFlagValue);
break;
case NServiceKitTypeCode.UInt64:
writer.Write((ulong)enumFlagValue);
break;
default:
writer.Write((int)enumFlagValue);
break;
}
#else
var typeCode = Type.GetTypeCode(Enum.GetUnderlyingType(enumFlagValue.GetType()));
switch (typeCode)
{
case TypeCode.SByte:
writer.Write((sbyte) enumFlagValue);
break;
case TypeCode.Byte:
writer.Write((byte)enumFlagValue);
break;
case TypeCode.Int16:
writer.Write((short)enumFlagValue);
break;
case TypeCode.UInt16:
writer.Write((ushort)enumFlagValue);
break;
case TypeCode.Int32:
writer.Write((int)enumFlagValue);
break;
case TypeCode.UInt32:
writer.Write((uint)enumFlagValue);
break;
case TypeCode.Int64:
writer.Write((long)enumFlagValue);
break;
case TypeCode.UInt64:
writer.Write((ulong)enumFlagValue);
break;
default:
writer.Write((int)enumFlagValue);
break;
}
#endif
}
}
/// <summary>The js writer.</summary>
/// <typeparam name="TSerializer">Type of the serializer.</typeparam>
internal class JsWriter<TSerializer>
where TSerializer : ITypeSerializer
{
/// <summary>The serializer.</summary>
private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
/// <summary>
/// Initializes a new instance of the NServiceKit.Text.Common.JsWriter<TSerializer>
/// class.
/// </summary>
public JsWriter()
{
this.SpecialTypes = new Dictionary<Type, WriteObjectDelegate>
{
{ typeof(Uri), Serializer.WriteObjectString },
{ typeof(Type), WriteType },
{ typeof(Exception), Serializer.WriteException },
#if !MONOTOUCH && !SILVERLIGHT && !XBOX && !ANDROID
{ typeof(System.Data.Linq.Binary), Serializer.WriteLinqBinary },
#endif
};
}
/// <summary>Gets value type to string method.</summary>
/// <param name="type">The type.</param>
/// <returns>The value type to string method.</returns>
public WriteObjectDelegate GetValueTypeToStringMethod(Type type)
{
if (type == typeof(char) || type == typeof(char?))
return Serializer.WriteChar;
if (type == typeof(int) || type == typeof(int?))
return Serializer.WriteInt32;
if (type == typeof(long) || type == typeof(long?))
return Serializer.WriteInt64;
if (type == typeof(ulong) || type == typeof(ulong?))
return Serializer.WriteUInt64;
if (type == typeof(uint) || type == typeof(uint?))
return Serializer.WriteUInt32;
if (type == typeof(byte) || type == typeof(byte?))
return Serializer.WriteByte;
if (type == typeof(short) || type == typeof(short?))
return Serializer.WriteInt16;
if (type == typeof(ushort) || type == typeof(ushort?))
return Serializer.WriteUInt16;
if (type == typeof(bool) || type == typeof(bool?))
return Serializer.WriteBool;
if (type == typeof(DateTime))
return Serializer.WriteDateTime;
if (type == typeof(DateTime?))
return Serializer.WriteNullableDateTime;
if (type == typeof(DateTimeOffset))
return Serializer.WriteDateTimeOffset;
if (type == typeof(DateTimeOffset?))
return Serializer.WriteNullableDateTimeOffset;
if (type == typeof(TimeSpan))
return Serializer.WriteTimeSpan;
if (type == typeof(TimeSpan?))
return Serializer.WriteNullableTimeSpan;
if (type == typeof(Guid))
return Serializer.WriteGuid;
if (type == typeof(Guid?))
return Serializer.WriteNullableGuid;
if (type == typeof(float) || type == typeof(float?))
return Serializer.WriteFloat;
if (type == typeof(double) || type == typeof(double?))
return Serializer.WriteDouble;
if (type == typeof(decimal) || type == typeof(decimal?))
return Serializer.WriteDecimal;
if (type.IsUnderlyingEnum())
return type.FirstAttribute<FlagsAttribute>(false) != null
? (WriteObjectDelegate)Serializer.WriteEnumFlags
: Serializer.WriteEnum;
Type nullableType;
if ((nullableType = Nullable.GetUnderlyingType(type)) != null && nullableType.IsEnum())
return nullableType.FirstAttribute<FlagsAttribute>(false) != null
? (WriteObjectDelegate)Serializer.WriteEnumFlags
: Serializer.WriteEnum;
if (type.HasInterface(typeof (IFormattable)))
return Serializer.WriteFormattableObjectString;
return Serializer.WriteObjectString;
}
/// <summary>Gets write function.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <returns>The write function.</returns>
internal WriteObjectDelegate GetWriteFn<T>()
{
if (typeof(T) == typeof(string))
{
return Serializer.WriteObjectString;
}
var onSerializingFn = JsConfig<T>.OnSerializingFn;
if (onSerializingFn != null)
{
return (w, x) => GetCoreWriteFn<T>()(w, onSerializingFn((T)x));
}
if (JsConfig<T>.HasSerializeFn)
{
return JsConfig<T>.WriteFn<TSerializer>;
}
return GetCoreWriteFn<T>();
}
/// <summary>Gets core write function.</summary>
/// <typeparam name="T">Generic type parameter.</typeparam>
/// <returns>The core write function.</returns>
private WriteObjectDelegate GetCoreWriteFn<T>()
{
if ((typeof(T).IsValueType() && !JsConfig.TreatAsRefType(typeof(T))) || JsConfig<T>.HasSerializeFn)
{
return JsConfig<T>.HasSerializeFn
? JsConfig<T>.WriteFn<TSerializer>
: GetValueTypeToStringMethod(typeof(T));
}
var specialWriteFn = GetSpecialWriteFn(typeof(T));
if (specialWriteFn != null)
{
return specialWriteFn;
}
if (typeof(T).IsArray)
{
if (typeof(T) == typeof(byte[]))
return (w, x) => WriteLists.WriteBytes(Serializer, w, x);
if (typeof(T) == typeof(string[]))
return (w, x) => WriteLists.WriteStringArray(Serializer, w, x);
if (typeof(T) == typeof(int[]))
return WriteListsOfElements<int, TSerializer>.WriteGenericArrayValueType;
if (typeof(T) == typeof(long[]))
return WriteListsOfElements<long, TSerializer>.WriteGenericArrayValueType;
var elementType = typeof(T).GetElementType();
var writeFn = WriteListsOfElements<TSerializer>.GetGenericWriteArray(elementType);
return writeFn;
}
if (typeof(T).HasGenericType() ||
typeof(T).HasInterface(typeof(IDictionary<string, object>))) // is ExpandoObject?
{
if (typeof(T).IsOrHasGenericInterfaceTypeOf(typeof(IList<>)))
return WriteLists<T, TSerializer>.Write;
var mapInterface = typeof(T).GetTypeWithGenericTypeDefinitionOf(typeof(IDictionary<,>));
if (mapInterface != null)
{
var mapTypeArgs = mapInterface.GenericTypeArguments();
var writeFn = WriteDictionary<TSerializer>.GetWriteGenericDictionary(
mapTypeArgs[0], mapTypeArgs[1]);
var keyWriteFn = Serializer.GetWriteFn(mapTypeArgs[0]);
var valueWriteFn = typeof(T) == typeof(JsonObject)
? JsonObject.WriteValue
: Serializer.GetWriteFn(mapTypeArgs[1]);
return (w, x) => writeFn(w, x, keyWriteFn, valueWriteFn);
}
}
var enumerableInterface = typeof(T).GetTypeWithGenericTypeDefinitionOf(typeof(IEnumerable<>));
if (enumerableInterface != null)
{
var elementType = enumerableInterface.GenericTypeArguments()[0];
var writeFn = WriteListsOfElements<TSerializer>.GetGenericWriteEnumerable(elementType);
return writeFn;
}
var isDictionary = typeof(T) != typeof(IEnumerable) && typeof(T) != typeof(ICollection)
&& (typeof(T).AssignableFrom(typeof(IDictionary)) || typeof(T).HasInterface(typeof(IDictionary)));
if (isDictionary)
{
return WriteDictionary<TSerializer>.WriteIDictionary;
}
var isEnumerable = typeof(T).AssignableFrom(typeof(IEnumerable))
|| typeof(T).HasInterface(typeof(IEnumerable));
if (isEnumerable)
{
return WriteListsOfElements<TSerializer>.WriteIEnumerable;
}
if (typeof(T).IsClass() || typeof(T).IsInterface() || JsConfig.TreatAsRefType(typeof(T)))
{
var typeToStringMethod = WriteType<T, TSerializer>.Write;
if (typeToStringMethod != null)
{
return typeToStringMethod;
}
}
return Serializer.WriteBuiltIn;
}
/// <summary>List of types of the specials.</summary>
public Dictionary<Type, WriteObjectDelegate> SpecialTypes;
/// <summary>Gets special write function.</summary>
/// <param name="type">The type.</param>
/// <returns>The special write function.</returns>
public WriteObjectDelegate GetSpecialWriteFn(Type type)
{
WriteObjectDelegate writeFn = null;
if (SpecialTypes.TryGetValue(type, out writeFn))
return writeFn;
if (type.InstanceOfType(typeof(Type)))
return WriteType;
if (type.IsInstanceOf(typeof(Exception)))
return Serializer.WriteException;
return null;
}
/// <summary>Writes a type.</summary>
/// <param name="writer">The writer.</param>
/// <param name="value"> The value.</param>
public void WriteType(TextWriter writer, object value)
{
Serializer.WriteRawString(writer, JsConfig.TypeWriter((Type)value));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Orleans.AzureUtils;
using Microsoft.WindowsAzure.Storage.Table;
namespace Orleans.Runtime.ReminderService
{
internal class ReminderTableEntry : TableEntity
{
public string GrainReference { get; set; } // Part of RowKey
public string ReminderName { get; set; } // Part of RowKey
public string ServiceId { get; set; } // Part of PartitionKey
public string DeploymentId { get; set; }
public string StartAt { get; set; }
public string Period { get; set; }
public string GrainRefConsistentHash { get; set; } // Part of PartitionKey
public static string ConstructRowKey(GrainReference grainRef, string reminderName)
{
var key = String.Format("{0}-{1}", grainRef.ToKeyString(), reminderName); //grainRef.ToString(), reminderName);
return AzureStorageUtils.SanitizeTableProperty(key);
}
public static string ConstructPartitionKey(Guid serviceId, GrainReference grainRef)
{
return ConstructPartitionKey(serviceId, grainRef.GetUniformHashCode());
}
public static string ConstructPartitionKey(Guid serviceId, uint number)
{
// IMPORTANT NOTE: Other code using this return data is very sensitive to format changes,
// so take great care when making any changes here!!!
// this format of partition key makes sure that the comparisons in FindReminderEntries(begin, end) work correctly
// the idea is that when converting to string, negative numbers start with 0, and positive start with 1. Now,
// when comparisons will be done on strings, this will ensure that positive numbers are always greater than negative
// string grainHash = number < 0 ? string.Format("0{0}", number.ToString("X")) : string.Format("1{0:d16}", number);
var grainHash = String.Format("{0:X8}", number);
return String.Format("{0}_{1}", ConstructServiceIdStr(serviceId), grainHash);
}
public static string ConstructServiceIdStr(Guid serviceId)
{
return serviceId.ToString();
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("Reminder [");
sb.Append(" PartitionKey=").Append(PartitionKey);
sb.Append(" RowKey=").Append(RowKey);
sb.Append(" GrainReference=").Append(GrainReference);
sb.Append(" ReminderName=").Append(ReminderName);
sb.Append(" Deployment=").Append(DeploymentId);
sb.Append(" ServiceId=").Append(ServiceId);
sb.Append(" StartAt=").Append(StartAt);
sb.Append(" Period=").Append(Period);
sb.Append(" GrainRefConsistentHash=").Append(GrainRefConsistentHash);
sb.Append("]");
return sb.ToString();
}
}
internal class RemindersTableManager : AzureTableDataManager<ReminderTableEntry>
{
private const string REMINDERS_TABLE_NAME = "OrleansReminders";
public Guid ServiceId { get; private set; }
public string DeploymentId { get; private set; }
private static readonly TimeSpan initTimeout = AzureTableDefaultPolicies.TableCreationTimeout;
public static async Task<RemindersTableManager> GetManager(Guid serviceId, string deploymentId, string storageConnectionString)
{
var singleton = new RemindersTableManager(serviceId, deploymentId, storageConnectionString);
try
{
singleton.Logger.Info("Creating RemindersTableManager for service id {0} and deploymentId {1}.", serviceId, deploymentId);
await singleton.InitTableAsync()
.WithTimeout(initTimeout);
}
catch (TimeoutException te)
{
string errorMsg = $"Unable to create or connect to the Azure table in {initTimeout}";
singleton.Logger.Error(ErrorCode.AzureTable_38, errorMsg, te);
throw new OrleansException(errorMsg, te);
}
catch (Exception ex)
{
string errorMsg = $"Exception trying to create or connect to the Azure table: {ex.Message}";
singleton.Logger.Error(ErrorCode.AzureTable_39, errorMsg, ex);
throw new OrleansException(errorMsg, ex);
}
return singleton;
}
private RemindersTableManager(Guid serviceId, string deploymentId, string storageConnectionString)
: base(REMINDERS_TABLE_NAME, storageConnectionString)
{
DeploymentId = deploymentId;
ServiceId = serviceId;
}
internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(uint begin, uint end)
{
string sBegin = ReminderTableEntry.ConstructPartitionKey(ServiceId, begin);
string sEnd = ReminderTableEntry.ConstructPartitionKey(ServiceId, end);
string serviceIdStr = ReminderTableEntry.ConstructServiceIdStr(ServiceId);
if (begin < end)
{
Expression<Func<ReminderTableEntry, bool>> query =
e => String.Compare(e.PartitionKey, serviceIdStr + '_') > 0
&& String.Compare(e.PartitionKey, serviceIdStr + (char)('_' + 1)) <= 0
&& String.Compare(e.PartitionKey, sBegin) > 0
&& String.Compare(e.PartitionKey, sEnd) <= 0;
var queryResults = await ReadTableEntriesAndEtagsAsync(query);
return queryResults.ToList();
}
if (begin == end)
{
Expression<Func<ReminderTableEntry, bool>> query =
e => String.Compare(e.PartitionKey, serviceIdStr + '_') > 0
&& String.Compare(e.PartitionKey, serviceIdStr + (char)('_' + 1)) <= 0;
var queryResults = await ReadTableEntriesAndEtagsAsync(query);
return queryResults.ToList();
}
// (begin > end)
Expression<Func<ReminderTableEntry, bool>> p1Query =
e => String.Compare(e.PartitionKey, serviceIdStr + '_') > 0
&& String.Compare(e.PartitionKey, serviceIdStr + (char)('_' + 1)) <= 0
&& String.Compare(e.PartitionKey, sBegin) > 0;
Expression<Func<ReminderTableEntry, bool>> p2Query =
e => String.Compare(e.PartitionKey, serviceIdStr + '_') > 0
&& String.Compare(e.PartitionKey, serviceIdStr + (char)('_' + 1)) <= 0
&& String.Compare(e.PartitionKey, sEnd) <= 0;
var p1 = ReadTableEntriesAndEtagsAsync(p1Query);
var p2 = ReadTableEntriesAndEtagsAsync(p2Query);
IEnumerable<Tuple<ReminderTableEntry, string>>[] arr = await Task.WhenAll(p1, p2);
return arr[0].Concat(arr[1]).ToList();
}
internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(GrainReference grainRef)
{
var partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef);
Expression<Func<ReminderTableEntry, bool>> query =
e => e.PartitionKey == partitionKey
&& String.Compare(e.RowKey, grainRef.ToKeyString() + '-') > 0
&& String.Compare(e.RowKey, grainRef.ToKeyString() + (char)('-' + 1)) <= 0;
var queryResults = await ReadTableEntriesAndEtagsAsync(query);
return queryResults.ToList();
}
internal async Task<Tuple<ReminderTableEntry, string>> FindReminderEntry(GrainReference grainRef, string reminderName)
{
string partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef);
string rowKey = ReminderTableEntry.ConstructRowKey(grainRef, reminderName);
return await ReadSingleTableEntryAsync(partitionKey, rowKey);
}
private Task<List<Tuple<ReminderTableEntry, string>>> FindAllReminderEntries()
{
return FindReminderEntries(0, 0);
}
internal async Task<string> UpsertRow(ReminderTableEntry reminderEntry)
{
try
{
return await UpsertTableEntryAsync(reminderEntry);
}
catch(Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus))
{
if (Logger.IsVerbose2) Logger.Verbose2("UpsertRow failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return null; // false;
}
throw;
}
}
internal async Task<bool> DeleteReminderEntryConditionally(ReminderTableEntry reminderEntry, string eTag)
{
try
{
await DeleteTableEntryAsync(reminderEntry, eTag);
return true;
}catch(Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus))
{
if (Logger.IsVerbose2) Logger.Verbose2("DeleteReminderEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false;
}
throw;
}
}
#region Table operations
internal async Task DeleteTableEntries()
{
if (ServiceId.Equals(Guid.Empty) && DeploymentId == null)
{
await DeleteTableAsync();
}
else
{
List<Tuple<ReminderTableEntry, string>> entries = await FindAllReminderEntries();
// return manager.DeleteTableEntries(entries); // this doesnt work as entries can be across partitions, which is not allowed
// group by grain hashcode so each query goes to different partition
var tasks = new List<Task>();
var groupedByHash = entries
.Where(tuple => tuple.Item1.ServiceId.Equals(ReminderTableEntry.ConstructServiceIdStr(ServiceId)))
.Where(tuple => tuple.Item1.DeploymentId.Equals(DeploymentId)) // delete only entries that belong to our DeploymentId.
.GroupBy(x => x.Item1.GrainRefConsistentHash).ToDictionary(g => g.Key, g => g.ToList());
foreach (var entriesPerPartition in groupedByHash.Values)
{
foreach (var batch in entriesPerPartition.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS))
{
tasks.Add(DeleteTableEntriesAsync(batch));
}
}
await Task.WhenAll(tasks);
}
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Collections;
namespace MathLanguage {
public class Token {
public int kind; // token kind
public int pos; // token position in bytes in the source text (starting at 0)
public int charPos; // token position in characters in the source text (starting at 0)
public int col; // token column (starting at 1)
public int line; // token line (starting at 1)
public string val; // token value
public Token next; // ML 2005-03-11 Tokens are kept in linked list
}
//-----------------------------------------------------------------------------------
// Buffer
//-----------------------------------------------------------------------------------
public class Buffer {
// This Buffer supports the following cases:
// 1) seekable stream (file)
// a) whole stream in buffer
// b) part of stream in buffer
// 2) non seekable stream (network, console)
public const int EOF = char.MaxValue + 1;
const int MIN_BUFFER_LENGTH = 1024; // 1KB
const int MAX_BUFFER_LENGTH = MIN_BUFFER_LENGTH * 64; // 64KB
byte[] buf; // input buffer
int bufStart; // position of first byte in buffer relative to input stream
int bufLen; // length of buffer
int fileLen; // length of input stream (may change if the stream is no file)
int bufPos; // current position in buffer
Stream stream; // input stream (seekable)
bool isUserStream; // was the stream opened by the user?
public Buffer (Stream s, bool isUserStream) {
stream = s; this.isUserStream = isUserStream;
if (stream.CanSeek) {
fileLen = (int) stream.Length;
bufLen = Math.Min(fileLen, MAX_BUFFER_LENGTH);
bufStart = Int32.MaxValue; // nothing in the buffer so far
} else {
fileLen = bufLen = bufStart = 0;
}
buf = new byte[(bufLen>0) ? bufLen : MIN_BUFFER_LENGTH];
if (fileLen > 0) Pos = 0; // setup buffer to position 0 (start)
else bufPos = 0; // index 0 is already after the file, thus Pos = 0 is invalid
if (bufLen == fileLen && stream.CanSeek) Close();
}
protected Buffer(Buffer b) { // called in UTF8Buffer constructor
buf = b.buf;
bufStart = b.bufStart;
bufLen = b.bufLen;
fileLen = b.fileLen;
bufPos = b.bufPos;
stream = b.stream;
// keep destructor from closing the stream
b.stream = null;
isUserStream = b.isUserStream;
}
~Buffer() { Close(); }
protected void Close() {
if (!isUserStream && stream != null) {
stream.Close();
stream = null;
}
}
public virtual int Read () {
if (bufPos < bufLen) {
return buf[bufPos++];
} else if (Pos < fileLen) {
Pos = Pos; // shift buffer start to Pos
return buf[bufPos++];
} else if (stream != null && !stream.CanSeek && ReadNextStreamChunk() > 0) {
return buf[bufPos++];
} else {
return EOF;
}
}
public int Peek () {
int curPos = Pos;
int ch = Read();
Pos = curPos;
return ch;
}
// beg .. begin, zero-based, inclusive, in byte
// end .. end, zero-based, exclusive, in byte
public string GetString (int beg, int end) {
int len = 0;
char[] buf = new char[end - beg];
int oldPos = Pos;
Pos = beg;
while (Pos < end) buf[len++] = (char) Read();
Pos = oldPos;
return new String(buf, 0, len);
}
public int Pos {
get { return bufPos + bufStart; }
set {
if (value >= fileLen && stream != null && !stream.CanSeek) {
// Wanted position is after buffer and the stream
// is not seek-able e.g. network or console,
// thus we have to read the stream manually till
// the wanted position is in sight.
while (value >= fileLen && ReadNextStreamChunk() > 0);
}
if (value < 0 || value > fileLen) {
throw new FatalError("buffer out of bounds access, position: " + value);
}
if (value >= bufStart && value < bufStart + bufLen) { // already in buffer
bufPos = value - bufStart;
} else if (stream != null) { // must be swapped in
stream.Seek(value, SeekOrigin.Begin);
bufLen = stream.Read(buf, 0, buf.Length);
bufStart = value; bufPos = 0;
} else {
// set the position to the end of the file, Pos will return fileLen.
bufPos = fileLen - bufStart;
}
}
}
// Read the next chunk of bytes from the stream, increases the buffer
// if needed and updates the fields fileLen and bufLen.
// Returns the number of bytes read.
private int ReadNextStreamChunk() {
int free = buf.Length - bufLen;
if (free == 0) {
// in the case of a growing input stream
// we can neither seek in the stream, nor can we
// foresee the maximum length, thus we must adapt
// the buffer size on demand.
byte[] newBuf = new byte[bufLen * 2];
Array.Copy(buf, newBuf, bufLen);
buf = newBuf;
free = bufLen;
}
int read = stream.Read(buf, bufLen, free);
if (read > 0) {
fileLen = bufLen = (bufLen + read);
return read;
}
// end of stream reached
return 0;
}
}
//-----------------------------------------------------------------------------------
// UTF8Buffer
//-----------------------------------------------------------------------------------
public class UTF8Buffer: Buffer {
public UTF8Buffer(Buffer b): base(b) {}
public override int Read() {
int ch;
do {
ch = base.Read();
// until we find a utf8 start (0xxxxxxx or 11xxxxxx)
} while ((ch >= 128) && ((ch & 0xC0) != 0xC0) && (ch != EOF));
if (ch < 128 || ch == EOF) {
// nothing to do, first 127 chars are the same in ascii and utf8
// 0xxxxxxx or end of file character
} else if ((ch & 0xF0) == 0xF0) {
// 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x07; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F; ch = base.Read();
int c4 = ch & 0x3F;
ch = (((((c1 << 6) | c2) << 6) | c3) << 6) | c4;
} else if ((ch & 0xE0) == 0xE0) {
// 1110xxxx 10xxxxxx 10xxxxxx
int c1 = ch & 0x0F; ch = base.Read();
int c2 = ch & 0x3F; ch = base.Read();
int c3 = ch & 0x3F;
ch = (((c1 << 6) | c2) << 6) | c3;
} else if ((ch & 0xC0) == 0xC0) {
// 110xxxxx 10xxxxxx
int c1 = ch & 0x1F; ch = base.Read();
int c2 = ch & 0x3F;
ch = (c1 << 6) | c2;
}
return ch;
}
}
//-----------------------------------------------------------------------------------
// Scanner
//-----------------------------------------------------------------------------------
public class Scanner {
const char EOL = '\n';
const int eofSym = 0; /* pdt */
const int maxT = 20;
const int noSym = 20;
public Buffer buffer; // scanner buffer
public bool IsSpaceSignificant{ // whether a whitespace becomes a token by itself
get; set;
}
Token t; // current token
int ch; // current input character
int pos; // byte position of current character
int charPos; // position by unicode characters starting with 0
int col; // column number of current character
int line; // line number of current character
int oldEols; // EOLs that appeared in a comment;
static readonly Hashtable start; // maps first token character to start state
Token tokens; // list of tokens already peeked (first token is a dummy)
Token pt; // current peek token
char[] tval = new char[128]; // text of current token
int tlen; // length of current token
static Scanner() {
start = new Hashtable(128);
for (int i = 32; i <= 32; ++i) start[i] = 6;
for (int i = 10; i <= 10; ++i) start[i] = 7;
for (int i = 65; i <= 90; ++i) start[i] = 8;
for (int i = 95; i <= 95; ++i) start[i] = 8;
for (int i = 97; i <= 122; ++i) start[i] = 8;
for (int i = 48; i <= 57; ++i) start[i] = 16;
start[40] = 1;
start[41] = 2;
start[61] = 3;
start[58] = 4;
start[46] = 27;
start[43] = 18;
start[45] = 19;
start[42] = 20;
start[47] = 21;
start[94] = 22;
start[33] = 23;
start[44] = 24;
start[91] = 25;
start[93] = 26;
start[Buffer.EOF] = -1;
}
public Scanner (string fileName) {
try {
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
buffer = new UTF8Buffer(new Buffer(stream, false));
Init();
} catch (IOException) {
throw new FatalError("Cannot open file " + fileName);
}
}
public Scanner (Stream s) {
buffer = new Buffer(s, true);
Init();
}
void Init() {
pos = -1; line = 1; col = 0; charPos = -1;
oldEols = 0;
NextCh();
/*if (ch == 0xEF) { // check optional byte order mark for UTF-8
NextCh(); int ch1 = ch;
NextCh(); int ch2 = ch;
if (ch1 != 0xBB || ch2 != 0xBF) {
throw new FatalError(String.Format("illegal byte order mark: EF {0,2:X} {1,2:X}", ch1, ch2));
}
buffer = new UTF8Buffer(buffer); col = 0; charPos = -1;
NextCh();
}*/
pt = tokens = new Token(); // first token is a dummy
}
void NextCh() {
if (oldEols > 0) { ch = EOL; oldEols--; }
else {
pos = buffer.Pos;
// buffer reads unicode chars, if UTF8 has been detected
ch = buffer.Read(); col++; charPos++;
// replace isolated '\r' by '\n' in order to make
// eol handling uniform across Windows, Unix and Mac
if (ch == '\r' && buffer.Peek() != '\n') ch = EOL;
if (ch == EOL) { line++; col = 0; }
}
}
void AddCh() {
if (tlen >= tval.Length) {
char[] newBuf = new char[2 * tval.Length];
Array.Copy(tval, 0, newBuf, 0, tval.Length);
tval = newBuf;
}
if (ch != Buffer.EOF) {
tval[tlen++] = (char) ch;
NextCh();
}
}
bool Comment0() {
int level = 1, pos0 = pos, line0 = line, col0 = col, charPos0 = charPos;
NextCh();
for(;;) {
if (ch == 10) {
level--;
if (level == 0) { oldEols = line - line0; NextCh(); return true; }
NextCh();
} else if (ch == Buffer.EOF) return false;
else NextCh();
}
}
void CheckLiteral() {
switch (t.val) {
default: break;
}
}
Token NextToken() {
while (!IsSpaceSignificant && ch == ' ' ||
ch == 9 || ch == 13
) NextCh();
if (ch == '#' && Comment0()) return NextToken();
int recKind = noSym;
int recEnd = pos;
t = new Token();
t.pos = pos; t.col = col; t.line = line; t.charPos = charPos;
int state;
if (start.ContainsKey(ch)) { state = (int) start[ch]; }
else { state = 0; }
tlen = 0; AddCh();
switch (state) {
case -1: { t.kind = eofSym; break; } // NextCh already done
case 0: {
if (recKind != noSym) {
tlen = recEnd - t.pos;
SetScannerBehindT();
}
t.kind = recKind; break;
} // NextCh already done
case 1:
{t.kind = 1; break;}
case 2:
{t.kind = 2; break;}
case 3:
{t.kind = 3; break;}
case 4:
if (ch == '=') {AddCh(); goto case 5;}
else {goto case 0;}
case 5:
{t.kind = 4; break;}
case 6:
{t.kind = 5; break;}
case 7:
{t.kind = 6; break;}
case 8:
recEnd = pos; recKind = 7;
if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'Z' || ch == '_' || ch >= 'a' && ch <= 'z') {AddCh(); goto case 8;}
else {t.kind = 7; break;}
case 9:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 11;}
else if (ch == '+' || ch == '-') {AddCh(); goto case 10;}
else {goto case 0;}
case 10:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 11;}
else {goto case 0;}
case 11:
recEnd = pos; recKind = 9;
if (ch >= '0' && ch <= '9' || ch == '_') {AddCh(); goto case 11;}
else {t.kind = 9; break;}
case 12:
recEnd = pos; recKind = 9;
if (ch >= '0' && ch <= '9' || ch == '_') {AddCh(); goto case 12;}
else if (ch == 'E' || ch == 'e') {AddCh(); goto case 13;}
else {t.kind = 9; break;}
case 13:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 15;}
else if (ch == '+' || ch == '-') {AddCh(); goto case 14;}
else {goto case 0;}
case 14:
if (ch >= '0' && ch <= '9') {AddCh(); goto case 15;}
else {goto case 0;}
case 15:
recEnd = pos; recKind = 9;
if (ch >= '0' && ch <= '9' || ch == '_') {AddCh(); goto case 15;}
else {t.kind = 9; break;}
case 16:
recEnd = pos; recKind = 8;
if (ch >= '0' && ch <= '9' || ch == '_') {AddCh(); goto case 16;}
else if (ch == '.') {AddCh(); goto case 17;}
else {t.kind = 8; break;}
case 17:
recEnd = pos; recKind = 9;
if (ch >= '0' && ch <= '9') {AddCh(); goto case 12;}
else if (ch == 'E' || ch == 'e') {AddCh(); goto case 9;}
else {t.kind = 9; break;}
case 18:
{t.kind = 10; break;}
case 19:
{t.kind = 11; break;}
case 20:
{t.kind = 12; break;}
case 21:
{t.kind = 13; break;}
case 22:
{t.kind = 15; break;}
case 23:
{t.kind = 16; break;}
case 24:
{t.kind = 17; break;}
case 25:
{t.kind = 18; break;}
case 26:
{t.kind = 19; break;}
case 27:
recEnd = pos; recKind = 14;
if (ch >= '0' && ch <= '9') {AddCh(); goto case 12;}
else {t.kind = 14; break;}
}
t.val = new String(tval, 0, tlen);
return t;
}
private void SetScannerBehindT() {
buffer.Pos = t.pos;
NextCh();
line = t.line; col = t.col; charPos = t.charPos;
for (int i = 0; i < tlen; i++) NextCh();
}
// get the next token (possibly a token already seen during peeking)
public Token Scan () {
if (tokens.next == null) {
return NextToken();
} else {
pt = tokens = tokens.next;
return tokens;
}
}
// peek for the next token, ignore pragmas
public Token Peek () {
do {
if (pt.next == null) {
pt.next = NextToken();
}
pt = pt.next;
} while (pt.kind > maxT); // skip pragmas
return pt;
}
// make sure that peeking starts at the current scan position
public void ResetPeek () { pt = tokens; }
} // end Scanner
}
| |
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace Python.Runtime.Platform
{
interface ILibraryLoader
{
IntPtr Load(string dllToLoad);
IntPtr GetFunction(IntPtr hModule, string procedureName);
void Free(IntPtr hModule);
}
static class LibraryLoader
{
public static ILibraryLoader Get(OperatingSystemType os)
{
switch (os)
{
case OperatingSystemType.Windows:
return new WindowsLoader();
case OperatingSystemType.Darwin:
return new DarwinLoader();
case OperatingSystemType.Linux:
return new LinuxLoader();
default:
throw new PlatformNotSupportedException($"This operating system ({os}) is not supported");
}
}
}
class LinuxLoader : ILibraryLoader
{
private static int RTLD_NOW = 0x2;
private static int RTLD_GLOBAL = 0x100;
private static IntPtr RTLD_DEFAULT = IntPtr.Zero;
private const string NativeDll = "libdl.so";
public IntPtr Load(string dllToLoad)
{
var filename = $"lib{dllToLoad}.so";
ClearError();
var res = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
if (res == IntPtr.Zero)
{
var err = GetError();
throw new DllNotFoundException($"Could not load {filename} with flags RTLD_NOW | RTLD_GLOBAL: {err}");
}
return res;
}
public void Free(IntPtr handle)
{
dlclose(handle);
}
public IntPtr GetFunction(IntPtr dllHandle, string name)
{
// look in the exe if dllHandle is NULL
if (dllHandle == IntPtr.Zero)
{
dllHandle = RTLD_DEFAULT;
}
ClearError();
IntPtr res = dlsym(dllHandle, name);
if (res == IntPtr.Zero)
{
var err = GetError();
throw new MissingMethodException($"Failed to load symbol {name}: {err}");
}
return res;
}
void ClearError()
{
dlerror();
}
string GetError()
{
var res = dlerror();
if (res != IntPtr.Zero)
return Marshal.PtrToStringAnsi(res);
else
return null;
}
[DllImport(NativeDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr dlopen(string fileName, int flags);
[DllImport(NativeDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern IntPtr dlsym(IntPtr handle, string symbol);
[DllImport(NativeDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int dlclose(IntPtr handle);
[DllImport(NativeDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr dlerror();
}
class DarwinLoader : ILibraryLoader
{
private static int RTLD_NOW = 0x2;
private static int RTLD_GLOBAL = 0x8;
private const string NativeDll = "/usr/lib/libSystem.dylib";
private static IntPtr RTLD_DEFAULT = new IntPtr(-2);
public IntPtr Load(string dllToLoad)
{
var filename = $"lib{dllToLoad}.dylib";
ClearError();
var res = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
if (res == IntPtr.Zero)
{
var err = GetError();
throw new DllNotFoundException($"Could not load {filename} with flags RTLD_NOW | RTLD_GLOBAL: {err}");
}
return res;
}
public void Free(IntPtr handle)
{
dlclose(handle);
}
public IntPtr GetFunction(IntPtr dllHandle, string name)
{
// look in the exe if dllHandle is NULL
if (dllHandle == IntPtr.Zero)
{
dllHandle = RTLD_DEFAULT;
}
ClearError();
IntPtr res = dlsym(dllHandle, name);
if (res == IntPtr.Zero)
{
var err = GetError();
throw new MissingMethodException($"Failed to load symbol {name}: {err}");
}
return res;
}
void ClearError()
{
dlerror();
}
string GetError()
{
var res = dlerror();
if (res != IntPtr.Zero)
return Marshal.PtrToStringAnsi(res);
else
return null;
}
[DllImport(NativeDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern IntPtr dlopen(String fileName, int flags);
[DllImport(NativeDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern IntPtr dlsym(IntPtr handle, String symbol);
[DllImport(NativeDll, CallingConvention = CallingConvention.Cdecl)]
private static extern int dlclose(IntPtr handle);
[DllImport(NativeDll, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr dlerror();
}
class WindowsLoader : ILibraryLoader
{
private const string NativeDll = "kernel32.dll";
public IntPtr Load(string dllToLoad)
{
var res = WindowsLoader.LoadLibrary(dllToLoad);
if (res == IntPtr.Zero)
throw new DllNotFoundException($"Could not load {dllToLoad}", new Win32Exception());
return res;
}
public IntPtr GetFunction(IntPtr hModule, string procedureName)
{
var res = WindowsLoader.GetProcAddress(hModule, procedureName);
if (res == IntPtr.Zero)
throw new MissingMethodException($"Failed to load symbol {procedureName}", new Win32Exception());
return res;
}
public void Free(IntPtr hModule) => WindowsLoader.FreeLibrary(hModule);
[DllImport(NativeDll, SetLastError = true)]
static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport(NativeDll, SetLastError = true)]
static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport(NativeDll)]
static extern bool FreeLibrary(IntPtr hModule);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
namespace System
{
/// <summary>
/// ReadOnlySpan represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
[IsReadOnly]
[IsByRefLike]
[NonVersionable]
public struct ReadOnlySpan<T>
{
/// <summary>A byref or a native ptr.</summary>
private readonly ByReference<T> _pointer;
/// <summary>The number of elements this ReadOnlySpan contains.</summary>
#if PROJECTN
[Bound]
#endif
private readonly int _length;
/// <summary>
/// Creates a new read-only span over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
_pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()));
_length = array.Length;
}
/// <summary>
/// Creates a new read-only span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the read-only span.</param>
/// <param name="length">The number of items in the read-only span.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start));
_length = length;
}
/// <summary>
/// Creates a new read-only span over the target unmanaged buffer. Clearly this
/// is quite dangerous, because we are creating arbitrarily typed T's
/// out of a void*-typed block of memory. And the length is not checked.
/// But if this creation is correct, then all subsequent uses are correct.
/// </summary>
/// <param name="pointer">An unmanaged pointer to memory.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe ReadOnlySpan(void* pointer, int length)
{
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
_pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer));
_length = length;
}
/// <summary>
/// Create a new read-only span over a portion of a regular managed object. This can be useful
/// if part of a managed object represents a "fixed array." This is dangerous because neither the
/// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that
/// "rawPointer" actually lies within <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length) => new ReadOnlySpan<T>(ref objectData, length);
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlySpan(ref T ptr, int length)
{
Debug.Assert(length >= 0);
_pointer = new ByReference<T>(ref ptr);
_length = length;
}
//Debugger Display = {T[length]}
private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length);
/// <summary>
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[EditorBrowsable(EditorBrowsableState.Never)]
public ref T DangerousGetPinnableReference()
{
return ref _pointer.Value;
}
/// <summary>
/// The number of items in the read-only span.
/// </summary>
public int Length
{
[NonVersionable]
get
{
return _length;
}
}
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty
{
[NonVersionable]
get
{
return _length == 0;
}
}
/// <summary>
/// Returns the specified element of the read-only span.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
public T this[int index]
{
#if PROJECTN
[BoundsChecking]
get
{
return Unsafe.Add(ref _pointer.Value, index);
}
#else
#if CORERT
[Intrinsic]
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[NonVersionable]
get
{
if ((uint)index >= (uint)_length)
ThrowHelper.ThrowIndexOutOfRangeException();
return Unsafe.Add(ref _pointer.Value, index);
}
#endif
}
/// <summary>
/// Copies the contents of this read-only span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The span to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination Span is shorter than the source Span.
/// </exception>
/// </summary>
public void CopyTo(Span<T> destination)
{
if (!TryCopyTo(destination))
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
/// Copies the contents of this read-only span into destination span. If the source
/// and destinations overlap, this method behaves as if the original values in
/// a temporary location before the destination is overwritten.
/// </summary>
/// <returns>If the destination span is shorter than the source span, this method
/// return false and no data is written to the destination.</returns>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Span<T> destination)
{
if ((uint)_length > (uint)destination.Length)
return false;
Span.CopyTo<T>(ref destination.DangerousGetPinnableReference(), ref _pointer.Value, _length);
return true;
}
/// <summary>
/// Returns true if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right)
{
return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value);
}
/// <summary>
/// Returns false if left and right point at the same memory and have the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public static bool operator !=(ReadOnlySpan<T> left, ReadOnlySpan<T> right) => !(left == right);
/// <summary>
/// This method is not supported as spans cannot be boxed. To compare two spans, use operator==.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("Equals() on Span will always throw an exception. Use == instead.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan);
}
/// <summary>
/// This method is not supported as spans cannot be boxed.
/// <exception cref="System.NotSupportedException">
/// Always thrown by this method.
/// </exception>
/// </summary>
[Obsolete("GetHashCode() on Span will always throw an exception.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan);
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(T[] array) => new ReadOnlySpan<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlySpan{T}"/>
/// </summary>
public static implicit operator ReadOnlySpan<T>(ArraySegment<T> arraySegment) => new ReadOnlySpan<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Forms a slice out of the given read-only span, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start);
}
/// <summary>
/// Forms a slice out of the given read-only span, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), length);
}
/// <summary>
/// Copies the contents of this read-only span into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray()
{
if (_length == 0)
return Array.Empty<T>();
var destination = new T[_length];
Span.CopyTo<T>(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, _length);
return destination;
}
/// <summary>
/// Returns a 0-length read-only span whose base is the null pointer.
/// </summary>
public static ReadOnlySpan<T> Empty => default(ReadOnlySpan<T>);
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using com.calitha.goldparser.lalr;
using com.calitha.commons;
using com.calitha.goldparser;
namespace EpiMenu.CommandPlugin
{
[Serializable()]
public class SymbolException : System.Exception
{
public SymbolException(string message) : base(message)
{
}
public SymbolException(string message,
Exception inner) : base(message, inner)
{
}
protected SymbolException(SerializationInfo info,
StreamingContext context) : base(info, context)
{
}
}
[Serializable()]
public class RuleException : System.Exception
{
public RuleException(string message) : base(message)
{
}
public RuleException(string message,
Exception inner) : base(message, inner)
{
}
protected RuleException(SerializationInfo info,
StreamingContext context) : base(info, context)
{
}
}
public class EpiMenuInterpreterParser
{
private LALRParser parser;
//private IEnterCheckCode EnterCheckCodeInterface = null;
//private IAnalysisCheckCode AnalysisCheckCodeInterface = null;
private Rule_Context.eRunMode RunMode = Rule_Context.eRunMode.Enter;
private Rule_Context mContext;
public Rule ProgramStart = null;
private string commandText = String.Empty;
private Stack<Token> tokenStack = new Stack<Token>();
public Rule_Context Context
{
get { return mContext; }
}
public EpiMenuInterpreterParser(string filename)
{
FileStream stream = new FileStream(filename,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
Init(stream);
stream.Close();
}
/*
public EpiMenuInterpreterParser(string filename, IEnterCheckCode pEnterCheckCodeInterface, Rule_Context.eRunMode pRunMode)
{
this.EnterCheckCodeInterface = pEnterCheckCodeInterface;
this.RunMode = pRunMode;
FileStream stream = new FileStream(filename,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
Init(stream);
stream.Close();
}
public EpiMenuInterpreterParser(string filename, IAnalysisCheckCode pAnalysisCheckCodeInterface, Rule_Context.eRunMode pRunMode)
{
this.AnalysisCheckCodeInterface = pAnalysisCheckCodeInterface;
this.RunMode = pRunMode;
FileStream stream = new FileStream(filename,
FileMode.Open,
FileAccess.Read,
FileShare.Read);
Init(stream);
stream.Close();
}
*/
public EpiMenuInterpreterParser(string baseName, string resourceName)
{
byte[] buffer = ResourceUtil.GetByteArrayResource(
System.Reflection.Assembly.GetExecutingAssembly(),
baseName,
resourceName);
MemoryStream stream = new MemoryStream(buffer);
Init(stream);
stream.Close();
}
public EpiMenuInterpreterParser(Stream stream)
{
Init(stream);
}
private void Init(Stream stream)
{
CGTReader reader = new CGTReader(stream);
parser = reader.CreateNewParser();
parser.TrimReductions = false;
parser.StoreTokens = LALRParser.StoreTokensMode.NoUserObject;
parser.OnReduce += new LALRParser.ReduceHandler(ReduceEvent);
parser.OnTokenRead += new LALRParser.TokenReadHandler(TokenReadEvent);
parser.OnAccept += new LALRParser.AcceptHandler(AcceptEvent);
parser.OnTokenError += new LALRParser.TokenErrorHandler(TokenErrorEvent);
parser.OnParseError += new LALRParser.ParseErrorHandler(ParseErrorEvent);
mContext = new Rule_Context();
}
/*
public EpiMenuInterpreterParser(Stream stream, IEnterCheckCode pEnterCheckCodeInterface, Rule_Context.eRunMode pRunMode)
{
Init(stream);
this.EnterCheckCodeInterface = pEnterCheckCodeInterface;
this.RunMode = pRunMode;
}
public EpiMenuInterpreterParser(Stream stream, IAnalysisCheckCode pAnalysisCheckCodeInterface, Rule_Context.eRunMode pRunMode)
{
Init(stream);
this.AnalysisCheckCodeInterface = pAnalysisCheckCodeInterface;
this.RunMode = pRunMode;
}*/
public void Parse(string source)
{
try
{
this.commandText = source;
parser.Parse(source);
}
catch(InvalidOperationException ex)
{
if (!ex.Message.ToUpperInvariant().Contains("STACK EMPTY"))
{
throw ex;
}
}
}
private void TokenReadEvent(LALRParser parser, TokenReadEventArgs args)
{
try
{
args.Token.UserObject = CreateObject(args.Token);
}
catch (ApplicationException ex)
{
args.Continue = false;
tokenStack.Clear();
//Logger.Log(DateTime.Now + ": " + ex.Message);
throw ex;
}
}
private Object CreateObject(TerminalToken token)
{
return null;
}
private void ReduceEvent(LALRParser parser, ReduceEventArgs args)
{
try
{
args.Token.UserObject = CreateObject(args.Token);
}
catch (ApplicationException ex)
{
args.Continue = false;
//Logger.Log(DateTime.Now + ": " + ex.Message);
//todo: Report message to UI?
}
}
public static Object CreateObject(NonterminalToken token)
{
return null;
}
private void AcceptEvent(LALRParser parser, AcceptEventArgs args)
{
//System.Console.WriteLine("AcceptEvent ");
NonterminalToken T = (NonterminalToken)args.Token;
/*
try
{
Configuration.Load(Configuration.DefaultConfigurationPath);
this.Context.module = new MemoryRegion();
}
catch (System.Exception ex)
{
Configuration.CreateDefaultConfiguration();
Configuration.Load(Configuration.DefaultConfigurationPath);
this.Context.module = new MemoryRegion();
}*/
if (this.RunMode == Rule_Context.eRunMode.Enter)
{
//mContext.EnterCheckCodeInterface = this.EnterCheckCodeInterface;
mContext.RunMode = Rule_Context.eRunMode.Enter;
}
else if (this.RunMode == Rule_Context.eRunMode.Analysis)
{
//mContext.AnalysisCheckCodeInterface = this.AnalysisCheckCodeInterface;
mContext.RunMode = Rule_Context.eRunMode.Analysis;
}
this.ProgramStart = new Rule_Statements(mContext, T);
this.ProgramStart.Execute();
}
private void TokenErrorEvent(LALRParser parser, TokenErrorEventArgs args)
{
//throw new TokenException.TokenException(args);
}
private void ParseErrorEvent(LALRParser parser, ParseErrorEventArgs args)
{
//throw new ParseException(args);
}
}
}
| |
// Authors:
// Rafael Mizrahi <rafim@mainsoft.com>
// Erez Lotan <erezl@mainsoft.com>
// Oren Gurfinkel <oreng@mainsoft.com>
// Ofer Borstein
//
// Copyright (c) 2004 Mainsoft Co.
//
// 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 NUnit.Framework;
using System;
using System.Data;
using GHTUtils;
using GHTUtils.Base;
namespace tests.system_data_dll.System_Data
{
[TestFixture] public class DataSet_Merge_DtBM : GHTBase
{
[Test] public void Main()
{
DataSet_Merge_DtBM tc = new DataSet_Merge_DtBM();
Exception exp = null;
try
{
tc.BeginTest("DataSet_Merge_DtBM");
tc.run();
}
catch(Exception ex)
{
exp = ex;
}
finally
{
tc.EndTest(exp);
}
}
//Activate This Construntor to log All To Standard output
//public TestClass():base(true){}
//Activate this constructor to log Failures to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, false){}
//Activate this constructor to log All to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, true){}
//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES
public void run()
{
Exception exp = null;
DataTable dt = GHTUtils.DataProvider.CreateParentDataTable();
dt.TableName = "Table1";
dt.PrimaryKey = new DataColumn[] {dt.Columns[0]};
//create target dataset (copy of source dataset)
DataSet dsTarget = new DataSet();
dsTarget.Tables.Add(dt.Copy());
//add new column (for checking MissingSchemaAction)
DataColumn dc = new DataColumn("NewColumn",typeof(float));
dt.Columns.Add(dc);
//Update row
string OldValue = dt.Select("ParentId=1")[0][1].ToString();
dt.Select("ParentId=1")[0][1] = "NewValue";
//delete rows
dt.Select("ParentId=2")[0].Delete();
//add row
object[] arrAddedRow = new object[] {99,"NewRowValue1","NewRowValue2",new DateTime(0),0.5,true};
dt.Rows.Add(arrAddedRow);
#region "Merge(dt,true,MissingSchemaAction.Ignore )"
DataSet dsTarget1 = dsTarget.Copy();
dsTarget1.Merge(dt,true,MissingSchemaAction.Ignore );
try
{
BeginCase("Merge true,Ignore - Column");
Compare(dsTarget1.Tables["Table1"].Columns.Contains("NewColumn"),false);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge true,Ignore - changed values");
Compare(dsTarget1.Tables["Table1"].Select("ParentId=1")[0][1] , OldValue);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge true,Ignore - added values");
Compare(dsTarget1.Tables["Table1"].Select("ParentId=99")[0].ItemArray , arrAddedRow);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge true,Ignore - deleted row");
Compare(dsTarget1.Tables["Table1"].Select("ParentId=2").Length > 0,true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
#endregion
#region "Merge(dt,false,MissingSchemaAction.Ignore )"
dsTarget1 = dsTarget.Copy();
dsTarget1.Merge(dt,false,MissingSchemaAction.Ignore );
try
{
BeginCase("Merge true,Ignore - Column");
Compare(dsTarget1.Tables["Table1"].Columns.Contains("NewColumn"),false);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge true,Ignore - changed values");
Compare(dsTarget1.Tables["Table1"].Select("ParentId=1")[0][1] , "NewValue");
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge true,Ignore - added values");
Compare(dsTarget1.Tables["Table1"].Select("ParentId=99")[0].ItemArray , arrAddedRow);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge true,Ignore - deleted row");
Compare(dsTarget1.Tables["Table1"].Select("ParentId=2").Length ,0);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
#endregion
#region "Merge(dt,true,MissingSchemaAction.Add )"
dsTarget1 = dsTarget.Copy();
dsTarget1.Merge(dt,true,MissingSchemaAction.Add );
try
{
BeginCase("Merge true,Add - Column");
Compare(dsTarget1.Tables["Table1"].Columns.Contains("NewColumn"),true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge true,Add - changed values");
Compare(dsTarget1.Tables["Table1"].Select("ParentId=1")[0][1] , OldValue);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge true,Add - added values");
Compare(dsTarget1.Tables["Table1"].Select("ParentId=99").Length , 1);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge true,Add - deleted row");
Compare(dsTarget1.Tables["Table1"].Select("ParentId=2").Length > 0,true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
#endregion
#region "Merge(dt,false,MissingSchemaAction.Add )"
dsTarget1 = dsTarget.Copy();
dsTarget1.Merge(dt,false,MissingSchemaAction.Add );
try
{
BeginCase("Merge true,Add - Column");
Compare(dsTarget1.Tables["Table1"].Columns.Contains("NewColumn"),true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge true,Add - changed values");
Compare(dsTarget1.Tables["Table1"].Select("ParentId=1")[0][1] , "NewValue");
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge true,Add - added values");
Compare(dsTarget1.Tables["Table1"].Select("ParentId=99").Length , 1);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge true,Add - deleted row");
Compare(dsTarget1.Tables["Table1"].Select("ParentId=2").Length ,0);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
#endregion
#region "Merge(dt,false/true,MissingSchemaAction.Error )"
// dsTarget1 = dsTarget.Copy();
// Exception expMerge = null;
// try
// {
// BeginCase("Merge true,Error - Column");
// try { dsTarget1.Merge(dt,true,MissingSchemaAction.Error ); }
// catch (Exception e) {expMerge = e;}
// Compare(expMerge.GetType() , typeof(InvalidOperationException) );
// }
// catch(Exception ex) {exp = ex;}
// finally {EndCase(exp); exp = null;}
//
// expMerge = null;
// try
// {
// BeginCase("Merge false,Error - Column");
// try { dsTarget1.Merge(dt,false,MissingSchemaAction.Error ); }
// catch (Exception e) {expMerge = e;}
// Compare(expMerge.GetType() , typeof(InvalidOperationException) );
// }
// catch(Exception ex) {exp = ex;}
// finally {EndCase(exp); exp = null;}
#endregion
}
}
}
| |
//
// MonoTests.System.Xml.XPathNavigatorTests
//
// Authors:
// Jason Diamond <jason@injektilo.org>
// Martin Willemoes Hansen <mwh@sysrq.dk>
//
// (C) 2002 Jason Diamond
// (C) 2003 Martin Willemoes Hansen
//
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using NUnit.Framework;
namespace MonoTests.System.Xml
{
[TestFixture]
public class XPathNavigatorTests : Assertion
{
XmlDocument document;
XPathNavigator navigator;
[SetUp]
public void GetReady ()
{
document = new XmlDocument ();
}
[Test]
public void CreateNavigator ()
{
document.LoadXml ("<foo />");
navigator = document.CreateNavigator ();
AssertNotNull (navigator);
}
[Test]
public void PropertiesOnDocument ()
{
document.LoadXml ("<foo:bar xmlns:foo='#foo' />");
navigator = document.CreateNavigator ();
AssertEquals (XPathNodeType.Root, navigator.NodeType);
AssertEquals (String.Empty, navigator.Name);
AssertEquals (String.Empty, navigator.LocalName);
AssertEquals (String.Empty, navigator.NamespaceURI);
AssertEquals (String.Empty, navigator.Prefix);
Assert (!navigator.HasAttributes);
Assert (navigator.HasChildren);
Assert (!navigator.IsEmptyElement);
}
[Test]
public void PropertiesOnElement ()
{
document.LoadXml ("<foo:bar xmlns:foo='#foo' />");
navigator = document.DocumentElement.CreateNavigator ();
AssertEquals (XPathNodeType.Element, navigator.NodeType);
AssertEquals ("foo:bar", navigator.Name);
AssertEquals ("bar", navigator.LocalName);
AssertEquals ("#foo", navigator.NamespaceURI);
AssertEquals ("foo", navigator.Prefix);
Assert (!navigator.HasAttributes);
Assert (!navigator.HasChildren);
Assert (navigator.IsEmptyElement);
}
[Test]
public void PropertiesOnAttribute ()
{
document.LoadXml ("<foo bar:baz='quux' xmlns:bar='#bar' />");
navigator = document.DocumentElement.GetAttributeNode("baz", "#bar").CreateNavigator ();
AssertEquals (XPathNodeType.Attribute, navigator.NodeType);
AssertEquals ("bar:baz", navigator.Name);
AssertEquals ("baz", navigator.LocalName);
AssertEquals ("#bar", navigator.NamespaceURI);
AssertEquals ("bar", navigator.Prefix);
Assert (!navigator.HasAttributes);
Assert (!navigator.HasChildren);
Assert (!navigator.IsEmptyElement);
}
[Test]
public void PropertiesOnNamespace ()
{
document.LoadXml ("<root xmlns='urn:foo' />");
navigator = document.DocumentElement.Attributes [0].CreateNavigator ();
AssertEquals (XPathNodeType.Namespace, navigator.NodeType);
}
[Test]
public void Navigation ()
{
document.LoadXml ("<foo><bar /><baz /></foo>");
navigator = document.DocumentElement.CreateNavigator ();
AssertEquals ("foo", navigator.Name);
Assert (navigator.MoveToFirstChild ());
AssertEquals ("bar", navigator.Name);
Assert (navigator.MoveToNext ());
AssertEquals ("baz", navigator.Name);
Assert (!navigator.MoveToNext ());
AssertEquals ("baz", navigator.Name);
Assert (navigator.MoveToPrevious ());
AssertEquals ("bar", navigator.Name);
Assert (!navigator.MoveToPrevious ());
Assert (navigator.MoveToParent ());
AssertEquals ("foo", navigator.Name);
navigator.MoveToRoot ();
AssertEquals (XPathNodeType.Root, navigator.NodeType);
Assert (!navigator.MoveToParent ());
AssertEquals (XPathNodeType.Root, navigator.NodeType);
Assert (navigator.MoveToFirstChild ());
AssertEquals ("foo", navigator.Name);
Assert (navigator.MoveToFirst ());
AssertEquals ("foo", navigator.Name);
Assert (navigator.MoveToFirstChild ());
AssertEquals ("bar", navigator.Name);
Assert (navigator.MoveToNext ());
AssertEquals ("baz", navigator.Name);
Assert (navigator.MoveToFirst ());
AssertEquals ("bar", navigator.Name);
}
[Test]
public void MoveToAndIsSamePosition ()
{
XmlDocument document1 = new XmlDocument ();
document1.LoadXml ("<foo><bar /></foo>");
XPathNavigator navigator1a = document1.DocumentElement.CreateNavigator ();
XPathNavigator navigator1b = document1.DocumentElement.CreateNavigator ();
XmlDocument document2 = new XmlDocument ();
document2.LoadXml ("<foo><bar /></foo>");
XPathNavigator navigator2 = document2.DocumentElement.CreateNavigator ();
AssertEquals ("foo", navigator1a.Name);
Assert (navigator1a.MoveToFirstChild ());
AssertEquals ("bar", navigator1a.Name);
Assert (!navigator1b.IsSamePosition (navigator1a));
AssertEquals ("foo", navigator1b.Name);
Assert (navigator1b.MoveTo (navigator1a));
Assert (navigator1b.IsSamePosition (navigator1a));
AssertEquals ("bar", navigator1b.Name);
Assert (!navigator2.IsSamePosition (navigator1a));
AssertEquals ("foo", navigator2.Name);
Assert (!navigator2.MoveTo (navigator1a));
AssertEquals ("foo", navigator2.Name);
}
[Test]
public void AttributeNavigation ()
{
document.LoadXml ("<foo bar='baz' quux='quuux' />");
navigator = document.DocumentElement.CreateNavigator ();
AssertEquals (XPathNodeType.Element, navigator.NodeType);
AssertEquals ("foo", navigator.Name);
Assert (navigator.MoveToFirstAttribute ());
AssertEquals (XPathNodeType.Attribute, navigator.NodeType);
AssertEquals ("bar", navigator.Name);
AssertEquals ("baz", navigator.Value);
Assert (navigator.MoveToNextAttribute ());
AssertEquals (XPathNodeType.Attribute, navigator.NodeType);
AssertEquals ("quux", navigator.Name);
AssertEquals ("quuux", navigator.Value);
}
[Test]
public void ElementAndRootValues()
{
document.LoadXml ("<foo><bar>baz</bar><quux>quuux</quux></foo>");
navigator = document.DocumentElement.CreateNavigator ();
AssertEquals (XPathNodeType.Element, navigator.NodeType);
AssertEquals ("foo", navigator.Name);
//AssertEquals ("bazquuux", navigator.Value);
navigator.MoveToRoot ();
//AssertEquals ("bazquuux", navigator.Value);
}
[Test]
public void DocumentWithXmlDeclaration ()
{
document.LoadXml ("<?xml version=\"1.0\" standalone=\"yes\"?><Root><foo>bar</foo></Root>");
navigator = document.CreateNavigator ();
navigator.MoveToRoot ();
navigator.MoveToFirstChild ();
AssertEquals (XPathNodeType.Element, navigator.NodeType);
AssertEquals ("Root", navigator.Name);
}
[Test]
public void DocumentWithProcessingInstruction ()
{
document.LoadXml ("<?xml-stylesheet href='foo.xsl' type='text/xsl' ?><foo />");
navigator = document.CreateNavigator ();
Assert (navigator.MoveToFirstChild ());
AssertEquals (XPathNodeType.ProcessingInstruction, navigator.NodeType);
AssertEquals ("xml-stylesheet", navigator.Name);
XPathNodeIterator iter = navigator.SelectChildren (XPathNodeType.Element);
AssertEquals (0, iter.Count);
}
[Test]
public void SelectFromOrphan ()
{
// SelectSingleNode () from node without parent.
XmlDocument doc = new XmlDocument ();
doc.LoadXml ("<foo><include id='original' /></foo>");
XmlNode node = doc.CreateElement ("child");
node.InnerXml = "<include id='new' />";
XmlNode new_include = node.SelectSingleNode ("//include");
AssertEquals ("<include id=\"new\" />", new_include.OuterXml);
// In this case 'node2' has parent 'node'
doc = new XmlDocument ();
doc.LoadXml ("<foo><include id='original' /></foo>");
node = doc.CreateElement ("child");
XmlNode node2 = doc.CreateElement ("grandchild");
node.AppendChild (node2);
node2.InnerXml = "<include id='new' />";
new_include = node2.SelectSingleNode ("/");
AssertEquals ("<child><grandchild><include id=\"new\" /></grandchild></child>",
new_include.OuterXml);
}
[Test]
public void XPathDocumentMoveToId ()
{
string dtd = "<!DOCTYPE root [<!ELEMENT root EMPTY><!ATTLIST root id ID #REQUIRED>]>";
string xml = dtd + "<root id='aaa'/>";
StringReader sr = new StringReader (xml);
XPathNavigator nav = new XPathDocument (sr).CreateNavigator ();
Assert ("ctor() from TextReader", nav.MoveToId ("aaa"));
XmlValidatingReader xvr = new XmlValidatingReader (xml, XmlNodeType.Document, null);
nav = new XPathDocument (xvr).CreateNavigator ();
Assert ("ctor() from XmlValidatingReader", nav.MoveToId ("aaa"));
// When it is XmlTextReader, XPathDocument fails.
XmlTextReader xtr = new XmlTextReader (xml, XmlNodeType.Document, null);
nav = new XPathDocument (xtr).CreateNavigator ();
Assert ("ctor() from XmlTextReader", !nav.MoveToId ("aaa"));
xtr.Close ();
}
[Test]
public void SignificantWhitespaceConstruction ()
{
string xml = @"<root>
<child xml:space='preserve'> <!-- --> </child>
<child xml:space='preserve'> </child>
</root>";
XPathNavigator nav = new XPathDocument (
new XmlTextReader (xml, XmlNodeType.Document, null),
XmlSpace.Preserve).CreateNavigator ();
nav.MoveToFirstChild ();
nav.MoveToFirstChild ();
AssertEquals ("#1", XPathNodeType.Whitespace, nav.NodeType);
nav.MoveToNext ();
nav.MoveToFirstChild ();
AssertEquals ("#2", XPathNodeType.SignificantWhitespace,
nav.NodeType);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
namespace System.IO
{
public sealed class DirectoryInfo : FileSystemInfo
{
[System.Security.SecuritySafeCritical]
public DirectoryInfo(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
OriginalPath = PathHelpers.ShouldReviseDirectoryPathToCurrent(path) ? "." : path;
FullPath = PathHelpers.GetFullPathInternal(path);
DisplayPath = GetDisplayName(OriginalPath, FullPath);
}
[System.Security.SecuritySafeCritical]
internal DirectoryInfo(String fullPath, IFileSystemObject fileSystemObject) : base(fileSystemObject)
{
Debug.Assert(PathInternal.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
// Fast path when we know a DirectoryInfo exists.
OriginalPath = Path.GetFileName(fullPath);
FullPath = fullPath;
DisplayPath = GetDisplayName(OriginalPath, FullPath);
}
public override String Name
{
get
{
// DisplayPath is dir name for coreclr
Debug.Assert(GetDirName(FullPath) == DisplayPath || DisplayPath == ".");
return DisplayPath;
}
}
public DirectoryInfo Parent
{
[System.Security.SecuritySafeCritical]
get
{
string s = FullPath;
// FullPath might end in either "parent\child" or "parent\child", and in either case we want
// the parent of child, not the child. Trim off an ending directory separator if there is one,
// but don't mangle the root.
if (!PathHelpers.IsRoot(s))
{
s = PathHelpers.TrimEndingDirectorySeparator(s);
}
string parentName = Path.GetDirectoryName(s);
return parentName != null ?
new DirectoryInfo(parentName, null) :
null;
}
}
[System.Security.SecuritySafeCritical]
public DirectoryInfo CreateSubdirectory(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return CreateSubdirectoryHelper(path);
}
[System.Security.SecurityCritical] // auto-generated
private DirectoryInfo CreateSubdirectoryHelper(String path)
{
Contract.Requires(path != null);
PathHelpers.ThrowIfEmptyOrRootedPath(path);
String newDirs = Path.Combine(FullPath, path);
String fullPath = Path.GetFullPath(newDirs);
if (0 != String.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.GetComparison()))
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath), "path");
}
FileSystem.Current.CreateDirectory(fullPath);
// Check for read permission to directory we hand back by calling this constructor.
return new DirectoryInfo(fullPath);
}
[System.Security.SecurityCritical]
public void Create()
{
FileSystem.Current.CreateDirectory(FullPath);
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
public override bool Exists
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
try
{
return FileSystemObject.Exists;
}
catch
{
return false;
}
}
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
[SecurityCritical]
public FileInfo[] GetFiles(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public FileInfo[] GetFiles(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetFiles(searchPattern, searchOption);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
private FileInfo[] InternalGetFiles(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileInfo> enumerable = (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files);
return EnumerableHelpers.ToArray(enumerable);
}
// Returns an array of Files in the DirectoryInfo specified by path
public FileInfo[] GetFiles()
{
return InternalGetFiles("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current directory.
public DirectoryInfo[] GetDirectories()
{
return InternalGetDirectories("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt").
public FileSystemInfo[] GetFileSystemInfos(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt").
public FileSystemInfo[] GetFileSystemInfos(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetFileSystemInfos(searchPattern, searchOption);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt").
private FileSystemInfo[] InternalGetFileSystemInfos(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileSystemInfo> enumerable = FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both);
return EnumerableHelpers.ToArray(enumerable);
}
// Returns an array of strongly typed FileSystemInfo entries which will contain a listing
// of all the files and directories.
public FileSystemInfo[] GetFileSystemInfos()
{
return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "System*" could match the System & System32
// directories).
public DirectoryInfo[] GetDirectories(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "System*" could match the System & System32
// directories).
public DirectoryInfo[] GetDirectories(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalGetDirectories(searchPattern, searchOption);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "System*" could match the System & System32
// directories).
private DirectoryInfo[] InternalGetDirectories(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories);
return EnumerableHelpers.ToArray(enumerable);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories()
{
return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateDirectories(searchPattern, searchOption);
}
private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories);
}
public IEnumerable<FileInfo> EnumerateFiles()
{
return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileInfo> EnumerateFiles(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileInfo> EnumerateFiles(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateFiles(searchPattern, searchOption);
}
private IEnumerable<FileInfo> InternalEnumerateFiles(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos()
{
return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateFileSystemInfos(searchPattern, searchOption);
}
private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both);
}
// Returns the root portion of the given path. The resulting string
// consists of those rightmost characters of the path that constitute the
// root of the path. Possible patterns for the resulting string are: An
// empty string (a relative path on the current drive), "\" (an absolute
// path on the current drive), "X:" (a relative path on a given drive,
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
// The resulting string is null if path is null.
//
public DirectoryInfo Root
{
[System.Security.SecuritySafeCritical]
get
{
String rootPath = Path.GetPathRoot(FullPath);
return new DirectoryInfo(rootPath);
}
}
[System.Security.SecuritySafeCritical]
public void MoveTo(String destDirName)
{
if (destDirName == null)
throw new ArgumentNullException("destDirName");
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName");
Contract.EndContractBlock();
String fullDestDirName = PathHelpers.GetFullPathInternal(destDirName);
if (fullDestDirName[fullDestDirName.Length - 1] != Path.DirectorySeparatorChar)
fullDestDirName = fullDestDirName + PathHelpers.DirectorySeparatorCharAsString;
String fullSourcePath;
if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar)
fullSourcePath = FullPath;
else
fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString;
int maxDirectoryPath = FileSystem.Current.MaxDirectoryPath;
if (fullSourcePath.Length >= maxDirectoryPath)
throw new PathTooLongException(SR.IO_PathTooLong);
if (fullDestDirName.Length >= maxDirectoryPath)
throw new PathTooLongException(SR.IO_PathTooLong);
StringComparison pathComparison = PathInternal.GetComparison();
if (String.Equals(fullSourcePath, fullDestDirName, pathComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
String sourceRoot = Path.GetPathRoot(fullSourcePath);
String destinationRoot = Path.GetPathRoot(fullDestDirName);
if (!String.Equals(sourceRoot, destinationRoot, pathComparison))
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
FileSystem.Current.MoveDirectory(FullPath, fullDestDirName);
FullPath = fullDestDirName;
OriginalPath = destDirName;
DisplayPath = GetDisplayName(OriginalPath, FullPath);
// Flush any cached information about the directory.
Invalidate();
}
[System.Security.SecuritySafeCritical]
public override void Delete()
{
FileSystem.Current.RemoveDirectory(FullPath, false);
}
[System.Security.SecuritySafeCritical]
public void Delete(bool recursive)
{
FileSystem.Current.RemoveDirectory(FullPath, recursive);
}
// Returns the fully qualified path
public override String ToString()
{
return DisplayPath;
}
private static String GetDisplayName(String originalPath, String fullPath)
{
Debug.Assert(originalPath != null);
Debug.Assert(fullPath != null);
return PathHelpers.ShouldReviseDirectoryPathToCurrent(originalPath) ?
"." :
GetDirName(fullPath);
}
private static String GetDirName(String fullPath)
{
Debug.Assert(fullPath != null);
return PathHelpers.IsRoot(fullPath) ?
fullPath :
Path.GetFileName(PathHelpers.TrimEndingDirectorySeparator(fullPath));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using GitVersion.Extensions;
using GitVersion.Logging;
using GitVersion.Model.Configuration;
using GitVersion.VersionCalculation;
namespace GitVersion.Configuration
{
public static class ConfigExtensions
{
public static Config ApplyDefaults(this Config config)
{
config.Reset();
return config;
}
public static void Reset(this Config config)
{
config.AssemblyVersioningScheme ??= AssemblyVersioningScheme.MajorMinorPatch;
config.AssemblyFileVersioningScheme ??= AssemblyFileVersioningScheme.MajorMinorPatch;
config.AssemblyInformationalFormat = config.AssemblyInformationalFormat;
config.AssemblyVersioningFormat = config.AssemblyVersioningFormat;
config.AssemblyFileVersioningFormat = config.AssemblyFileVersioningFormat;
config.TagPrefix ??= Config.DefaultTagPrefix;
config.VersioningMode ??= VersioningMode.ContinuousDelivery;
config.ContinuousDeploymentFallbackTag ??= "ci";
config.MajorVersionBumpMessage ??= IncrementStrategyFinder.DefaultMajorPattern;
config.MinorVersionBumpMessage ??= IncrementStrategyFinder.DefaultMinorPattern;
config.PatchVersionBumpMessage ??= IncrementStrategyFinder.DefaultPatchPattern;
config.NoBumpMessage ??= IncrementStrategyFinder.DefaultNoBumpPattern;
config.CommitMessageIncrementing ??= CommitMessageIncrementMode.Enabled;
config.LegacySemVerPadding ??= 4;
config.BuildMetaDataPadding ??= 4;
config.CommitsSinceVersionSourcePadding ??= 4;
config.CommitDateFormat ??= "yyyy-MM-dd";
var configBranches = config.Branches.ToList();
ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.DevelopBranchKey), Config.DevelopBranchRegex,
new List<string>(),
defaultTag: "alpha",
defaultIncrementStrategy: IncrementStrategy.Minor,
defaultVersioningMode: config.VersioningMode == VersioningMode.Mainline ? VersioningMode.Mainline : VersioningMode.ContinuousDeployment,
defaultTrackMergeTarget: true,
tracksReleaseBranches: true);
ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.MasterBranchKey), Config.MasterBranchRegex,
new List<string>
{ "develop", "release" },
defaultTag: string.Empty,
defaultPreventIncrement: true,
defaultIncrementStrategy: IncrementStrategy.Patch,
isMainline: true);
ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.ReleaseBranchKey), Config.ReleaseBranchRegex,
new List<string>
{ "develop", "master", "support", "release" },
defaultTag: "beta",
defaultPreventIncrement: true,
defaultIncrementStrategy: IncrementStrategy.None,
isReleaseBranch: true);
ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.FeatureBranchKey), Config.FeatureBranchRegex,
new List<string>
{ "develop", "master", "release", "feature", "support", "hotfix" },
defaultIncrementStrategy: IncrementStrategy.Inherit);
ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.PullRequestBranchKey), Config.PullRequestRegex,
new List<string>
{ "develop", "master", "release", "feature", "support", "hotfix" },
defaultTag: "PullRequest",
defaultTagNumberPattern: @"[/-](?<number>\d+)",
defaultIncrementStrategy: IncrementStrategy.Inherit);
ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.HotfixBranchKey), Config.HotfixBranchRegex,
new List<string>
{ "develop", "master", "support" },
defaultTag: "beta",
defaultIncrementStrategy: IncrementStrategy.Patch);
ApplyBranchDefaults(config, GetOrCreateBranchDefaults(config, Config.SupportBranchKey), Config.SupportBranchRegex,
new List<string>
{ "master" },
defaultTag: string.Empty,
defaultPreventIncrement: true,
defaultIncrementStrategy: IncrementStrategy.Patch,
isMainline: true);
// Any user defined branches should have other values defaulted after known branches filled in.
// This allows users to override any of the value.
foreach (var branchConfig in configBranches)
{
var regex = branchConfig.Value.Regex;
if (regex == null)
{
throw new ConfigurationException($"Branch configuration '{branchConfig.Key}' is missing required configuration 'regex'{System.Environment.NewLine}" +
"See https://gitversion.net/docs/configuration/ for more info");
}
var sourceBranches = branchConfig.Value.SourceBranches;
if (sourceBranches == null)
{
throw new ConfigurationException($"Branch configuration '{branchConfig.Key}' is missing required configuration 'source-branches'{System.Environment.NewLine}" +
"See https://gitversion.net/docs/configuration/ for more info");
}
ApplyBranchDefaults(config, branchConfig.Value, regex, sourceBranches);
}
// This is a second pass to add additional sources, it has to be another pass to prevent ordering issues
foreach (var branchConfig in configBranches)
{
if (branchConfig.Value.IsSourceBranchFor == null) continue;
foreach (var isSourceBranch in branchConfig.Value.IsSourceBranchFor)
{
config.Branches[isSourceBranch].SourceBranches.Add(branchConfig.Key);
}
}
}
private static readonly Dictionary<string, int> DefaultPreReleaseWeight =
new Dictionary<string, int>
{
{ Config.DevelopBranchRegex, 0 },
{ Config.HotfixBranchRegex, 30000 },
{ Config.ReleaseBranchRegex, 30000 },
{ Config.FeatureBranchRegex, 30000 },
{ Config.PullRequestRegex, 30000 },
{ Config.SupportBranchRegex, 55000 },
{ Config.MasterBranchRegex, 55000 }
};
private const IncrementStrategy DefaultIncrementStrategy = IncrementStrategy.Inherit;
public static void ApplyBranchDefaults(this Config config,
BranchConfig branchConfig,
string branchRegex,
List<string> sourceBranches,
string defaultTag = "useBranchName",
IncrementStrategy? defaultIncrementStrategy = null, // Looked up from main config
bool defaultPreventIncrement = false,
VersioningMode? defaultVersioningMode = null, // Looked up from main config
bool defaultTrackMergeTarget = false,
string defaultTagNumberPattern = null,
bool tracksReleaseBranches = false,
bool isReleaseBranch = false,
bool isMainline = false)
{
branchConfig.Regex = string.IsNullOrEmpty(branchConfig.Regex) ? branchRegex : branchConfig.Regex;
branchConfig.SourceBranches = branchConfig.SourceBranches == null || !branchConfig.SourceBranches.Any()
? sourceBranches : branchConfig.SourceBranches;
branchConfig.Tag ??= defaultTag;
branchConfig.TagNumberPattern ??= defaultTagNumberPattern;
branchConfig.Increment ??= defaultIncrementStrategy ?? config.Increment ?? DefaultIncrementStrategy;
branchConfig.PreventIncrementOfMergedBranchVersion ??= defaultPreventIncrement;
branchConfig.TrackMergeTarget ??= defaultTrackMergeTarget;
branchConfig.VersioningMode ??= defaultVersioningMode ?? config.VersioningMode;
branchConfig.TracksReleaseBranches ??= tracksReleaseBranches;
branchConfig.IsReleaseBranch ??= isReleaseBranch;
branchConfig.IsMainline ??= isMainline;
DefaultPreReleaseWeight.TryGetValue(branchRegex, out var defaultPreReleaseNumber);
branchConfig.PreReleaseWeight ??= defaultPreReleaseNumber;
}
public static void Verify(this Config readConfig)
{
// Verify no branches are set to mainline mode
if (readConfig.Branches.Any(b => b.Value.VersioningMode == VersioningMode.Mainline))
{
throw new ConfigurationException(@"Mainline mode only works at the repository level, a single branch cannot be put into mainline mode
This is because mainline mode treats your entire git repository as an event source with each merge into the 'mainline' incrementing the version.
If the docs do not help you decide on the mode open an issue to discuss what you are trying to do.");
}
}
public static void ApplyOverridesTo(this Config config, Config overrideConfig)
{
config.Branches.Clear();
config.Ignore = overrideConfig.Ignore;
config.Branches = overrideConfig.Branches;
config.Increment = overrideConfig.Increment;
config.NextVersion = overrideConfig.NextVersion;
config.VersioningMode = overrideConfig.VersioningMode;
config.AssemblyFileVersioningFormat = overrideConfig.AssemblyFileVersioningFormat;
config.TagPrefix = string.IsNullOrWhiteSpace(overrideConfig.TagPrefix) ? config.TagPrefix : overrideConfig.TagPrefix;
}
public static BranchConfig GetConfigForBranch(this Config config, string branchName)
{
if (branchName == null) throw new ArgumentNullException(nameof(branchName));
var matches = config.Branches
.Where(b => Regex.IsMatch(branchName, b.Value.Regex, RegexOptions.IgnoreCase))
.ToArray();
try
{
return matches
.Select(kvp => kvp.Value)
.SingleOrDefault();
}
catch (InvalidOperationException)
{
var matchingConfigs = string.Concat(matches.Select(m => $"{System.Environment.NewLine} - {m.Key}"));
var picked = matches
.Select(kvp => kvp.Value)
.First();
// TODO check how to log this
Console.WriteLine(
$"Multiple branch configurations match the current branch branchName of '{branchName}'. " +
$"Using the first matching configuration, '{picked.Name}'. Matching configurations include:'{matchingConfigs}'");
return picked;
}
}
public static bool IsReleaseBranch(this Config config, string branchName) => config.GetConfigForBranch(branchName)?.IsReleaseBranch ?? false;
public static EffectiveConfiguration CalculateEffectiveConfiguration(this Config configuration, BranchConfig currentBranchConfig)
{
var name = currentBranchConfig.Name;
if (!currentBranchConfig.VersioningMode.HasValue)
throw new Exception($"Configuration value for 'Versioning mode' for branch {name} has no value. (this should not happen, please report an issue)");
if (!currentBranchConfig.Increment.HasValue)
throw new Exception($"Configuration value for 'Increment' for branch {name} has no value. (this should not happen, please report an issue)");
if (!currentBranchConfig.PreventIncrementOfMergedBranchVersion.HasValue)
throw new Exception($"Configuration value for 'PreventIncrementOfMergedBranchVersion' for branch {name} has no value. (this should not happen, please report an issue)");
if (!currentBranchConfig.TrackMergeTarget.HasValue)
throw new Exception($"Configuration value for 'TrackMergeTarget' for branch {name} has no value. (this should not happen, please report an issue)");
if (!currentBranchConfig.TracksReleaseBranches.HasValue)
throw new Exception($"Configuration value for 'TracksReleaseBranches' for branch {name} has no value. (this should not happen, please report an issue)");
if (!currentBranchConfig.IsReleaseBranch.HasValue)
throw new Exception($"Configuration value for 'IsReleaseBranch' for branch {name} has no value. (this should not happen, please report an issue)");
if (!configuration.AssemblyVersioningScheme.HasValue)
throw new Exception("Configuration value for 'AssemblyVersioningScheme' has no value. (this should not happen, please report an issue)");
if (!configuration.AssemblyFileVersioningScheme.HasValue)
throw new Exception("Configuration value for 'AssemblyFileVersioningScheme' has no value. (this should not happen, please report an issue)");
if (!configuration.CommitMessageIncrementing.HasValue)
throw new Exception("Configuration value for 'CommitMessageIncrementing' has no value. (this should not happen, please report an issue)");
if (!configuration.LegacySemVerPadding.HasValue)
throw new Exception("Configuration value for 'LegacySemVerPadding' has no value. (this should not happen, please report an issue)");
if (!configuration.BuildMetaDataPadding.HasValue)
throw new Exception("Configuration value for 'BuildMetaDataPadding' has no value. (this should not happen, please report an issue)");
if (!configuration.CommitsSinceVersionSourcePadding.HasValue)
throw new Exception("Configuration value for 'CommitsSinceVersionSourcePadding' has no value. (this should not happen, please report an issue)");
var versioningMode = currentBranchConfig.VersioningMode.Value;
var tag = currentBranchConfig.Tag;
var tagNumberPattern = currentBranchConfig.TagNumberPattern;
var incrementStrategy = currentBranchConfig.Increment.Value;
var preventIncrementForMergedBranchVersion = currentBranchConfig.PreventIncrementOfMergedBranchVersion.Value;
var trackMergeTarget = currentBranchConfig.TrackMergeTarget.Value;
var preReleaseWeight = currentBranchConfig.PreReleaseWeight ?? 0;
var nextVersion = configuration.NextVersion;
var assemblyVersioningScheme = configuration.AssemblyVersioningScheme.Value;
var assemblyFileVersioningScheme = configuration.AssemblyFileVersioningScheme.Value;
var assemblyInformationalFormat = configuration.AssemblyInformationalFormat;
var assemblyVersioningFormat = configuration.AssemblyVersioningFormat;
var assemblyFileVersioningFormat = configuration.AssemblyFileVersioningFormat;
var gitTagPrefix = configuration.TagPrefix;
var majorMessage = configuration.MajorVersionBumpMessage;
var minorMessage = configuration.MinorVersionBumpMessage;
var patchMessage = configuration.PatchVersionBumpMessage;
var noBumpMessage = configuration.NoBumpMessage;
var commitDateFormat = configuration.CommitDateFormat;
var commitMessageVersionBump = currentBranchConfig.CommitMessageIncrementing ?? configuration.CommitMessageIncrementing.Value;
return new EffectiveConfiguration(
assemblyVersioningScheme, assemblyFileVersioningScheme, assemblyInformationalFormat, assemblyVersioningFormat, assemblyFileVersioningFormat, versioningMode, gitTagPrefix,
tag, nextVersion, incrementStrategy,
currentBranchConfig.Regex,
preventIncrementForMergedBranchVersion,
tagNumberPattern, configuration.ContinuousDeploymentFallbackTag,
trackMergeTarget,
majorMessage, minorMessage, patchMessage, noBumpMessage,
commitMessageVersionBump,
configuration.LegacySemVerPadding.Value,
configuration.BuildMetaDataPadding.Value,
configuration.CommitsSinceVersionSourcePadding.Value,
configuration.Ignore.ToFilters(),
currentBranchConfig.TracksReleaseBranches.Value,
currentBranchConfig.IsReleaseBranch.Value,
commitDateFormat,
preReleaseWeight);
}
public static string GetBranchSpecificTag(this EffectiveConfiguration configuration, ILog log, string branchFriendlyName, string branchNameOverride)
{
var tagToUse = configuration.Tag;
if (tagToUse == "useBranchName")
{
tagToUse = "{BranchName}";
}
if (tagToUse.Contains("{BranchName}"))
{
log.Info("Using branch name to calculate version tag");
var branchName = branchNameOverride ?? branchFriendlyName;
if (!string.IsNullOrWhiteSpace(configuration.BranchPrefixToTrim))
{
branchName = branchName.RegexReplace(configuration.BranchPrefixToTrim, string.Empty, RegexOptions.IgnoreCase);
}
branchName = branchName.RegexReplace("[^a-zA-Z0-9-]", "-");
tagToUse = tagToUse.Replace("{BranchName}", branchName);
}
return tagToUse;
}
public static List<KeyValuePair<string, BranchConfig>> GetReleaseBranchConfig(this Config configuration)
{
return configuration.Branches
.Where(b => b.Value.IsReleaseBranch == true)
.ToList();
}
private static BranchConfig GetOrCreateBranchDefaults(this Config config, string branchKey)
{
if (!config.Branches.ContainsKey(branchKey))
{
var branchConfig = new BranchConfig { Name = branchKey };
config.Branches.Add(branchKey, branchConfig);
return branchConfig;
}
return config.Branches[branchKey];
}
}
}
| |
using System;
using System.Collections.Generic;
using xsc = DotNetXmlSwfChart;
namespace testWeb.tests
{
public class FloatingColumnOne : ChartTestBase
{
//TODO: Update test so the links work
//Note: the reference chart on the gallery page at
//http://www.maani.us/xml_charts/index.php?menu=Gallery&submenu=Floating_Column
//contains a link. Need a license in order to make the links work. Fix it
//once a license is available
#region ChartInclude
public override DotNetXmlSwfChart.ChartHTML ChartInclude
{
get
{
DotNetXmlSwfChart.ChartHTML chartHtml = new DotNetXmlSwfChart.ChartHTML();
chartHtml.height = 300;
chartHtml.bgColor = "ccaaff";
chartHtml.flashFile = "charts/charts.swf";
chartHtml.libraryPath = "charts/charts_library";
chartHtml.xmlSource = "xmlData.aspx";
return chartHtml;
}
}
#endregion
#region Chart
public override DotNetXmlSwfChart.Chart Chart
{
get
{
xsc.Chart c = new xsc.Chart();
c.AddChartType(xsc.XmlSwfChartType.ColumnFloating);
c.AxisCategory = SetAxisCategory(c.ChartType[0]);
c.AxisTicks = SetAxisTicks();
c.AxisValue = SetAxisValue();
c.ChartBorder = SetChartBorder();
c.ChartGridH = SetChartGridH();
c.ChartGridV = SetChartGridV();
c.ChartRectangle = SetChartRectangle();
c.ChartTransition = SetChartTransition();
c.ChartValue = SetChartValue();
c.Data = SetChartData();
c.DrawImages = SetDrawImages();
c.DrawTexts = SetDrawTexts();
c.DrawRectangles = SetDrawRectangles();
c.DrawCircles = SetDrawCircles();
c.LinkAreas = SetLinkAreas();
c.LegendRectangle = SetLegendRectangle();
c.SeriesColors = new List<string>();
c.SeriesColors.Add("ffaa22");
c.SeriesGap = SetSeriesGap();
return c;
}
}
#endregion
#region Helpers
#region SetAxisCategory()
private xsc.AxisCategory SetAxisCategory(xsc.XmlSwfChartType type)
{
xsc.AxisCategory ac = new xsc.AxisCategory(type);
ac.Size = 14;
ac.Color = "000000";
ac.Alpha = 50;
return ac;
}
#endregion
#region SetAxisTicks()
private xsc.AxisTicks SetAxisTicks()
{
xsc.AxisTicks at = new xsc.AxisTicks();
at.ValueTicks = false;
at.CategoryTicks = true;
at.MajorThickness = 2;
at.MinorThickness = 0;
at.MinorCount = 0;
at.MajorColor = "888888";
at.Position = "centered";
return at;
}
#endregion
#region SetAxisValue()
private xsc.AxisValue SetAxisValue()
{
xsc.AxisValue av = new xsc.AxisValue();
av.Size = 12;
av.Color = "000000";
av.Alpha = 50;
av.Steps = 4;
av.Prefix = "";
av.Suffix = "F";
av.Decimals = 0;
av.Separator = "";
av.ShowMin = true;
return av;
}
#endregion
#region SetChartBorder()
private xsc.ChartBorder SetChartBorder()
{
xsc.ChartBorder cb = new xsc.ChartBorder();
cb.Color = "000000";
cb.TopThickness = 0;
cb.BottomThickness = 2;
cb.LeftThickness = 1;
cb.RightThickness = 0;
return cb;
}
#endregion
#region SetChartGridH()
private xsc.ChartGrid SetChartGridH()
{
xsc.ChartGrid cg = new xsc.ChartGrid(xsc.ChartGridType.Horizontal);
cg.Alpha = 20;
cg.Color = "000000";
cg.Thickness = 0;
cg.GridLineType = xsc.ChartGridLineType.dashed;
return cg;
}
#endregion
#region SetChartGridV()
private xsc.ChartGrid SetChartGridV()
{
xsc.ChartGrid cg = new xsc.ChartGrid(xsc.ChartGridType.Vertical);
cg.Alpha = 20;
cg.Color = "ffffff";
cg.Thickness = 5;
cg.GridLineType = xsc.ChartGridLineType.solid;
return cg;
}
#endregion
#region SetChartRectangle()
private xsc.ChartRectangle SetChartRectangle()
{
xsc.ChartRectangle cr = new xsc.ChartRectangle();
cr.X = 75;
cr.Y = 50;
cr.Width = 300;
cr.Height = 150;
cr.PositiveColor = "ffff00";
cr.PositiveAlpha = 80;
return cr;
}
#endregion
#region SetChartTransition()
private xsc.ChartTransition SetChartTransition()
{
xsc.ChartTransition ct = new xsc.ChartTransition();
ct.TransitionType = xsc.TransitionType.dissolve;
ct.Delay = 0.5;
ct.Duration = 0.5;
ct.Order = xsc.TransitionOrder.all;
return ct;
}
#endregion
#region SetChartValue()
private xsc.ChartValue SetChartValue()
{
xsc.ChartValue cv = new xsc.ChartValue();
cv.Color = "ffffff";
cv.Alpha = 85;
cv.Font = "Arial";
cv.Bold = true;
cv.Size = 10;
cv.Position = "inside";
cv.Prefix = "";
cv.Suffix = "";
cv.Decimals = 0;
cv.Separator = "";
cv.AsPercentage = false;
return cv;
}
#endregion
#region SetChartData()
private xsc.ChartData SetChartData()
{
xsc.ChartData cd = new xsc.ChartData();
cd.AddDataPoint("hi", "MON", 54);
cd.AddDataPoint("hi", "TUE", 60);
cd.AddDataPoint("hi", "WED", 62);
cd.AddDataPoint("hi", "THU", 63);
cd.AddDataPoint("hi", "FRI", 64);
cd.AddDataPoint("hi", "SAT", 63);
cd.AddDataPoint("hi", "SUN", 62);
cd.AddDataPoint("lo", "MON", 45);
cd.AddDataPoint("lo", "TUE", 51);
cd.AddDataPoint("lo", "WED", 55);
cd.AddDataPoint("lo", "THU", 53);
cd.AddDataPoint("lo", "FRI", 51);
cd.AddDataPoint("lo", "SAT", 50);
cd.AddDataPoint("lo", "SUN", 53);
return cd;
}
#endregion
#region SetDrawImages()
private List<xsc.DrawImage> SetDrawImages()
{
List<xsc.DrawImage> img = new List<xsc.DrawImage>();
xsc.DrawImage i = new xsc.DrawImage();
i.Transition = xsc.TransitionType.dissolve;
i.Delay = 0;
i.Duration = 0.5;
i.Layer = xsc.DrawLayer.background;
i.Alpha = 10;
i.Url = "images/pattern.swf";
i.X = 0;
i.Y = 0;
i.Width = 550;
i.Height = 400;
img.Add(i);
return img;
}
#endregion
#region SetDrawTexts()
private List<xsc.DrawText> SetDrawTexts()
{
List<xsc.DrawText> txt = new List<xsc.DrawText>();
xsc.DrawText t = new xsc.DrawText();
t.Color = "ffffee";
t.Alpha = 75;
t.Rotation = 0;
t.Size = 50;
t.X = 0;
t.Y = -10;
t.Width = 400;
t.Height = 200;
t.HAlign = xsc.TextHAlign.left;
t.VAlign = xsc.TextVAlign.top;
t.Text = "temperatures";
txt.Add(t);
t = new xsc.DrawText();
t.Color = "000000";
t.Alpha = 35;
t.Rotation = 0;
t.Size = 25;
t.X = 317;
t.Y = 10;
t.Width = 300;
t.Height = 200;
t.HAlign = xsc.TextHAlign.left;
t.VAlign = xsc.TextVAlign.top;
t.Text = "hi/low";
txt.Add(t);
t = new xsc.DrawText();
t.Color = "ffff88";
t.Alpha = 90;
t.Size = 18;
t.X = 95;
t.Y = 240;
t.Width = 300;
t.Height = 200;
t.Text = "Fahrenheit Celsius";
txt.Add(t);
t = new xsc.DrawText();
t.Transition = xsc.TransitionType.drop;
t.Duration = 2;
t.Color = "000000";
t.Alpha = 40;
t.Rotation = -90;
t.Size = 30;
t.X = 20;
t.Y = 210;
t.Width = 300;
t.Height = 200;
t.HAlign = xsc.TextHAlign.left;
t.VAlign = xsc.TextVAlign.top;
t.Text = "fahrenheit";
txt.Add(t);
return txt;
}
#endregion
#region SetDrawRectangles()
private List<xsc.DrawRectangle> SetDrawRectangles()
{
List<xsc.DrawRectangle> dr = new List<xsc.DrawRectangle>();
xsc.DrawRectangle r = new xsc.DrawRectangle();
r.X = 0;
r.Y = 230;
r.Width = 400;
r.Height = 400;
r.FillColor = "440088";
r.FillAlpha = 40;
r.LineColor = "000000";
r.LineAlpha = 0;
r.LineThickness = 0;
dr.Add(r);
return dr;
}
#endregion
#region SetDrawCircles()
private List<xsc.DrawCircle> SetDrawCircles()
{
List<xsc.DrawCircle> cir = new List<xsc.DrawCircle>();
xsc.DrawCircle c = new xsc.DrawCircle();
c.X = 85;
c.Y = 252;
c.Radius = 8;
c.FillColor = "000000";
c.FillAlpha = 0;
c.LineColor = "000000";
c.LineAlpha = 60;
c.LineThickness = 2;
cir.Add(c);
c = new xsc.DrawCircle();
c.X = 260;
c.Y = 252;
c.Radius = 8;
c.FillColor = "000000";
c.FillAlpha = 0;
c.LineColor = "000000";
c.LineAlpha = 60;
c.LineThickness = 2;
cir.Add(c);
c = new xsc.DrawCircle();
c.X = 85;
c.Y = 252;
c.Radius = 5;
c.FillColor = "000000";
c.FillAlpha = 90;
c.LineColor = "000000";
c.LineAlpha = 0;
c.LineThickness = 0;
cir.Add(c);
return cir;
}
#endregion
#region SetLinkAreas()
private List<xsc.LinkArea> SetLinkAreas()
{
List<xsc.LinkArea> la = new List<xsc.LinkArea>();
xsc.LinkArea l = new xsc.LinkArea();
l.X = 250;
l.Y = 240;
l.Width = 130;
l.Height = 25;
l.Url = "chartView.aspx?test=floatingcolumn1";
l.Target = "live_update";
la.Add(l);
return la;
}
#endregion
#region SetLegendRectangle()
private xsc.LegendRectangle SetLegendRectangle()
{
xsc.LegendRectangle lr = new xsc.LegendRectangle();
lr.X = -1000;
lr.Y = -1000;
lr.Width = 0;
lr.Height = 0;
return lr;
}
#endregion
#region SetSeriesGap()
private xsc.SeriesGap SetSeriesGap()
{
xsc.SeriesGap sg = new xsc.SeriesGap();
sg.BarGap = 0;
sg.SetGap = 25;
return sg;
}
#endregion
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
namespace Org.BouncyCastle.Asn1.X509
{
/**
* <pre>
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::= SET SIZE (1..MAX) OF AttributeTypeAndValue
*
* AttributeTypeAndValue ::= SEQUENCE {
* type OBJECT IDENTIFIER,
* value ANY }
* </pre>
*/
public class X509Name
: Asn1Encodable
{
/**
* country code - StringType(SIZE(2))
*/
public static readonly DerObjectIdentifier C = new DerObjectIdentifier("2.5.4.6");
/**
* organization - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier O = new DerObjectIdentifier("2.5.4.10");
/**
* organizational unit name - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier OU = new DerObjectIdentifier("2.5.4.11");
/**
* Title
*/
public static readonly DerObjectIdentifier T = new DerObjectIdentifier("2.5.4.12");
/**
* common name - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier CN = new DerObjectIdentifier("2.5.4.3");
/**
* street - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier Street = new DerObjectIdentifier("2.5.4.9");
/**
* device serial number name - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier SerialNumber = new DerObjectIdentifier("2.5.4.5");
/**
* locality name - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier L = new DerObjectIdentifier("2.5.4.7");
/**
* state, or province name - StringType(SIZE(1..64))
*/
public static readonly DerObjectIdentifier ST = new DerObjectIdentifier("2.5.4.8");
/**
* Naming attributes of type X520name
*/
public static readonly DerObjectIdentifier Surname = new DerObjectIdentifier("2.5.4.4");
public static readonly DerObjectIdentifier GivenName = new DerObjectIdentifier("2.5.4.42");
public static readonly DerObjectIdentifier Initials = new DerObjectIdentifier("2.5.4.43");
public static readonly DerObjectIdentifier Generation = new DerObjectIdentifier("2.5.4.44");
public static readonly DerObjectIdentifier UniqueIdentifier = new DerObjectIdentifier("2.5.4.45");
/**
* businessCategory - DirectoryString(SIZE(1..128)
*/
public static readonly DerObjectIdentifier BusinessCategory = new DerObjectIdentifier(
"2.5.4.15");
/**
* postalCode - DirectoryString(SIZE(1..40)
*/
public static readonly DerObjectIdentifier PostalCode = new DerObjectIdentifier(
"2.5.4.17");
/**
* dnQualifier - DirectoryString(SIZE(1..64)
*/
public static readonly DerObjectIdentifier DnQualifier = new DerObjectIdentifier(
"2.5.4.46");
/**
* RFC 3039 Pseudonym - DirectoryString(SIZE(1..64)
*/
public static readonly DerObjectIdentifier Pseudonym = new DerObjectIdentifier(
"2.5.4.65");
/**
* RFC 3039 DateOfBirth - GeneralizedTime - YYYYMMDD000000Z
*/
public static readonly DerObjectIdentifier DateOfBirth = new DerObjectIdentifier(
"1.3.6.1.5.5.7.9.1");
/**
* RFC 3039 PlaceOfBirth - DirectoryString(SIZE(1..128)
*/
public static readonly DerObjectIdentifier PlaceOfBirth = new DerObjectIdentifier(
"1.3.6.1.5.5.7.9.2");
/**
* RFC 3039 DateOfBirth - PrintableString (SIZE(1)) -- "M", "F", "m" or "f"
*/
public static readonly DerObjectIdentifier Gender = new DerObjectIdentifier(
"1.3.6.1.5.5.7.9.3");
/**
* RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
* codes only
*/
public static readonly DerObjectIdentifier CountryOfCitizenship = new DerObjectIdentifier(
"1.3.6.1.5.5.7.9.4");
/**
* RFC 3039 CountryOfCitizenship - PrintableString (SIZE (2)) -- ISO 3166
* codes only
*/
public static readonly DerObjectIdentifier CountryOfResidence = new DerObjectIdentifier(
"1.3.6.1.5.5.7.9.5");
/**
* ISIS-MTT NameAtBirth - DirectoryString(SIZE(1..64)
*/
public static readonly DerObjectIdentifier NameAtBirth = new DerObjectIdentifier("1.3.36.8.3.14");
/**
* RFC 3039 PostalAddress - SEQUENCE SIZE (1..6) OF
* DirectoryString(SIZE(1..30))
*/
public static readonly DerObjectIdentifier PostalAddress = new DerObjectIdentifier("2.5.4.16");
/**
* RFC 2256 dmdName
*/
public static readonly DerObjectIdentifier DmdName = new DerObjectIdentifier("2.5.4.54");
/**
* id-at-telephoneNumber
*/
public static readonly DerObjectIdentifier TelephoneNumber = X509ObjectIdentifiers.id_at_telephoneNumber;
/**
* id-at-name
*/
public static readonly DerObjectIdentifier Name = X509ObjectIdentifiers.id_at_name;
/**
* Email address (RSA PKCS#9 extension) - IA5String.
* <p>Note: if you're trying to be ultra orthodox, don't use this! It shouldn't be in here.</p>
*/
public static readonly DerObjectIdentifier EmailAddress = PkcsObjectIdentifiers.Pkcs9AtEmailAddress;
/**
* more from PKCS#9
*/
public static readonly DerObjectIdentifier UnstructuredName = PkcsObjectIdentifiers.Pkcs9AtUnstructuredName;
public static readonly DerObjectIdentifier UnstructuredAddress = PkcsObjectIdentifiers.Pkcs9AtUnstructuredAddress;
/**
* email address in Verisign certificates
*/
public static readonly DerObjectIdentifier E = EmailAddress;
/*
* others...
*/
public static readonly DerObjectIdentifier DC = new DerObjectIdentifier("0.9.2342.19200300.100.1.25");
/**
* LDAP User id.
*/
public static readonly DerObjectIdentifier UID = new DerObjectIdentifier("0.9.2342.19200300.100.1.1");
/**
* determines whether or not strings should be processed and printed
* from back to front.
*/
// public static bool DefaultReverse = false;
public static bool DefaultReverse
{
get { return defaultReverse[0]; }
set { defaultReverse[0] = value; }
}
private static readonly bool[] defaultReverse = { false };
#if SILVERLIGHT || NETFX_CORE
/**
* default look up table translating OID values into their common symbols following
* the convention in RFC 2253 with a few extras
*/
public static readonly IDictionary DefaultSymbols = Platform.CreateHashtable();
/**
* look up table translating OID values into their common symbols following the convention in RFC 2253
*/
public static readonly IDictionary RFC2253Symbols = Platform.CreateHashtable();
/**
* look up table translating OID values into their common symbols following the convention in RFC 1779
*
*/
public static readonly IDictionary RFC1779Symbols = Platform.CreateHashtable();
/**
* look up table translating common symbols into their OIDS.
*/
public static readonly IDictionary DefaultLookup = Platform.CreateHashtable();
#else
/**
* default look up table translating OID values into their common symbols following
* the convention in RFC 2253 with a few extras
*/
public static readonly Hashtable DefaultSymbols = new Hashtable();
/**
* look up table translating OID values into their common symbols following the convention in RFC 2253
*/
public static readonly Hashtable RFC2253Symbols = new Hashtable();
/**
* look up table translating OID values into their common symbols following the convention in RFC 1779
*
*/
public static readonly Hashtable RFC1779Symbols = new Hashtable();
/**
* look up table translating common symbols into their OIDS.
*/
public static readonly Hashtable DefaultLookup = new Hashtable();
#endif
static X509Name()
{
DefaultSymbols.Add(C, "C");
DefaultSymbols.Add(O, "O");
DefaultSymbols.Add(T, "T");
DefaultSymbols.Add(OU, "OU");
DefaultSymbols.Add(CN, "CN");
DefaultSymbols.Add(L, "L");
DefaultSymbols.Add(ST, "ST");
DefaultSymbols.Add(SerialNumber, "SERIALNUMBER");
DefaultSymbols.Add(EmailAddress, "E");
DefaultSymbols.Add(DC, "DC");
DefaultSymbols.Add(UID, "UID");
DefaultSymbols.Add(Street, "STREET");
DefaultSymbols.Add(Surname, "SURNAME");
DefaultSymbols.Add(GivenName, "GIVENNAME");
DefaultSymbols.Add(Initials, "INITIALS");
DefaultSymbols.Add(Generation, "GENERATION");
DefaultSymbols.Add(UnstructuredAddress, "unstructuredAddress");
DefaultSymbols.Add(UnstructuredName, "unstructuredName");
DefaultSymbols.Add(UniqueIdentifier, "UniqueIdentifier");
DefaultSymbols.Add(DnQualifier, "DN");
DefaultSymbols.Add(Pseudonym, "Pseudonym");
DefaultSymbols.Add(PostalAddress, "PostalAddress");
DefaultSymbols.Add(NameAtBirth, "NameAtBirth");
DefaultSymbols.Add(CountryOfCitizenship, "CountryOfCitizenship");
DefaultSymbols.Add(CountryOfResidence, "CountryOfResidence");
DefaultSymbols.Add(Gender, "Gender");
DefaultSymbols.Add(PlaceOfBirth, "PlaceOfBirth");
DefaultSymbols.Add(DateOfBirth, "DateOfBirth");
DefaultSymbols.Add(PostalCode, "PostalCode");
DefaultSymbols.Add(BusinessCategory, "BusinessCategory");
DefaultSymbols.Add(TelephoneNumber, "TelephoneNumber");
RFC2253Symbols.Add(C, "C");
RFC2253Symbols.Add(O, "O");
RFC2253Symbols.Add(OU, "OU");
RFC2253Symbols.Add(CN, "CN");
RFC2253Symbols.Add(L, "L");
RFC2253Symbols.Add(ST, "ST");
RFC2253Symbols.Add(Street, "STREET");
RFC2253Symbols.Add(DC, "DC");
RFC2253Symbols.Add(UID, "UID");
RFC1779Symbols.Add(C, "C");
RFC1779Symbols.Add(O, "O");
RFC1779Symbols.Add(OU, "OU");
RFC1779Symbols.Add(CN, "CN");
RFC1779Symbols.Add(L, "L");
RFC1779Symbols.Add(ST, "ST");
RFC1779Symbols.Add(Street, "STREET");
DefaultLookup.Add("c", C);
DefaultLookup.Add("o", O);
DefaultLookup.Add("t", T);
DefaultLookup.Add("ou", OU);
DefaultLookup.Add("cn", CN);
DefaultLookup.Add("l", L);
DefaultLookup.Add("st", ST);
DefaultLookup.Add("serialnumber", SerialNumber);
DefaultLookup.Add("street", Street);
DefaultLookup.Add("emailaddress", E);
DefaultLookup.Add("dc", DC);
DefaultLookup.Add("e", E);
DefaultLookup.Add("uid", UID);
DefaultLookup.Add("surname", Surname);
DefaultLookup.Add("givenname", GivenName);
DefaultLookup.Add("initials", Initials);
DefaultLookup.Add("generation", Generation);
DefaultLookup.Add("unstructuredaddress", UnstructuredAddress);
DefaultLookup.Add("unstructuredname", UnstructuredName);
DefaultLookup.Add("uniqueidentifier", UniqueIdentifier);
DefaultLookup.Add("dn", DnQualifier);
DefaultLookup.Add("pseudonym", Pseudonym);
DefaultLookup.Add("postaladdress", PostalAddress);
DefaultLookup.Add("nameofbirth", NameAtBirth);
DefaultLookup.Add("countryofcitizenship", CountryOfCitizenship);
DefaultLookup.Add("countryofresidence", CountryOfResidence);
DefaultLookup.Add("gender", Gender);
DefaultLookup.Add("placeofbirth", PlaceOfBirth);
DefaultLookup.Add("dateofbirth", DateOfBirth);
DefaultLookup.Add("postalcode", PostalCode);
DefaultLookup.Add("businesscategory", BusinessCategory);
DefaultLookup.Add("telephonenumber", TelephoneNumber);
}
private readonly IList _ordering = Platform.CreateArrayList();
private readonly X509NameEntryConverter _converter;
private readonly IList _values = Platform.CreateArrayList();
private readonly IList _added = Platform.CreateArrayList();
private Asn1Sequence _seq;
/**
* Return a X509Name based on the passed in tagged object.
*
* @param obj tag object holding name.
* @param explicitly true if explicitly tagged false otherwise.
* @return the X509Name
*/
public static X509Name GetInstance(
Asn1TaggedObject obj,
bool explicitly)
{
return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
}
public static X509Name GetInstance(
object obj)
{
if (obj == null || obj is X509Name)
return (X509Name)obj;
if (obj != null)
return new X509Name(Asn1Sequence.GetInstance(obj));
throw new ArgumentException(@"null object in factory", "obj");
}
protected X509Name()
{
}
/**
* Constructor from Asn1Sequence
*
* the principal will be a list of constructed sets, each containing an (OID, string) pair.
*/
protected X509Name(
Asn1Sequence seq)
{
_seq = seq;
foreach (Asn1Encodable asn1Obj in seq)
{
Asn1Set asn1Set = Asn1Set.GetInstance(asn1Obj.ToAsn1Object());
for (int i = 0; i < asn1Set.Count; i++)
{
Asn1Sequence s = Asn1Sequence.GetInstance(asn1Set[i].ToAsn1Object());
if (s.Count != 2)
throw new ArgumentException("badly sized pair");
_ordering.Add(DerObjectIdentifier.GetInstance(s[0].ToAsn1Object()));
Asn1Object derValue = s[1].ToAsn1Object();
if (derValue is IAsn1String && !(derValue is DerUniversalString))
{
string v = ((IAsn1String)derValue).GetString();
if (v.StartsWith("#"))
{
v = "\\" + v;
}
_values.Add(v);
}
else
{
_values.Add("#" + Hex.ToHexString(derValue.GetEncoded()));
}
_added.Add(i != 0);
}
}
}
#if !(SILVERLIGHT || NETFX_CORE)
[Obsolete]
public X509Name(
ArrayList ordering,
Hashtable attributes)
: this(ordering, attributes, new X509DefaultEntryConverter())
{
}
#endif
/**
* Constructor from a table of attributes with ordering.
* <p>
* it's is assumed the table contains OID/string pairs, and the contents
* of the table are copied into an internal table as part of the
* construction process. The ordering ArrayList should contain the OIDs
* in the order they are meant to be encoded or printed in ToString.</p>
*/
public X509Name(
IList ordering,
IDictionary attributes)
: this(ordering, attributes, new X509DefaultEntryConverter())
{
}
#if !(SILVERLIGHT || NETFX_CORE)
[Obsolete]
public X509Name(
ArrayList ordering,
Hashtable attributes,
X509NameEntryConverter converter)
: this((IList)ordering, (IDictionary)attributes, converter)
{
}
#endif
/**
* Constructor from a table of attributes with ordering.
* <p>
* it's is assumed the table contains OID/string pairs, and the contents
* of the table are copied into an internal table as part of the
* construction process. The ordering ArrayList should contain the OIDs
* in the order they are meant to be encoded or printed in ToString.</p>
* <p>
* The passed in converter will be used to convert the strings into their
* ASN.1 counterparts.</p>
*/
public X509Name(
IList ordering,
IDictionary attributes,
X509NameEntryConverter converter)
{
_converter = converter;
foreach (DerObjectIdentifier oid in ordering)
{
object attribute = attributes[oid];
if (attribute == null)
{
throw new ArgumentException("No attribute for object id - " + oid + " - passed to distinguished name");
}
_ordering.Add(oid);
_added.Add(false);
_values.Add(attribute); // copy the hash table
}
}
#if !(SILVERLIGHT || NETFX_CORE)
[Obsolete]
public X509Name(
ArrayList oids,
ArrayList values)
: this(oids, values, new X509DefaultEntryConverter())
{
}
#endif
/**
* Takes two vectors one of the oids and the other of the values.
*/
public X509Name(
IList oids,
IList values)
: this(oids, values, new X509DefaultEntryConverter())
{
}
#if !(SILVERLIGHT || NETFX_CORE)
[Obsolete]
public X509Name(
ArrayList oids,
ArrayList values,
X509NameEntryConverter converter)
: this((IList)oids, (IList)values, converter)
{
}
#endif
/**
* Takes two vectors one of the oids and the other of the values.
* <p>
* The passed in converter will be used to convert the strings into their
* ASN.1 counterparts.</p>
*/
public X509Name(
IList oids,
IList values,
X509NameEntryConverter converter)
{
_converter = converter;
if (oids.Count != values.Count)
{
throw new ArgumentException("'oids' must be same length as 'values'.");
}
for (int i = 0; i < oids.Count; i++)
{
_ordering.Add(oids[i]);
_values.Add(values[i]);
_added.Add(false);
}
}
// private static bool IsEncoded(
// string s)
// {
// return s.StartsWith("#");
// }
/**
* Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
* some such, converting it into an ordered set of name attributes.
*/
public X509Name(
string dirName)
: this(DefaultReverse, (IDictionary)DefaultLookup, dirName)
{
}
/**
* Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
* some such, converting it into an ordered set of name attributes with each
* string value being converted to its associated ASN.1 type using the passed
* in converter.
*/
public X509Name(
string dirName,
X509NameEntryConverter converter)
: this(DefaultReverse, DefaultLookup, dirName, converter)
{
}
/**
* Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
* some such, converting it into an ordered set of name attributes. If reverse
* is true, create the encoded version of the sequence starting from the
* last element in the string.
*/
public X509Name(
bool reverse,
string dirName)
: this(reverse, (IDictionary)DefaultLookup, dirName)
{
}
/**
* Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
* some such, converting it into an ordered set of name attributes with each
* string value being converted to its associated ASN.1 type using the passed
* in converter. If reverse is true the ASN.1 sequence representing the DN will
* be built by starting at the end of the string, rather than the start.
*/
public X509Name(
bool reverse,
string dirName,
X509NameEntryConverter converter)
: this(reverse, DefaultLookup, dirName, converter)
{
}
#if !(SILVERLIGHT || NETFX_CORE)
[Obsolete]
public X509Name(
bool reverse,
Hashtable lookUp,
string dirName)
: this(reverse, lookUp, dirName, new X509DefaultEntryConverter())
{
}
#endif
/**
* Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
* some such, converting it into an ordered set of name attributes. lookUp
* should provide a table of lookups, indexed by lowercase only strings and
* yielding a DerObjectIdentifier, other than that OID. and numeric oids
* will be processed automatically.
* <br/>
* If reverse is true, create the encoded version of the sequence
* starting from the last element in the string.
* @param reverse true if we should start scanning from the end (RFC 2553).
* @param lookUp table of names and their oids.
* @param dirName the X.500 string to be parsed.
*/
public X509Name(
bool reverse,
IDictionary lookUp,
string dirName)
: this(reverse, lookUp, dirName, new X509DefaultEntryConverter())
{
}
private DerObjectIdentifier DecodeOid(
string name,
IDictionary lookUp)
{
if (Platform.StringToUpper(name).StartsWith("OID."))
{
return new DerObjectIdentifier(name.Substring(4));
}
if (name[0] >= '0' && name[0] <= '9')
{
return new DerObjectIdentifier(name);
}
var oid = (DerObjectIdentifier)lookUp[Platform.StringToLower(name)];
if (oid == null)
{
throw new ArgumentException("Unknown object id - " + name + " - passed to distinguished name");
}
return oid;
}
/**
* Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or
* some such, converting it into an ordered set of name attributes. lookUp
* should provide a table of lookups, indexed by lowercase only strings and
* yielding a DerObjectIdentifier, other than that OID. and numeric oids
* will be processed automatically. The passed in converter is used to convert the
* string values to the right of each equals sign to their ASN.1 counterparts.
* <br/>
* @param reverse true if we should start scanning from the end, false otherwise.
* @param lookUp table of names and oids.
* @param dirName the string dirName
* @param converter the converter to convert string values into their ASN.1 equivalents
*/
public X509Name(
bool reverse,
IDictionary lookUp,
string dirName,
X509NameEntryConverter converter)
{
_converter = converter;
var nTok = new X509NameTokenizer(dirName);
while (nTok.HasMoreTokens())
{
string token = nTok.NextToken();
int index = token.IndexOf('=');
if (index == -1)
{
throw new ArgumentException("badly formated directory string");
}
var name = token.Substring(0, index);
var value = token.Substring(index + 1);
var oid = DecodeOid(name, lookUp);
if (value.IndexOf('+') > 0)
{
var vTok = new X509NameTokenizer(value, '+');
var v = vTok.NextToken();
_ordering.Add(oid);
_values.Add(v);
_added.Add(false);
while (vTok.HasMoreTokens())
{
var sv = vTok.NextToken();
var ndx = sv.IndexOf('=');
var nm = sv.Substring(0, ndx);
var vl = sv.Substring(ndx + 1);
_ordering.Add(DecodeOid(nm, lookUp));
_values.Add(vl);
_added.Add(true);
}
}
else
{
_ordering.Add(oid);
_values.Add(value);
_added.Add(false);
}
}
if (reverse)
{
// this.ordering.Reverse();
// this.values.Reverse();
// this.added.Reverse();
IList o = Platform.CreateArrayList();
IList v = Platform.CreateArrayList();
IList a = Platform.CreateArrayList();
int count = 1;
for (int i = 0; i < _ordering.Count; i++)
{
if (!((bool)_added[i]))
{
count = 0;
}
int index = count++;
o.Insert(index, _ordering[i]);
v.Insert(index, _values[i]);
a.Insert(index, _added[i]);
}
_ordering = o;
_values = v;
_added = a;
}
}
#if !(SILVERLIGHT || NETFX_CORE)
/**
* return an ArrayList of the oids in the name, in the order they were found.
*/
[Obsolete("Use 'GetOidList' instead")]
public ArrayList GetOids()
{
return new ArrayList(_ordering);
}
#endif
/**
* return an IList of the oids in the name, in the order they were found.
*/
public IList GetOidList()
{
return Platform.CreateArrayList(_ordering);
}
#if !(SILVERLIGHT || NETFX_CORE)
/**
* return an ArrayList of the values found in the name, in the order they
* were found.
*/
[Obsolete("Use 'GetValueList' instead")]
public ArrayList GetValues()
{
return new ArrayList(_values);
}
#endif
/**
* return an IList of the values found in the name, in the order they
* were found.
*/
public IList GetValueList()
{
return Platform.CreateArrayList(_values);
}
#if !(SILVERLIGHT || NETFX_CORE)
/**
* return an ArrayList of the values found in the name, in the order they
* were found, with the DN label corresponding to passed in oid.
*/
public ArrayList GetValues(
DerObjectIdentifier oid)
{
var v = new ArrayList();
DoGetValueList(oid, v);
return v;
}
#endif
/**
* return an IList of the values found in the name, in the order they
* were found, with the DN label corresponding to passed in oid.
*/
public IList GetValueList(DerObjectIdentifier oid)
{
var v = Platform.CreateArrayList();
DoGetValueList(oid, v);
return v;
}
private void DoGetValueList(DerObjectIdentifier oid, IList v)
{
for (int i = 0; i != _values.Count; i++)
{
if (_ordering[i].Equals(oid))
{
string val = (string)_values[i];
if (val.StartsWith("\\#"))
{
val = val.Substring(1);
}
v.Add(val);
}
}
}
public override Asn1Object ToAsn1Object()
{
if (_seq == null)
{
var vec = new Asn1EncodableVector();
var sVec = new Asn1EncodableVector();
DerObjectIdentifier lstOid = null;
for (var i = 0; i != _ordering.Count; i++)
{
var oid = (DerObjectIdentifier)_ordering[i];
var str = (string)_values[i];
if (lstOid != null && (!((bool) _added[i])))
{
vec.Add(new DerSet(sVec));
sVec = new Asn1EncodableVector();
}
sVec.Add(new DerSequence(oid, _converter.GetConvertedValue(oid, str)));
lstOid = oid;
}
vec.Add(new DerSet(sVec));
_seq = new DerSequence(vec);
}
return _seq;
}
/// <param name="other">The X509Name object to test equivalency against.</param>
/// <param name="inOrder">If true, the order of elements must be the same,
/// as well as the values associated with each element.</param>
public bool Equivalent(
X509Name other,
bool inOrder)
{
if (!inOrder)
return this.Equivalent(other);
if (other == null)
return false;
if (Equals(other, this))
return true;
var orderingSize = _ordering.Count;
if (orderingSize != other._ordering.Count)
return false;
for (var i = 0; i < orderingSize; i++)
{
var oid = (DerObjectIdentifier)_ordering[i];
var oOid = (DerObjectIdentifier)other._ordering[i];
if (!oid.Equals(oOid))
return false;
var val = (string)_values[i];
var oVal = (string)other._values[i];
if (!EquivalentStrings(val, oVal))
return false;
}
return true;
}
/**
* test for equivalence - note: case is ignored.
*/
public bool Equivalent(X509Name other)
{
if (other == null)
return false;
if (Equals(other, this))
return true;
var orderingSize = _ordering.Count;
if (orderingSize != other._ordering.Count)
{
return false;
}
var indexes = new bool[orderingSize];
int start, end, delta;
if (_ordering[0].Equals(other._ordering[0])) // guess forward
{
start = 0;
end = orderingSize;
delta = 1;
}
else // guess reversed - most common problem
{
start = orderingSize - 1;
end = -1;
delta = -1;
}
for (var i = start; i != end; i += delta)
{
var found = false;
var oid = (DerObjectIdentifier)_ordering[i];
var value = (string)_values[i];
for (var j = 0; j < orderingSize; j++)
{
if (indexes[j])
{
continue;
}
var oOid = (DerObjectIdentifier)other._ordering[j];
if (!oid.Equals(oOid))
continue;
var oValue = (string)other._values[j];
if (!EquivalentStrings(value, oValue))
continue;
indexes[j] = true;
found = true;
break;
}
if (!found)
{
return false;
}
}
return true;
}
private static bool EquivalentStrings(
string s1,
string s2)
{
string v1 = Canonicalize(s1);
string v2 = Canonicalize(s2);
if (!v1.Equals(v2))
{
v1 = StripInternalSpaces(v1);
v2 = StripInternalSpaces(v2);
if (!v1.Equals(v2))
{
return false;
}
}
return true;
}
private static string Canonicalize(string s)
{
var v = Platform.StringToLower(s).Trim();
if (v.StartsWith("#"))
{
var obj = DecodeObject(v);
var str = obj as IAsn1String;
if (str != null)
{
v = Platform.StringToLower(str.GetString()).Trim();
}
}
return v;
}
private static Asn1Object DecodeObject(string v)
{
try
{
return Asn1Object.FromByteArray(Hex.Decode(v.Substring(1)));
}
catch (IOException e)
{
throw new InvalidOperationException("unknown encoding in name: " + e.Message, e);
}
}
private static string StripInternalSpaces(string str)
{
var res = new StringBuilder();
if (str.Length != 0)
{
var c1 = str[0];
res.Append(c1);
for (var k = 1; k < str.Length; k++)
{
var c2 = str[k];
if (!(c1 == ' ' && c2 == ' '))
{
res.Append(c2);
}
c1 = c2;
}
}
return res.ToString();
}
private void AppendValue(
StringBuilder buf,
IDictionary oidSymbols,
DerObjectIdentifier oid,
string val)
{
var sym = (string)oidSymbols[oid];
buf.Append(sym ?? oid.Id);
buf.Append('=');
var index = buf.Length;
buf.Append(val);
var end = buf.Length;
if (val.StartsWith("\\#"))
{
index += 2;
}
while (index != end)
{
if ((buf[index] == ',')
|| (buf[index] == '"')
|| (buf[index] == '\\')
|| (buf[index] == '+')
|| (buf[index] == '=')
|| (buf[index] == '<')
|| (buf[index] == '>')
|| (buf[index] == ';'))
{
buf.Insert(index++, "\\");
end++;
}
index++;
}
}
#if !(SILVERLIGHT || NETFX_CORE)
[Obsolete]
public string ToString(
bool reverse,
Hashtable oidSymbols)
{
return ToString(reverse, (IDictionary)oidSymbols);
}
#endif
/**
* convert the structure to a string - if reverse is true the
* oids and values are listed out starting with the last element
* in the sequence (ala RFC 2253), otherwise the string will begin
* with the first element of the structure. If no string definition
* for the oid is found in oidSymbols the string value of the oid is
* added. Two standard symbol tables are provided DefaultSymbols, and
* RFC2253Symbols as part of this class.
*
* @param reverse if true start at the end of the sequence and work back.
* @param oidSymbols look up table strings for oids.
*/
public string ToString(
bool reverse,
IDictionary oidSymbols)
{
#if SILVERLIGHT || NETFX_CORE
var components = new List<object>();
#else
var components = new ArrayList();
#endif
StringBuilder ava = null;
for (var i = 0; i < _ordering.Count; i++)
{
if (ava != null && (bool)_added[i])
{
ava.Append('+');
AppendValue(ava, oidSymbols,
(DerObjectIdentifier)_ordering[i],
(string)_values[i]);
}
else
{
ava = new StringBuilder();
AppendValue(ava, oidSymbols,
(DerObjectIdentifier)_ordering[i],
(string)_values[i]);
components.Add(ava);
}
}
if (reverse)
{
components.Reverse();
}
var buf = new StringBuilder();
if (components.Count > 0)
{
buf.Append(components[0]);
for (var i = 1; i < components.Count; ++i)
{
buf.Append(',');
buf.Append(components[i]);
}
}
return buf.ToString();
}
public override string ToString()
{
return ToString(DefaultReverse, (IDictionary)DefaultSymbols);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void LeadingZeroCount_Vector128_Byte()
{
var test = new SimpleUnaryOpTest__LeadingZeroCount_Vector128_Byte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__LeadingZeroCount_Vector128_Byte
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Byte[] inArray1, Byte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Byte>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Byte> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__LeadingZeroCount_Vector128_Byte testClass)
{
var result = AdvSimd.LeadingZeroCount(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__LeadingZeroCount_Vector128_Byte testClass)
{
fixed (Vector128<Byte>* pFld1 = &_fld1)
{
var result = AdvSimd.LeadingZeroCount(
AdvSimd.LoadVector128((Byte*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte);
private static Byte[] _data1 = new Byte[Op1ElementCount];
private static Vector128<Byte> _clsVar1;
private Vector128<Byte> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__LeadingZeroCount_Vector128_Byte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>());
}
public SimpleUnaryOpTest__LeadingZeroCount_Vector128_Byte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
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 < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); }
_dataTable = new DataTable(_data1, new Byte[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.LeadingZeroCount(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.LeadingZeroCount(
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LeadingZeroCount), new Type[] { typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LeadingZeroCount), new Type[] { typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.LeadingZeroCount(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Byte>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.LeadingZeroCount(
AdvSimd.LoadVector128((Byte*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var result = AdvSimd.LeadingZeroCount(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var result = AdvSimd.LeadingZeroCount(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__LeadingZeroCount_Vector128_Byte();
var result = AdvSimd.LeadingZeroCount(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__LeadingZeroCount_Vector128_Byte();
fixed (Vector128<Byte>* pFld1 = &test._fld1)
{
var result = AdvSimd.LeadingZeroCount(
AdvSimd.LoadVector128((Byte*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.LeadingZeroCount(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Byte>* pFld1 = &_fld1)
{
var result = AdvSimd.LeadingZeroCount(
AdvSimd.LoadVector128((Byte*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.LeadingZeroCount(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.LeadingZeroCount(
AdvSimd.LoadVector128((Byte*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Byte> op1, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Byte[] firstOp, Byte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (Helpers.CountLeadingZeroBits(firstOp[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (Helpers.CountLeadingZeroBits(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LeadingZeroCount)}<Byte>(Vector128<Byte>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/* ***************************************************************************
* This file is part of SharpNEAT - Evolution of Neural Networks.
*
* Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com)
*
* SharpNEAT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SharpNEAT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SharpNEAT. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using SharpNeat.Network;
namespace SharpNeat.Genomes.Neat
{
// ENHANCEMENT: Consider switching to a SortedList[K,V] - which guarantees item sort order at all times.
/// <summary>
/// Represents a sorted list of ConnectionGene objects. The sorting of the items is done on request
/// rather than being strictly enforced at all times (e.g. as part of adding and removing genes). This
/// approach is currently more convenient for use in some of the routines that work with NEAT genomes.
///
/// Because we are not using a strictly sorted list such as the generic class SortedList[K,V] a customised
/// BinarySearch() method is provided for fast lookup of items if the list is known to be sorted. If the list is
/// not sorted then the BinarySearch method's behaviour is undefined. This is potentially a source of bugs
/// and thus this class should probably migrate to SortedList[K,V] or be modified to ensure items are sorted
/// prior to a binary search.
///
/// Sort order is with respect to connection gene innovation ID.
/// </summary>
public class ConnectionGeneList : List<ConnectionGene>, IConnectionList
{
static readonly ConnectionGeneComparer __connectionGeneComparer = new ConnectionGeneComparer();
#region Constructors
/// <summary>
/// Construct an empty list.
/// </summary>
public ConnectionGeneList()
{
}
/// <summary>
/// Construct an empty list with the specified capacity.
/// </summary>
public ConnectionGeneList(int capacity) : base(capacity)
{
}
/// <summary>
/// Copy constructor. The newly allocated list has a capacity 2 larger than copyFrom
/// allowing addition mutations to occur without reallocation of memory.
/// Note that a single add node mutation adds two connections and a single
/// add connection mutation adds one.
/// </summary>
public ConnectionGeneList(ICollection<ConnectionGene> copyFrom) : base(copyFrom.Count + 2)
{
// ENHANCEMENT: List.Foreach() is potentially faster then a foreach loop.
// http://diditwith.net/2006/10/05/PerformanceOfForeachVsListForEach.aspx
foreach(ConnectionGene srcGene in copyFrom) {
Add(srcGene.CreateCopy());
}
}
#endregion
#region Public Methods
/// <summary>
/// Inserts a ConnectionGene into its correct (sorted) location within the gene list.
/// Normally connection genes can safely be assumed to have a new Innovation ID higher
/// than all existing IDs, and so we can just call Add().
/// This routine handles genes with older IDs that need placing correctly.
/// </summary>
public void InsertIntoPosition(ConnectionGene connectionGene)
{
// Determine the insert idx with a linear search, starting from the end
// since mostly we expect to be adding genes that belong only 1 or 2 genes
// from the end at most.
int idx=Count-1;
for(; idx > -1; idx--)
{
if(this[idx].InnovationId < connectionGene.InnovationId)
{ // Insert idx found.
break;
}
}
Insert(idx+1, connectionGene);
}
/// <summary>
/// Remove the connection gene with the specified innovation ID.
/// </summary>
public void Remove(uint innovationId)
{
int idx = BinarySearch(innovationId);
if(idx<0) {
throw new ApplicationException("Attempt to remove connection with an unknown innovationId");
}
RemoveAt(idx);
}
/// <summary>
/// Sort connection genes into ascending order by their innovation IDs.
/// </summary>
public void SortByInnovationId()
{
Sort(__connectionGeneComparer);
}
/// <summary>
/// Obtain the index of the gene with the specified innovation ID by performing a binary search.
/// Binary search is fast and can be performed so long as we know the genes are sorted by innovation ID.
/// If the genes are not sorted then the behaviour of this method is undefined.
/// </summary>
public int BinarySearch(uint innovationId)
{
int lo = 0;
int hi = Count-1;
while (lo <= hi)
{
int i = (lo + hi) >> 1;
// Note. we don't calculate this[i].InnovationId-innovationId because we are dealing with uint.
// ENHANCEMENT: List<T>[i] invokes a bounds check on each call. Can we avoid this?
if(this[i].InnovationId < innovationId) {
lo = i + 1;
} else if(this[i].InnovationId > innovationId) {
hi = i - 1;
} else {
return i;
}
}
return ~lo;
}
/// <summary>
/// Resets the IsMutated flag on all ConnectionGenes in the list.
/// </summary>
public void ResetIsMutatedFlags()
{
int count = this.Count;
for(int i=0; i<count; i++) {
this[i].IsMutated = false;
}
}
/// <summary>
/// For debug purposes only. Don't call this method in normal circumstances as it is an
/// expensive O(n) operation.
/// </summary>
public bool IsSorted()
{
int count = this.Count;
if(0 == count) {
return true;
}
uint prev = this[0].InnovationId;
for(int i=1; i<count; i++)
{
if(this[i].InnovationId <= prev) {
return false;
}
}
return true;
}
#endregion
#region IConnectionList Members
INetworkConnection IConnectionList.this[int index]
{
get { return this[index]; }
}
int IConnectionList.Count
{
get { return this.Count; }
}
IEnumerator<INetworkConnection> IEnumerable<INetworkConnection>.GetEnumerator()
{
foreach(ConnectionGene gene in this) {
yield return gene;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<INetworkConnection>)this).GetEnumerator();
}
#endregion
}
}
| |
//
// HtmlGallery.cs
//
// Author:
// Lorenzo Milesi <maxxer@yetopen.it>
// Stephane Delcroix <stephane@delcroix.org>
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (C) 2008-2009 Novell, Inc.
// Copyright (C) 2008 Lorenzo Milesi
// Copyright (C) 2008-2009 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
/*
* Copyright (C) 2005 Alessandro Gervaso <gervystar@gervystar.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301
*/
//This should be used to export the selected pics to an original gallery
//located on a GIO location.
using System;
using System.IO;
using System.Collections.Generic;
using Mono.Unix;
using FSpot.Core;
namespace FSpot.Exporters.Folder
{
class HtmlGallery : FolderGallery
{
int perpage = 16;
string stylesheet = "f-spot-simple.css";
string altstylesheet = "f-spot-simple-white.css";
string javascript = "f-spot.js";
//Note for translators: light as clear, opposite as dark
static string light = Catalog.GetString("Light");
static string dark = Catalog.GetString("Dark");
List<string> allTagNames = new List<string> ();
Dictionary<string,Tag> allTags = new Dictionary<string, Tag> ();
Dictionary<string, List<int>> tagSets = new Dictionary<string, List<int>> ();
public HtmlGallery (IBrowsableCollection selection, string path, string name) : base (selection, path, name)
{
requests = new ScaleRequest [] { new ScaleRequest ("hq", 0, 0, false),
new ScaleRequest ("mq", 480, 320, false),
new ScaleRequest ("thumbs", 120, 90, false) };
}
protected override string ImageName (int photo_index)
{
return String.Format ("img-{0}.jpg", photo_index + 1);
}
public override void GenerateLayout ()
{
if (Collection.Count == 0)
return;
base.GenerateLayout ();
IPhoto [] photos = Collection.Items;
int i;
for (i = 0; i < photos.Length; i++)
SavePhotoHtmlIndex (i);
for (i = 0; i < PageCount; i++)
SaveHtmlIndex (i);
if (ExportTags) {
// identify tags present in these photos
i = 0;
foreach (IPhoto photo in photos) {
foreach (var tag in photo.Tags) {
if (!tagSets.ContainsKey (tag.Name)) {
tagSets.Add (tag.Name, new List<int> ());
allTags.Add (tag.Name, tag);
}
tagSets [tag.Name].Add (i);
}
i++;
}
allTagNames = new List<string> (tagSets.Keys);
allTagNames.Sort ();
// create tag pages
SaveTagsPage ();
foreach (string tag in allTagNames) {
for (i = 0; i < TagPageCount (tag); i++)
SaveTagIndex (tag, i);
}
}
if (ExportTags && ExportTagIcons) {
SaveTagIcons ();
}
MakeDir (SubdirPath ("style"));
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetCallingAssembly ();
using (Stream s = assembly.GetManifestResourceStream (stylesheet)) {
using (Stream fs = System.IO.File.Open (SubdirPath ("style", stylesheet), System.IO.FileMode.Create)) {
byte [] buffer = new byte [8192];
int n;
while ((n = s.Read (buffer, 0, buffer.Length)) != 0)
fs.Write (buffer, 0, n);
}
}
/* quick and stupid solution
this should have been iterated over an array of stylesheets, really
*/
using (Stream s = assembly.GetManifestResourceStream (altstylesheet)) {
using (Stream fs = System.IO.File.Open (SubdirPath ("style", altstylesheet), System.IO.FileMode.Create)) {
byte [] buffer = new byte [8192];
int n = 0;
while ((n = s.Read (buffer, 0, buffer.Length)) != 0)
fs.Write (buffer, 0, n);
}
}
/* Javascript for persistant style change */
MakeDir (SubdirPath ("script"));
using (Stream s = assembly.GetManifestResourceStream (javascript)) {
using (Stream fs = System.IO.File.Open (SubdirPath ("script", javascript), System.IO.FileMode.Create)) {
byte [] buffer = new byte [8192];
int n = 0;
while ((n = s.Read (buffer, 0, buffer.Length)) != 0)
fs.Write (buffer, 0, n);
}
}
}
public int PageCount {
get {
return (int) System.Math.Ceiling (Collection.Items.Length / (double)perpage);
}
}
public int TagPageCount (string tag)
{
return (int) System.Math.Ceiling (tagSets [tag].Count / (double)perpage);
}
public string PhotoThumbPath (int item)
{
return System.IO.Path.Combine (requests [2].Name, ImageName (item));
}
public string PhotoWebPath (int item)
{
return System.IO.Path.Combine (requests [1].Name, ImageName (item));
}
public string PhotoOriginalPath (int item)
{
return System.IO.Path.Combine (requests [0].Name, ImageName (item));
}
public string PhotoIndexPath (int item)
{
return (System.IO.Path.GetFileNameWithoutExtension (ImageName (item)) + ".html");
}
public static void WritePageNav (System.Web.UI.HtmlTextWriter writer, string id, string url, string name)
{
writer.AddAttribute ("id", id);
writer.RenderBeginTag ("div");
writer.AddAttribute ("href", url);
writer.RenderBeginTag ("a");
writer.Write (name);
writer.RenderEndTag ();
writer.RenderEndTag ();
}
public void SavePhotoHtmlIndex (int i)
{
System.IO.StreamWriter stream = System.IO.File.CreateText (SubdirPath (PhotoIndexPath (i)));
System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter (stream);
//writer.Indent = 4;
//writer.Write ("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
writer.WriteLine ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
writer.AddAttribute ("xmlns", "http://www.w3.org/1999/xhtml");
writer.AddAttribute ("xml:lang", this.Language);
writer.RenderBeginTag ("html");
WriteHeader (writer);
writer.AddAttribute ("onload", "checkForTheme()");
writer.RenderBeginTag ("body");
writer.AddAttribute ("class", "container1");
writer.RenderBeginTag ("div");
writer.AddAttribute ("class", "header");
writer.RenderBeginTag ("div");
writer.AddAttribute ("id", "title");
writer.RenderBeginTag ("div");
writer.Write (GalleryName);
writer.RenderEndTag ();
writer.AddAttribute ("class", "navi");
writer.RenderBeginTag ("div");
if (i > 0)
// Abbreviation of previous
WritePageNav (writer, "prev", PhotoIndexPath (i - 1), Catalog.GetString("Prev"));
WritePageNav (writer, "index", IndexPath (i / perpage), Catalog.GetString("Index"));
if (ExportTags)
WritePageNav (writer, "tagpage", TagsIndexPath (), Catalog.GetString ("Tags"));
if (i < Collection.Count -1)
WritePageNav (writer, "next", PhotoIndexPath (i + 1), Catalog.GetString("Next"));
writer.RenderEndTag (); //navi
writer.RenderEndTag (); //header
writer.AddAttribute ("class", "photo");
writer.RenderBeginTag ("div");
writer.AddAttribute ("href", PhotoOriginalPath (i));
writer.RenderBeginTag ("a");
writer.AddAttribute ("src", PhotoWebPath (i));
writer.AddAttribute ("alt", "#");
writer.AddAttribute ("class", "picture");
writer.RenderBeginTag ("img");
writer.RenderEndTag (); //img
writer.RenderEndTag (); //a
writer.AddAttribute ("id", "description");
writer.RenderBeginTag ("div");
writer.Write (Collection [i].Description);
writer.RenderEndTag (); //div#description
writer.RenderEndTag (); //div.photo
WriteTagsLinks (writer, Collection [i].Tags);
WriteStyleSelectionBox (writer);
writer.RenderEndTag (); //container1
WriteFooter (writer);
writer.RenderEndTag (); //body
writer.RenderEndTag (); // html
writer.Close ();
stream.Close ();
}
public static string IndexPath (int page_num)
{
if (page_num == 0)
return "index.html";
else
return String.Format ("index{0}.html", page_num);
}
public static string TagsIndexPath ()
{
return "tags.html";
}
public static string TagIndexPath (string tag, int page_num)
{
string name = "tag_"+tag;
name = name.Replace ("/", "_").Replace (" ","_");
if (page_num == 0)
return name + ".html";
else
return name + String.Format ("_{0}.html", page_num);
}
static string IndexTitle (int page)
{
return String.Format ("{0}", page + 1);
}
public void WriteHeader (System.Web.UI.HtmlTextWriter writer)
{
WriteHeader (writer, "");
}
public void WriteHeader (System.Web.UI.HtmlTextWriter writer, string titleExtension)
{
writer.RenderBeginTag ("head");
/* It seems HtmlTextWriter always uses UTF-8, unless told otherwise */
writer.Write ("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
writer.WriteLine ();
writer.RenderBeginTag ("title");
writer.Write (GalleryName + titleExtension);
writer.RenderEndTag ();
writer.Write ("<link type=\"text/css\" rel=\"stylesheet\" href=\"");
writer.Write (String.Format ("{0}", "style/" + stylesheet));
writer.Write ("\" title=\"" + dark + "\" media=\"screen\" />" + Environment.NewLine);
writer.Write ("<link type=\"text/css\" rel=\"prefetch ") ;
writer.Write ("alternate stylesheet\" href=\"");
writer.Write (String.Format ("{0}", "style/" + altstylesheet));
writer.Write ("\" title=\"" + light + "\" media=\"screen\" />" + Environment.NewLine);
writer.Write ("<script src=\"script/" + javascript + "\"");
writer.Write (" type=\"text/javascript\"></script>" + Environment.NewLine);
writer.RenderEndTag ();
}
public static void WriteFooter (System.Web.UI.HtmlTextWriter writer)
{
writer.AddAttribute ("class", "footer");
writer.RenderBeginTag ("div");
writer.Write (Catalog.GetString ("Gallery generated by") + " ");
writer.AddAttribute ("href", "http://f-spot.org");
writer.RenderBeginTag ("a");
writer.Write (String.Format ("{0} {1}", FSpot.Core.Defines.PACKAGE, FSpot.Core.Defines.VERSION));
writer.RenderEndTag ();
writer.RenderEndTag ();
}
public static void WriteStyleSelectionBox (System.Web.UI.HtmlTextWriter writer)
{
//Style Selection Box
writer.AddAttribute ("id", "styleboxcontainer");
writer.RenderBeginTag ("div");
writer.AddAttribute ("id", "stylebox");
writer.AddAttribute ("style", "display: none;");
writer.RenderBeginTag ("div");
writer.RenderBeginTag ("ul");
writer.RenderBeginTag ("li");
writer.AddAttribute ("href", "#");
writer.AddAttribute ("title", dark);
writer.AddAttribute ("onclick", "setActiveStyleSheet('" + dark + "')");
writer.RenderBeginTag ("a");
writer.Write (dark);
writer.RenderEndTag (); //a
writer.RenderEndTag (); //li
writer.RenderBeginTag ("li");
writer.AddAttribute ("href", "#");
writer.AddAttribute ("title", light);
writer.AddAttribute ("onclick", "setActiveStyleSheet('" + light + "')");
writer.RenderBeginTag ("a");
writer.Write (light);
writer.RenderEndTag (); //a
writer.RenderEndTag (); //li
writer.RenderEndTag (); //ul
writer.RenderEndTag (); //div stylebox
writer.RenderBeginTag ("div");
writer.Write ("<span class=\"style_toggle\">");
writer.Write ("<a href=\"javascript:toggle_stylebox()\">");
writer.Write ("<span id=\"showlink\">" + Catalog.GetString("Show Styles") + "</span><span id=\"hidelink\" ");
writer.Write ("style=\"display:none;\">" + Catalog.GetString("Hide Styles") + "</span></a></span>" + Environment.NewLine);
writer.RenderEndTag (); //div toggle
writer.RenderEndTag (); //div styleboxcontainer
}
public void WriteTagsLinks (System.Web.UI.HtmlTextWriter writer, Tag[] tags)
{
List<Tag> tagsList = new List<Tag> (tags.Length);
foreach (var tag in tags) {
tagsList.Add (tag);
}
WriteTagsLinks (writer, tagsList);
}
public void WriteTagsLinks (System.Web.UI.HtmlTextWriter writer, System.Collections.ICollection tags)
{
// check if we should write tags
if (!ExportTags && tags.Count>0)
return;
writer.AddAttribute ("id", "tagbox");
writer.RenderBeginTag ("div");
writer.RenderBeginTag ("h1");
writer.Write (Catalog.GetString ("Tags"));
writer.RenderEndTag (); //h1
writer.AddAttribute ("id", "innertagbox");
writer.RenderBeginTag ("ul");
foreach (Tag tag in tags) {
writer.AddAttribute ("class", "tag");
writer.RenderBeginTag ("li");
writer.AddAttribute ("href", TagIndexPath (tag.Name, 0));
writer.RenderBeginTag ("a");
if (ExportTagIcons) {
writer.AddAttribute ("alt", tag.Name);
writer.AddAttribute ("longdesc", Catalog.GetString ("Tags: ")+tag.Name);
writer.AddAttribute ("title", Catalog.GetString ("Tags: ")+tag.Name);
writer.AddAttribute ("src", TagPath (tag));
writer.RenderBeginTag ("img");
writer.RenderEndTag ();
}
writer.Write(" ");
if (ExportTagIcons)
writer.AddAttribute ("class", "tagtext-icon");
else
writer.AddAttribute ("class", "tagtext-noicon");
writer.RenderBeginTag ("span");
writer.Write (tag.Name);
writer.RenderEndTag (); //span.tagtext
writer.RenderEndTag (); //a href
writer.RenderEndTag (); //div.tag
}
writer.RenderEndTag (); //div#tagbox
}
public void SaveTagsPage ()
{
System.IO.StreamWriter stream = System.IO.File.CreateText (SubdirPath (TagsIndexPath ()));
System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter (stream);
writer.WriteLine ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
writer.AddAttribute ("xmlns", "http://www.w3.org/1999/xhtml");
writer.AddAttribute ("xml:lang", this.Language);
writer.RenderBeginTag ("html");
string titleExtension = " " + Catalog.GetString ("Tags");
WriteHeader (writer, titleExtension);
writer.AddAttribute ("onload", "checkForTheme()");
writer.AddAttribute ("id", "tagpage");
writer.RenderBeginTag ("body");
writer.AddAttribute ("class", "container1");
writer.RenderBeginTag ("div");
writer.AddAttribute ("class", "header");
writer.RenderBeginTag ("div");
writer.AddAttribute ("id", "title");
writer.RenderBeginTag ("div");
writer.Write (GalleryName + titleExtension);
writer.RenderEndTag (); //title div
writer.AddAttribute ("class", "navi");
writer.RenderBeginTag ("div");
writer.AddAttribute ("class", "navipage");
writer.RenderBeginTag ("div");
writer.AddAttribute ("href", IndexPath (0));
writer.RenderBeginTag ("a");
writer.Write (Catalog.GetString ("Index"));
writer.RenderEndTag (); //a
writer.RenderEndTag (); //navipage
writer.RenderEndTag (); //navi
writer.RenderEndTag (); //header
WriteTagsLinks (writer, allTags.Values);
WriteStyleSelectionBox (writer);
writer.RenderEndTag (); //container1
WriteFooter (writer);
writer.RenderEndTag (); //body
writer.RenderEndTag (); //html
writer.Close ();
stream.Close ();
}
public void SaveTagIndex (string tag, int page_num)
{
System.IO.StreamWriter stream = System.IO.File.CreateText (SubdirPath (TagIndexPath (tag, page_num)));
System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter (stream);
writer.WriteLine ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
writer.AddAttribute ("xmlns", "http://www.w3.org/1999/xhtml");
writer.AddAttribute ("xml:lang", this.Language);
writer.RenderBeginTag ("html");
string titleExtension = ": " + tag;
WriteHeader (writer, titleExtension);
writer.AddAttribute ("onload", "checkForTheme()");
writer.RenderBeginTag ("body");
writer.AddAttribute ("class", "container1");
writer.RenderBeginTag ("div");
writer.AddAttribute ("class", "header");
writer.RenderBeginTag ("div");
writer.AddAttribute ("id", "title");
writer.RenderBeginTag ("div");
writer.Write (GalleryName + titleExtension);
writer.RenderEndTag (); //title div
writer.AddAttribute ("class", "navi");
writer.RenderBeginTag ("div");
// link to all photos
writer.AddAttribute ("class", "navipage");
writer.RenderBeginTag ("div");
writer.AddAttribute ("href", IndexPath (0));
writer.RenderBeginTag ("a");
writer.Write ("Index");
writer.RenderEndTag (); //a
writer.RenderEndTag (); //navipage
// end link to all photos
// link to all tags
writer.AddAttribute ("class", "navipage");
writer.RenderBeginTag ("div");
writer.AddAttribute ("href", TagsIndexPath ());
writer.RenderBeginTag ("a");
writer.Write ("Tags");
writer.RenderEndTag (); //a
writer.RenderEndTag (); //navipage
// end link to all tags
writer.AddAttribute ("class", "navilabel");
writer.RenderBeginTag ("div");
writer.Write (Catalog.GetString ("Page:"));
writer.RenderEndTag (); //pages div
int i;
for (i = 0; i < TagPageCount (tag); i++) {
writer.AddAttribute ("class", i == page_num ? "navipage-current" : "navipage");
writer.RenderBeginTag ("div");
writer.AddAttribute ("href", TagIndexPath (tag, i));
writer.RenderBeginTag ("a");
writer.Write (IndexTitle (i));
writer.RenderEndTag (); //a
writer.RenderEndTag (); //navipage
}
writer.RenderEndTag (); //navi
writer.RenderEndTag (); //header
writer.AddAttribute ("class", "thumbs");
writer.RenderBeginTag ("div");
int start = page_num * perpage;
List<int> tagSet = tagSets [tag];
int end = Math.Min (start + perpage, tagSet.Count);
for (i = start; i < end; i++) {
writer.AddAttribute ("href", PhotoIndexPath ((int) tagSet [i]));
writer.RenderBeginTag ("a");
writer.AddAttribute ("src", PhotoThumbPath ((int) tagSet [i]));
writer.AddAttribute ("alt", "#");
writer.RenderBeginTag ("img");
writer.RenderEndTag ();
writer.RenderEndTag (); //a
}
writer.RenderEndTag (); //thumbs
writer.AddAttribute ("id", "gallery_description");
writer.RenderBeginTag ("div");
writer.Write (Description);
writer.RenderEndTag (); //description
WriteStyleSelectionBox (writer);
writer.RenderEndTag (); //container1
WriteFooter (writer);
writer.RenderEndTag (); //body
writer.RenderEndTag (); //html
writer.Close ();
stream.Close ();
}
public void SaveTagIcons ()
{
MakeDir (SubdirPath ("tags"));
foreach (Tag tag in allTags.Values)
SaveTagIcon (tag);
}
public void SaveTagIcon (Tag tag) {
Gdk.Pixbuf icon = tag.Icon;
Gdk.Pixbuf scaled = null;
if (icon.Height != 52 || icon.Width != 52) {
scaled=icon.ScaleSimple(52,52,Gdk.InterpType.Bilinear);
} else
scaled=icon.Copy ();
scaled.Save (SubdirPath("tags",TagName(tag)), "png");
scaled.Dispose ();
}
public string TagPath (Tag tag)
{
return System.IO.Path.Combine("tags",TagName(tag));
}
public string TagName (Tag tag)
{
return "tag_"+ ((DbItem)tag).Id+".png";
}
public void SaveHtmlIndex (int page_num)
{
System.IO.StreamWriter stream = System.IO.File.CreateText (SubdirPath (IndexPath (page_num)));
System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter (stream);
//writer.Indent = 4;
//writer.Write ("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
writer.WriteLine ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
writer.AddAttribute ("xmlns", "http://www.w3.org/1999/xhtml");
writer.AddAttribute ("xml:lang", this.Language);
writer.RenderBeginTag ("html");
WriteHeader (writer);
writer.AddAttribute ("onload", "checkForTheme()");
writer.RenderBeginTag ("body");
writer.AddAttribute ("class", "container1");
writer.RenderBeginTag ("div");
writer.AddAttribute ("class", "header");
writer.RenderBeginTag ("div");
writer.AddAttribute ("id", "title");
writer.RenderBeginTag ("div");
writer.Write (GalleryName);
writer.RenderEndTag (); //title div
writer.AddAttribute ("class", "navi");
writer.RenderBeginTag ("div");
if (ExportTags) {
// link to all tags
writer.AddAttribute ("class", "navipage");
writer.RenderBeginTag ("div");
writer.AddAttribute ("href", TagsIndexPath ());
writer.RenderBeginTag ("a");
writer.Write ("Tags");
writer.RenderEndTag (); //a
writer.RenderEndTag (); //navipage
// end link to all tags
}
writer.AddAttribute ("class", "navilabel");
writer.RenderBeginTag ("div");
writer.Write (Catalog.GetString ("Page:"));
writer.RenderEndTag (); //pages div
int i;
for (i = 0; i < PageCount; i++) {
writer.AddAttribute ("class", i == page_num ? "navipage-current" : "navipage");
writer.RenderBeginTag ("div");
writer.AddAttribute ("href", IndexPath (i));
writer.RenderBeginTag ("a");
writer.Write (IndexTitle (i));
writer.RenderEndTag (); //a
writer.RenderEndTag (); //navipage
}
writer.RenderEndTag (); //navi
writer.RenderEndTag (); //header
writer.AddAttribute ("class", "thumbs");
writer.RenderBeginTag ("div");
int start = page_num * perpage;
int end = Math.Min (start + perpage, Collection.Count);
for (i = start; i < end; i++) {
writer.AddAttribute ("href", PhotoIndexPath (i));
writer.RenderBeginTag ("a");
writer.AddAttribute ("src", PhotoThumbPath (i));
writer.AddAttribute ("alt", "#");
writer.RenderBeginTag ("img");
writer.RenderEndTag ();
writer.RenderEndTag (); //a
}
writer.RenderEndTag (); //thumbs
writer.AddAttribute ("id", "gallery_description");
writer.RenderBeginTag ("div");
writer.Write (Description);
writer.RenderEndTag (); //description
WriteStyleSelectionBox (writer);
writer.RenderEndTag (); //container1
WriteFooter (writer);
writer.RenderEndTag (); //body
writer.RenderEndTag (); //html
writer.Close ();
stream.Close ();
}
}
}
| |
using System;
using LanguageExt;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using LanguageExt.DataTypes.Serialisation;
using LanguageExt.TypeClasses;
using LanguageExt.ClassInstances;
using static LanguageExt.Prelude;
namespace LanguageExt
{
public static partial class OptionAsyncT
{
//
// Collections
//
public static OptionAsync<Arr<B>> Traverse<A, B>(this Arr<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Arr<B>>(Go(ma, f));
async Task<(bool, Arr<B>)> Go(Arr<OptionAsync<A>> ma, Func<A, B> f)
{
var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)).ConfigureAwait(false);
return rb.Exists(d => !d.IsSome)
? (false, default)
: (true, new Arr<B>(rb.Map(d => d.Value)));
}
}
public static OptionAsync<HashSet<B>> Traverse<A, B>(this HashSet<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<HashSet<B>>(Go(ma, f));
async Task<(bool, HashSet<B>)> Go(HashSet<OptionAsync<A>> ma, Func<A, B> f)
{
var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)).ConfigureAwait(false);
return rb.Exists(d => !d.IsSome)
? (false, default)
: (true, new HashSet<B>(rb.Map(d => d.Value)));
}
}
[Obsolete("use TraverseSerial or TraverseParallel instead")]
public static OptionAsync<IEnumerable<B>> Traverse<A, B>(this IEnumerable<OptionAsync<A>> ma, Func<A, B> f) =>
TraverseParallel(ma, f);
public static OptionAsync<IEnumerable<B>> TraverseSerial<A, B>(this IEnumerable<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<IEnumerable<B>>(Go(ma, f));
async Task<(bool, IEnumerable<B>)> Go(IEnumerable<OptionAsync<A>> ma, Func<A, B> f)
{
var rb = new List<B>();
foreach (var a in ma)
{
var (isSome, b) = await a.Data;
if (!isSome) return (false, default);
rb.Add(f(b));
}
return (true, rb);
};
}
public static OptionAsync<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<OptionAsync<A>> ma, Func<A, B> f) =>
TraverseParallel(ma, SysInfo.DefaultAsyncSequenceParallelism, f);
public static OptionAsync<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<OptionAsync<A>> ma, int windowSize, Func<A, B> f)
{
return new OptionAsync<IEnumerable<B>>(Go(ma, f));
async Task<(bool, IEnumerable<B>)> Go(IEnumerable<OptionAsync<A>> ma, Func<A, B> f)
{
var rb = await ma.Map(a => a.Map(f).Data).WindowMap(windowSize, Prelude.identity).ConfigureAwait(false);
return rb.Exists(d => !d.IsSome)
? (false, default)
: (true, rb.Map(d => d.Value));
}
}
[Obsolete("use SequenceSerial or SequenceParallel instead")]
public static OptionAsync<IEnumerable<A>> Sequence<A>(this IEnumerable<OptionAsync<A>> ma) =>
TraverseParallel(ma, Prelude.identity);
public static OptionAsync<IEnumerable<A>> SequenceSerial<A>(this IEnumerable<OptionAsync<A>> ma) =>
TraverseSerial(ma, Prelude.identity);
public static OptionAsync<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<OptionAsync<A>> ma) =>
TraverseParallel(ma, Prelude.identity);
public static OptionAsync<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<OptionAsync<A>> ma, int windowSize) =>
TraverseParallel(ma, windowSize, Prelude.identity);
public static OptionAsync<Lst<B>> Traverse<A, B>(this Lst<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Lst<B>>(Go(ma, f));
async Task<(bool, Lst<B>)> Go(Lst<OptionAsync<A>> ma, Func<A, B> f)
{
var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)).ConfigureAwait(false);
return rb.Exists(d => !d.IsSome)
? (false, default)
: (true, new Lst<B>(rb.Map(d => d.Value)));
}
}
public static OptionAsync<Que<B>> Traverse<A, B>(this Que<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Que<B>>(Go(ma, f));
async Task<(bool, Que<B>)> Go(Que<OptionAsync<A>> ma, Func<A, B> f)
{
var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)).ConfigureAwait(false);
return rb.Exists(d => !d.IsSome)
? (false, default)
: (true, new Que<B>(rb.Map(d => d.Value)));
}
}
[Obsolete("use TraverseSerial or TraverseParallel instead")]
public static OptionAsync<Seq<B>> Traverse<A, B>(this Seq<OptionAsync<A>> ma, Func<A, B> f) =>
TraverseParallel(ma, f);
public static OptionAsync<Seq<B>> TraverseSerial<A, B>(this Seq<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Seq<B>>(Go(ma, f));
async Task<(bool, Seq<B>)> Go(Seq<OptionAsync<A>> ma, Func<A, B> f)
{
var rb = new B[ma.Count];
var ix = 0;
foreach (var a in ma)
{
var (isSome, b) = await a.Data;
if (!isSome) return (false, default);
rb[ix] = f(b);
ix++;
}
return (true, Seq.FromArray<B>(rb));
};
}
public static OptionAsync<Seq<B>> TraverseParallel<A, B>(this Seq<OptionAsync<A>> ma, Func<A, B> f) =>
TraverseParallel(ma, SysInfo.DefaultAsyncSequenceParallelism, f);
public static OptionAsync<Seq<B>> TraverseParallel<A, B>(this Seq<OptionAsync<A>> ma, int windowSize, Func<A, B> f)
{
return new OptionAsync<Seq<B>>(Go(ma, f));
async Task<(bool, Seq<B>)> Go(Seq<OptionAsync<A>> ma, Func<A, B> f)
{
var rb = await ma.Map(a => a.Map(f).Data).WindowMap(windowSize, Prelude.identity).ConfigureAwait(false);
return rb.Exists(d => !d.IsSome)
? (false, default)
: (true, Seq.FromArray<B>(rb.Map(d => d.Value).ToArray()));
}
}
[Obsolete("use SequenceSerial or SequenceParallel instead")]
public static OptionAsync<Seq<A>> Sequence<A>(this Seq<OptionAsync<A>> ma) =>
TraverseParallel(ma, Prelude.identity);
public static OptionAsync<Seq<A>> SequenceSerial<A>(this Seq<OptionAsync<A>> ma) =>
TraverseSerial(ma, Prelude.identity);
public static OptionAsync<Seq<A>> SequenceParallel<A>(this Seq<OptionAsync<A>> ma) =>
TraverseParallel(ma, Prelude.identity);
public static OptionAsync<Seq<A>> SequenceParallel<A>(this Seq<OptionAsync<A>> ma, int windowSize) =>
TraverseParallel(ma, windowSize, Prelude.identity);
public static OptionAsync<Set<B>> Traverse<A, B>(this Set<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Set<B>>(Go(ma, f));
async Task<(bool, Set<B>)> Go(Set<OptionAsync<A>> ma, Func<A, B> f)
{
var rb = await Task.WhenAll(ma.Map(a => a.Map(f).Data)).ConfigureAwait(false);
return rb.Exists(d => !d.IsSome)
? (false, default)
: (true, new Set<B>(rb.Map(d => d.Value)));
}
}
public static OptionAsync<Stck<B>> Traverse<A, B>(this Stck<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Stck<B>>(Go(ma, f));
async Task<(bool, Stck<B>)> Go(Stck<OptionAsync<A>> ma, Func<A, B> f)
{
var rb = await Task.WhenAll(ma.Reverse().Map(a => a.Map(f).Data)).ConfigureAwait(false);
return rb.Exists(d => !d.IsSome)
? (false, default)
: (true, new Stck<B>(rb.Map(d => d.Value)));
}
}
//
// Async types
//
public static OptionAsync<EitherAsync<L, B>> Traverse<L, A, B>(this EitherAsync<L, OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<EitherAsync<L, B>>(Go(ma, f));
async Task<(bool, EitherAsync<L, B>)> Go(EitherAsync<L, OptionAsync<A>> ma, Func<A, B> f)
{
var da = await ma.Data.ConfigureAwait(false);
if (da.State == EitherStatus.IsBottom) return (false, default);
if (da.State == EitherStatus.IsLeft) return (true, EitherAsync<L, B>.Left(da.Left));
var (isSome, value) = await da.Right.Data.ConfigureAwait(false);
if (!isSome) return (false, default);
return (true, EitherAsync<L, B>.Right(f(value)));
}
}
public static OptionAsync<OptionAsync<B>> Traverse<A, B>(this OptionAsync<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<OptionAsync<B>>(Go(ma, f));
async Task<(bool, OptionAsync<B>)> Go(OptionAsync<OptionAsync<A>> ma, Func<A, B> f)
{
var (isSomeA, valueA) = await ma.Data.ConfigureAwait(false);
if (!isSomeA) return (true, OptionAsync<B>.None);
var (isSomeB, valueB) = await valueA.Data.ConfigureAwait(false);
if (!isSomeB) return (false, default);
return (true, OptionAsync<B>.Some(f(valueB)));
}
}
public static OptionAsync<TryAsync<B>> Traverse<A, B>(this TryAsync<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<TryAsync<B>>(Go(ma, f));
async Task<(bool, TryAsync<B>)> Go(TryAsync<OptionAsync<A>> ma, Func<A, B> f)
{
var resultA = await ma.Try().ConfigureAwait(false);
if (resultA.IsBottom) return (false, default);
if (resultA.IsFaulted) return (true, TryAsyncFail<B>(resultA.Exception));
var (isSome, value) = await resultA.Value.Data.ConfigureAwait(false);
if (!isSome) return (false, default);
return (true, TryAsync<B>(f(value)));
}
}
public static OptionAsync<TryOptionAsync<B>> Traverse<A, B>(this TryOptionAsync<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<TryOptionAsync<B>>(Go(ma, f));
async Task<(bool, TryOptionAsync<B>)> Go(TryOptionAsync<OptionAsync<A>> ma, Func<A, B> f)
{
var resultA = await ma.Try().ConfigureAwait(false);
if (resultA.IsBottom) return (false, default);
if (resultA.IsNone) return (true, TryOptionalAsync<B>(None));
if (resultA.IsFaulted) return (true, TryOptionAsyncFail<B>(resultA.Exception));
var (isSome, value) = await resultA.Value.Value.Data.ConfigureAwait(false);
if (!isSome) return (false, default);
return (true, TryOptionAsync<B>(f(value)));
}
}
public static OptionAsync<Task<B>> Traverse<A, B>(this Task<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Task<B>>(Go(ma, f));
async Task<(bool, Task<B>)> Go(Task<OptionAsync<A>> ma, Func<A, B> f)
{
var result = await ma.ConfigureAwait(false);
var (isSome, value) = await result.Data.ConfigureAwait(false);
if (!isSome) return (false, default);
return (true, f(value).AsTask());
}
}
public static OptionAsync<ValueTask<B>> Traverse<A, B>(this ValueTask<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<ValueTask<B>>(Go(ma, f).AsTask());
async ValueTask<(bool, ValueTask<B>)> Go(ValueTask<OptionAsync<A>> ma, Func<A, B> f)
{
var result = await ma.ConfigureAwait(false);
var (isSome, value) = await result.Data.ConfigureAwait(false);
if (!isSome) return (false, default);
return (true, f(value).AsValueTask());
}
}
public static OptionAsync<Aff<B>> Traverse<A, B>(this Aff<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Aff<B>>(Go(ma, f));
async Task<(bool, Aff<B>)> Go(Aff<OptionAsync<A>> ma, Func<A, B> f)
{
var resultA = await ma.Run().ConfigureAwait(false);
if (resultA.IsBottom) return (false, default);
if (resultA.IsFail) return (true, FailAff<B>(resultA.Error));
var (isSome, value) = await resultA.Value.Data.ConfigureAwait(false);
if (!isSome) return (false, default);
return (true, SuccessAff<B>(f(value)));
}
}
//
// Sync types
//
public static OptionAsync<Either<L, B>> Traverse<L, A, B>(this Either<L, OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Either<L, B>>(Go(ma, f));
async Task<(bool, Either<L, B>)> Go(Either<L, OptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsBottom) return (false, default);
if(ma.IsLeft) return (true, Left<L, B>(ma.LeftValue));
var (isSome, value) = await ma.RightValue.Data.ConfigureAwait(false);
if(!isSome) return (false, default);
return (true, f(value));
}
}
public static OptionAsync<EitherUnsafe<L, B>> Traverse<L, A, B>(this EitherUnsafe<L, OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<EitherUnsafe<L, B>>(Go(ma, f));
async Task<(bool, EitherUnsafe<L, B>)> Go(EitherUnsafe<L, OptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsBottom) return (false, default);
if(ma.IsLeft) return (true, LeftUnsafe<L, B>(ma.LeftValue));
var (isSome, value) = await ma.RightValue.Data.ConfigureAwait(false);
if(!isSome) return (false, default);
return (true, f(value));
}
}
public static OptionAsync<Identity<B>> Traverse<A, B>(this Identity<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Identity<B>>(Go(ma, f));
async Task<(bool, Identity<B>)> Go(Identity<OptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsBottom) return (false, default);
var (isSome, value) = await ma.Value.Data.ConfigureAwait(false);
if(!isSome) return (false, default);
return (true, new Identity<B>(f(value)));
}
}
public static OptionAsync<Fin<B>> Traverse<A, B>(this Fin<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Fin<B>>(Go(ma, f));
async Task<(bool, Fin<B>)> Go(Fin<OptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsFail) return (true, ma.Cast<B>());
var (isSome, value) = await ma.Value.Data.ConfigureAwait(false);
if(!isSome) return (false, default);
return (true, Fin<B>.Succ(f(value)));
}
}
public static OptionAsync<Option<B>> Traverse<A, B>(this Option<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Option<B>>(Go(ma, f));
async Task<(bool, Option<B>)> Go(Option<OptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsNone) return (true, Option<B>.None);
var (isSome, value) = await ma.Value.Data.ConfigureAwait(false);
if(!isSome) return (false, default);
return (true, Option<B>.Some(f(value)));
}
}
public static OptionAsync<OptionUnsafe<B>> Traverse<A, B>(this OptionUnsafe<OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<OptionUnsafe<B>>(Go(ma, f));
async Task<(bool, OptionUnsafe<B>)> Go(OptionUnsafe<OptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsNone) return (true, OptionUnsafe<B>.None);
var (isSome, value) = await ma.Value.Data.ConfigureAwait(false);
if(!isSome) return (false, default);
return (true, OptionUnsafe<B>.Some(f(value)));
}
}
public static OptionAsync<Try<B>> Traverse<A, B>(this Try<OptionAsync<A>> ma, Func<A, B> f)
{
try
{
return new OptionAsync<Try<B>>(Go(ma, f));
async Task<(bool, Try<B>)> Go(Try<OptionAsync<A>> ma, Func<A, B> f)
{
var ra = ma.Try();
if(ra.IsBottom) return (false, default);
if (ra.IsFaulted) return (true, TryFail<B>(ra.Exception));
var (isSome, value) = await ra.Value.Data.ConfigureAwait(false);
if(!isSome) return (false, default);
return (true, Try<B>(f(value)));
}
}
catch (Exception e)
{
return Try<B>(e);
}
}
public static OptionAsync<TryOption<B>> Traverse<A, B>(this TryOption<OptionAsync<A>> ma, Func<A, B> f)
{
try
{
return new OptionAsync<TryOption<B>>(Go(ma, f));
async Task<(bool, TryOption<B>)> Go(TryOption<OptionAsync<A>> ma, Func<A, B> f)
{
var ra = ma.Try();
if (ra.IsBottom) return (false, default);
if (ra.IsNone) return (true, TryOptional<B>(None));
if (ra.IsFaulted) return (true, TryOptionFail<B>(ra.Exception));
var (isSome, value) = await ra.Value.Value.Data.ConfigureAwait(false);
if (!isSome) return (false, default);
return (true, TryOption<B>(f(value)));
}
}
catch (Exception e)
{
return TryOption<B>(e);
}
}
public static OptionAsync<Validation<Fail, B>> Traverse<Fail, A, B>(this Validation<Fail, OptionAsync<A>> ma, Func<A, B> f)
{
return new OptionAsync<Validation<Fail, B>>(Go(ma, f));
async Task<(bool, Validation<Fail, B>)> Go(Validation<Fail, OptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsFail) return (true, Fail<Fail, B>(ma.FailValue));
var (isSome, value) = await ma.SuccessValue.Data.ConfigureAwait(false);
if(!isSome) return (false, default);
return (true, f(value));
}
}
public static OptionAsync<Validation<MonoidFail, Fail, B>> Traverse<MonoidFail, Fail, A, B>(this Validation<MonoidFail, Fail, OptionAsync<A>> ma, Func<A, B> f)
where MonoidFail : struct, Monoid<Fail>, Eq<Fail>
{
return new OptionAsync<Validation<MonoidFail, Fail, B>>(Go(ma, f));
async Task<(bool, Validation<MonoidFail, Fail, B>)> Go(Validation<MonoidFail, Fail, OptionAsync<A>> ma, Func<A, B> f)
{
if(ma.IsFail) return (true, Fail<MonoidFail, Fail, B>(ma.FailValue));
var (isSome, value) = await ma.SuccessValue.Data.ConfigureAwait(false);
if(!isSome) return (false, default);
return (true, f(value));
}
}
public static OptionAsync<Eff<B>> Traverse<A, B>(this Eff<OptionAsync<A>> ma, Func<A, B> f)
{
try
{
return new OptionAsync<Eff<B>>(Go(ma, f));
async Task<(bool, Eff<B>)> Go(Eff<OptionAsync<A>> ma, Func<A, B> f)
{
var ra = ma.Run();
if(ra.IsBottom) return (false, default);
if (ra.IsFail) return (true, FailEff<B>(ra.Error));
var (isSome, value) = await ra.Value.Data.ConfigureAwait(false);
if(!isSome) return (false, default);
return (true, SuccessEff<B>(f(value)));
}
}
catch (Exception e)
{
return FailEff<B>(e);
}
}
}
}
| |
/*
* 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.Xml;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Threading;
using log4net;
namespace OpenSim.Framework.Console
{
public delegate void CommandDelegate(string module, string[] cmd);
public class Commands
{
/// <summary>
/// Encapsulates a command that can be invoked from the console
/// </summary>
private class CommandInfo
{
/// <value>
/// The module from which this command comes
/// </value>
public string module;
/// <value>
/// Whether the module is shared
/// </value>
public bool shared;
/// <value>
/// Very short BNF description
/// </value>
public string help_text;
/// <value>
/// Longer one line help text
/// </value>
public string long_help;
/// <value>
/// Full descriptive help for this command
/// </value>
public string descriptive_help;
/// <value>
/// The method to invoke for this command
/// </value>
public List<CommandDelegate> fn;
}
/// <value>
/// Commands organized by keyword in a tree
/// </value>
private Dictionary<string, object> tree =
new Dictionary<string, object>();
/// <summary>
/// Get help for the given help string
/// </summary>
/// <param name="helpParts">Parsed parts of the help string. If empty then general help is returned.</param>
/// <returns></returns>
public List<string> GetHelp(string[] cmd)
{
List<string> help = new List<string>();
List<string> helpParts = new List<string>(cmd);
// Remove initial help keyword
helpParts.RemoveAt(0);
// General help
if (helpParts.Count == 0)
{
help.AddRange(CollectHelp(tree));
help.Sort();
}
else
{
help.AddRange(CollectHelp(helpParts));
}
return help;
}
/// <summary>
/// See if we can find the requested command in order to display longer help
/// </summary>
/// <param name="helpParts"></param>
/// <returns></returns>
private List<string> CollectHelp(List<string> helpParts)
{
string originalHelpRequest = string.Join(" ", helpParts.ToArray());
List<string> help = new List<string>();
Dictionary<string, object> dict = tree;
while (helpParts.Count > 0)
{
string helpPart = helpParts[0];
if (!dict.ContainsKey(helpPart))
break;
//m_log.Debug("Found {0}", helpParts[0]);
if (dict[helpPart] is Dictionary<string, Object>)
dict = (Dictionary<string, object>)dict[helpPart];
helpParts.RemoveAt(0);
}
// There was a command for the given help string
if (dict.ContainsKey(String.Empty))
{
CommandInfo commandInfo = (CommandInfo)dict[String.Empty];
help.Add(commandInfo.help_text);
help.Add(commandInfo.long_help);
string descriptiveHelp = commandInfo.descriptive_help;
// If we do have some descriptive help then insert a spacing line before and after for readability.
if (descriptiveHelp != string.Empty)
help.Add(string.Empty);
help.Add(commandInfo.descriptive_help);
if (descriptiveHelp != string.Empty)
help.Add(string.Empty);
}
else
{
help.Add(string.Format("No help is available for {0}", originalHelpRequest));
}
return help;
}
private List<string> CollectHelp(Dictionary<string, object> dict)
{
List<string> result = new List<string>();
foreach (KeyValuePair<string, object> kvp in dict)
{
if (kvp.Value is Dictionary<string, Object>)
{
result.AddRange(CollectHelp((Dictionary<string, Object>)kvp.Value));
}
else
{
if (((CommandInfo)kvp.Value).long_help != String.Empty)
result.Add(((CommandInfo)kvp.Value).help_text+" - "+
((CommandInfo)kvp.Value).long_help);
}
}
return result;
}
/// <summary>
/// Add a command to those which can be invoked from the console.
/// </summary>
/// <param name="module"></param>
/// <param name="command"></param>
/// <param name="help"></param>
/// <param name="longhelp"></param>
/// <param name="fn"></param>
public void AddCommand(string module, bool shared, string command,
string help, string longhelp, CommandDelegate fn)
{
AddCommand(module, shared, command, help, longhelp, String.Empty, fn);
}
/// <summary>
/// Add a command to those which can be invoked from the console.
/// </summary>
/// <param name="module"></param>
/// <param name="command"></param>
/// <param name="help"></param>
/// <param name="longhelp"></param>
/// <param name="descriptivehelp"></param>
/// <param name="fn"></param>
public void AddCommand(string module, bool shared, string command,
string help, string longhelp, string descriptivehelp,
CommandDelegate fn)
{
string[] parts = Parser.Parse(command);
Dictionary<string, Object> current = tree;
foreach (string s in parts)
{
if (current.ContainsKey(s))
{
if (current[s] is Dictionary<string, Object>)
{
current = (Dictionary<string, Object>)current[s];
}
else
return;
}
else
{
current[s] = new Dictionary<string, Object>();
current = (Dictionary<string, Object>)current[s];
}
}
CommandInfo info;
if (current.ContainsKey(String.Empty))
{
info = (CommandInfo)current[String.Empty];
if (!info.shared && !info.fn.Contains(fn))
info.fn.Add(fn);
return;
}
info = new CommandInfo();
info.module = module;
info.shared = shared;
info.help_text = help;
info.long_help = longhelp;
info.descriptive_help = descriptivehelp;
info.fn = new List<CommandDelegate>();
info.fn.Add(fn);
current[String.Empty] = info;
}
public string[] FindNextOption(string[] cmd, bool term)
{
Dictionary<string, object> current = tree;
int remaining = cmd.Length;
foreach (string s in cmd)
{
remaining--;
List<string> found = new List<string>();
foreach (string opt in current.Keys)
{
if (remaining > 0 && opt == s)
{
found.Clear();
found.Add(opt);
break;
}
if (opt.StartsWith(s))
{
found.Add(opt);
}
}
if (found.Count == 1 && (remaining != 0 || term))
{
current = (Dictionary<string, object>)current[found[0]];
}
else if (found.Count > 0)
{
return found.ToArray();
}
else
{
break;
// return new string[] {"<cr>"};
}
}
if (current.Count > 1)
{
List<string> choices = new List<string>();
bool addcr = false;
foreach (string s in current.Keys)
{
if (s == String.Empty)
{
CommandInfo ci = (CommandInfo)current[String.Empty];
if (ci.fn.Count != 0)
addcr = true;
}
else
choices.Add(s);
}
if (addcr)
choices.Add("<cr>");
return choices.ToArray();
}
if (current.ContainsKey(String.Empty))
return new string[] { "Command help: "+((CommandInfo)current[String.Empty]).help_text};
return new string[] { new List<string>(current.Keys)[0] };
}
public string[] Resolve(string[] cmd)
{
string[] result = cmd;
int index = -1;
Dictionary<string, object> current = tree;
foreach (string s in cmd)
{
index++;
List<string> found = new List<string>();
foreach (string opt in current.Keys)
{
if (opt == s)
{
found.Clear();
found.Add(opt);
break;
}
if (opt.StartsWith(s))
{
found.Add(opt);
}
}
if (found.Count == 1)
{
result[index] = found[0];
current = (Dictionary<string, object>)current[found[0]];
}
else if (found.Count > 0)
{
return new string[0];
}
else
{
break;
}
}
if (current.ContainsKey(String.Empty))
{
CommandInfo ci = (CommandInfo)current[String.Empty];
if (ci.fn.Count == 0)
return new string[0];
foreach (CommandDelegate fn in ci.fn)
{
if (fn != null)
fn(ci.module, result);
else
return new string[0];
}
return result;
}
return new string[0];
}
public XmlElement GetXml(XmlDocument doc)
{
CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty];
((Dictionary<string, object>)tree["help"]).Remove(string.Empty);
if (((Dictionary<string, object>)tree["help"]).Count == 0)
tree.Remove("help");
CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty];
((Dictionary<string, object>)tree["quit"]).Remove(string.Empty);
if (((Dictionary<string, object>)tree["quit"]).Count == 0)
tree.Remove("quit");
XmlElement root = doc.CreateElement("", "HelpTree", "");
ProcessTreeLevel(tree, root, doc);
if (!tree.ContainsKey("help"))
tree["help"] = (object) new Dictionary<string, object>();
((Dictionary<string, object>)tree["help"])[String.Empty] = help;
if (!tree.ContainsKey("quit"))
tree["quit"] = (object) new Dictionary<string, object>();
((Dictionary<string, object>)tree["quit"])[String.Empty] = quit;
return root;
}
private void ProcessTreeLevel(Dictionary<string, object> level, XmlElement xml, XmlDocument doc)
{
foreach (KeyValuePair<string, object> kvp in level)
{
if (kvp.Value is Dictionary<string, Object>)
{
XmlElement next = doc.CreateElement("", "Level", "");
next.SetAttribute("Name", kvp.Key);
xml.AppendChild(next);
ProcessTreeLevel((Dictionary<string, object>)kvp.Value, next, doc);
}
else
{
CommandInfo c = (CommandInfo)kvp.Value;
XmlElement cmd = doc.CreateElement("", "Command", "");
XmlElement e;
e = doc.CreateElement("", "Module", "");
cmd.AppendChild(e);
e.AppendChild(doc.CreateTextNode(c.module));
e = doc.CreateElement("", "Shared", "");
cmd.AppendChild(e);
e.AppendChild(doc.CreateTextNode(c.shared.ToString()));
e = doc.CreateElement("", "HelpText", "");
cmd.AppendChild(e);
e.AppendChild(doc.CreateTextNode(c.help_text));
e = doc.CreateElement("", "LongHelp", "");
cmd.AppendChild(e);
e.AppendChild(doc.CreateTextNode(c.long_help));
e = doc.CreateElement("", "Description", "");
cmd.AppendChild(e);
e.AppendChild(doc.CreateTextNode(c.descriptive_help));
xml.AppendChild(cmd);
}
}
}
public void FromXml(XmlElement root, CommandDelegate fn)
{
CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty];
((Dictionary<string, object>)tree["help"]).Remove(string.Empty);
if (((Dictionary<string, object>)tree["help"]).Count == 0)
tree.Remove("help");
CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty];
((Dictionary<string, object>)tree["quit"]).Remove(string.Empty);
if (((Dictionary<string, object>)tree["quit"]).Count == 0)
tree.Remove("quit");
tree.Clear();
ReadTreeLevel(tree, root, fn);
if (!tree.ContainsKey("help"))
tree["help"] = (object) new Dictionary<string, object>();
((Dictionary<string, object>)tree["help"])[String.Empty] = help;
if (!tree.ContainsKey("quit"))
tree["quit"] = (object) new Dictionary<string, object>();
((Dictionary<string, object>)tree["quit"])[String.Empty] = quit;
}
private void ReadTreeLevel(Dictionary<string, object> level, XmlNode node, CommandDelegate fn)
{
Dictionary<string, object> next;
string name;
XmlNodeList nodeL = node.ChildNodes;
XmlNodeList cmdL;
CommandInfo c;
foreach (XmlNode part in nodeL)
{
switch (part.Name)
{
case "Level":
name = ((XmlElement)part).GetAttribute("Name");
next = new Dictionary<string, object>();
level[name] = next;
ReadTreeLevel(next, part, fn);
break;
case "Command":
cmdL = part.ChildNodes;
c = new CommandInfo();
foreach (XmlNode cmdPart in cmdL)
{
switch (cmdPart.Name)
{
case "Module":
c.module = cmdPart.InnerText;
break;
case "Shared":
c.shared = Convert.ToBoolean(cmdPart.InnerText);
break;
case "HelpText":
c.help_text = cmdPart.InnerText;
break;
case "LongHelp":
c.long_help = cmdPart.InnerText;
break;
case "Description":
c.descriptive_help = cmdPart.InnerText;
break;
}
}
c.fn = new List<CommandDelegate>();
c.fn.Add(fn);
level[String.Empty] = c;
break;
}
}
}
}
public class Parser
{
public static string[] Parse(string text)
{
List<string> result = new List<string>();
int index;
string[] unquoted = text.Split(new char[] {'"'});
for (index = 0 ; index < unquoted.Length ; index++)
{
if (index % 2 == 0)
{
string[] words = unquoted[index].Split(new char[] {' '});
foreach (string w in words)
{
if (w != String.Empty)
result.Add(w);
}
}
else
{
result.Add(unquoted[index]);
}
}
return result.ToArray();
}
}
/// <summary>
/// A console that processes commands internally
/// </summary>
public class CommandConsole : ConsoleBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public Commands Commands = new Commands();
public CommandConsole(string defaultPrompt) : base(defaultPrompt)
{
Commands.AddCommand("console", false, "help", "help [<command>]",
"Get general command list or more detailed help on a specific command", Help);
}
private void Help(string module, string[] cmd)
{
List<string> help = Commands.GetHelp(cmd);
foreach (string s in help)
Output(s);
}
/// <summary>
/// Display a command prompt on the console and wait for user input
/// </summary>
public void Prompt()
{
string line = ReadLine(m_defaultPrompt + "# ", true, true);
if (line != String.Empty)
{
m_log.Info("[CONSOLE] Invalid command");
}
}
public void RunCommand(string cmd)
{
string[] parts = Parser.Parse(cmd);
Commands.Resolve(parts);
}
public override string ReadLine(string p, bool isCommand, bool e)
{
System.Console.Write("{0}", p);
string cmdinput = System.Console.ReadLine();
if (isCommand)
{
string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
if (cmd.Length != 0)
{
int i;
for (i=0 ; i < cmd.Length ; i++)
{
if (cmd[i].Contains(" "))
cmd[i] = "\"" + cmd[i] + "\"";
}
return String.Empty;
}
}
return cmdinput;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
///
$SSAOPostFx::overallStrength = 2.0;
// TODO: Add small/large param docs.
// The small radius SSAO settings.
$SSAOPostFx::sRadius = 0.1;
$SSAOPostFx::sStrength = 6.0;
$SSAOPostFx::sDepthMin = 0.1;
$SSAOPostFx::sDepthMax = 1.0;
$SSAOPostFx::sDepthPow = 1.0;
$SSAOPostFx::sNormalTol = 0.0;
$SSAOPostFx::sNormalPow = 1.0;
// The large radius SSAO settings.
$SSAOPostFx::lRadius = 1.0;
$SSAOPostFx::lStrength = 10.0;
$SSAOPostFx::lDepthMin = 0.2;
$SSAOPostFx::lDepthMax = 2.0;
$SSAOPostFx::lDepthPow = 0.2;
$SSAOPostFx::lNormalTol = -0.5;
$SSAOPostFx::lNormalPow = 2.0;
/// Valid values: 0, 1, 2
$SSAOPostFx::quality = 0;
///
$SSAOPostFx::blurDepthTol = 0.001;
///
$SSAOPostFx::blurNormalTol = 0.95;
///
$SSAOPostFx::targetScale = "0.5 0.5";
function SSAOPostFx::onAdd( %this )
{
%this.wasVis = "Uninitialized";
%this.quality = "Uninitialized";
}
function SSAOPostFx::preProcess( %this )
{
if ( $SSAOPostFx::quality !$= %this.quality )
{
%this.quality = mClamp( mRound( $SSAOPostFx::quality ), 0, 2 );
%this.setShaderMacro( "QUALITY", %this.quality );
}
%this.targetScale = $SSAOPostFx::targetScale;
}
function SSAOPostFx::setShaderConsts( %this )
{
%this.setShaderConst( "$overallStrength", $SSAOPostFx::overallStrength );
// Abbreviate is s-small l-large.
%this.setShaderConst( "$sRadius", $SSAOPostFx::sRadius );
%this.setShaderConst( "$sStrength", $SSAOPostFx::sStrength );
%this.setShaderConst( "$sDepthMin", $SSAOPostFx::sDepthMin );
%this.setShaderConst( "$sDepthMax", $SSAOPostFx::sDepthMax );
%this.setShaderConst( "$sDepthPow", $SSAOPostFx::sDepthPow );
%this.setShaderConst( "$sNormalTol", $SSAOPostFx::sNormalTol );
%this.setShaderConst( "$sNormalPow", $SSAOPostFx::sNormalPow );
%this.setShaderConst( "$lRadius", $SSAOPostFx::lRadius );
%this.setShaderConst( "$lStrength", $SSAOPostFx::lStrength );
%this.setShaderConst( "$lDepthMin", $SSAOPostFx::lDepthMin );
%this.setShaderConst( "$lDepthMax", $SSAOPostFx::lDepthMax );
%this.setShaderConst( "$lDepthPow", $SSAOPostFx::lDepthPow );
%this.setShaderConst( "$lNormalTol", $SSAOPostFx::lNormalTol );
%this.setShaderConst( "$lNormalPow", $SSAOPostFx::lNormalPow );
%blur = %this->blurY;
%blur.setShaderConst( "$blurDepthTol", $SSAOPostFx::blurDepthTol );
%blur.setShaderConst( "$blurNormalTol", $SSAOPostFx::blurNormalTol );
%blur = %this->blurX;
%blur.setShaderConst( "$blurDepthTol", $SSAOPostFx::blurDepthTol );
%blur.setShaderConst( "$blurNormalTol", $SSAOPostFx::blurNormalTol );
%blur = %this->blurY2;
%blur.setShaderConst( "$blurDepthTol", $SSAOPostFx::blurDepthTol );
%blur.setShaderConst( "$blurNormalTol", $SSAOPostFx::blurNormalTol );
%blur = %this->blurX2;
%blur.setShaderConst( "$blurDepthTol", $SSAOPostFx::blurDepthTol );
%blur.setShaderConst( "$blurNormalTol", $SSAOPostFx::blurNormalTol );
}
function SSAOPostFx::onEnabled( %this )
{
// This tells the AL shaders to reload and sample
// from our #ssaoMask texture target.
$AL::UseSSAOMask = true;
return true;
}
function SSAOPostFx::onDisabled( %this )
{
$AL::UseSSAOMask = false;
}
//-----------------------------------------------------------------------------
// GFXStateBlockData / ShaderData
//-----------------------------------------------------------------------------
singleton GFXStateBlockData( SSAOStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampPoint;
samplerStates[1] = SamplerWrapLinear;
samplerStates[2] = SamplerClampPoint;
};
singleton GFXStateBlockData( SSAOBlurStateBlock : PFX_DefaultStateBlock )
{
samplersDefined = true;
samplerStates[0] = SamplerClampLinear;
samplerStates[1] = SamplerClampPoint;
};
singleton ShaderData( SSAOShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/postFxV.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/SSAO_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/gl/postFxV.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/gl/SSAO_P.glsl";
samplerNames[0] = "$prepassMap";
samplerNames[1] = "$randNormalTex";
samplerNames[2] = "$powTable";
pixVersion = 3.0;
};
singleton ShaderData( SSAOBlurYShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/SSAO_Blur_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/SSAO_Blur_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/gl/SSAO_Blur_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/gl/SSAO_Blur_P.glsl";
samplerNames[0] = "$occludeMap";
samplerNames[1] = "$prepassMap";
pixVersion = 3.0;
defines = "BLUR_DIR=float2(0.0,1.0)";
};
singleton ShaderData( SSAOBlurXShader : SSAOBlurYShader )
{
defines = "BLUR_DIR=float2(1.0,0.0)";
};
//-----------------------------------------------------------------------------
// PostEffects
//-----------------------------------------------------------------------------
singleton PostEffect( SSAOPostFx )
{
allowReflectPass = false;
renderTime = "PFXBeforeBin";
renderBin = "AL_LightBinMgr";
renderPriority = 10;
shader = SSAOShader;
stateBlock = SSAOStateBlock;
texture[0] = "#prepass";
texture[1] = "core/images/noise.png";
texture[2] = "#ssao_pow_table";
target = "$outTex";
targetScale = "0.5 0.5";
targetViewport = "PFXTargetViewport_NamedInTexture0";
singleton PostEffect()
{
internalName = "blurY";
shader = SSAOBlurYShader;
stateBlock = SSAOBlurStateBlock;
texture[0] = "$inTex";
texture[1] = "#prepass";
target = "$outTex";
};
singleton PostEffect()
{
internalName = "blurX";
shader = SSAOBlurXShader;
stateBlock = SSAOBlurStateBlock;
texture[0] = "$inTex";
texture[1] = "#prepass";
target = "$outTex";
};
singleton PostEffect()
{
internalName = "blurY2";
shader = SSAOBlurYShader;
stateBlock = SSAOBlurStateBlock;
texture[0] = "$inTex";
texture[1] = "#prepass";
target = "$outTex";
};
singleton PostEffect()
{
internalName = "blurX2";
shader = SSAOBlurXShader;
stateBlock = SSAOBlurStateBlock;
texture[0] = "$inTex";
texture[1] = "#prepass";
// We write to a mask texture which is then
// read by the lighting shaders to mask ambient.
target = "#ssaoMask";
};
};
/// Just here for debug visualization of the
/// SSAO mask texture used during lighting.
singleton PostEffect( SSAOVizPostFx )
{
allowReflectPass = false;
shader = PFX_PassthruShader;
stateBlock = PFX_DefaultStateBlock;
texture[0] = "#ssaoMask";
target = "$backbuffer";
};
singleton ShaderData( SSAOPowTableShader )
{
DXVertexShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/SSAO_PowerTable_V.hlsl";
DXPixelShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/SSAO_PowerTable_P.hlsl";
OGLVertexShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/gl/SSAO_PowerTable_V.glsl";
OGLPixelShaderFile = $Core::CommonShaderPath @ "/postFX/ssao/gl/SSAO_PowerTable_P.glsl";
pixVersion = 2.0;
};
singleton PostEffect( SSAOPowTablePostFx )
{
shader = SSAOPowTableShader;
stateBlock = PFX_DefaultStateBlock;
renderTime = "PFXTexGenOnDemand";
target = "#ssao_pow_table";
targetFormat = "GFXFormatR16F";
targetSize = "256 1";
};
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Semantics;
namespace System.Runtime.Analyzers
{
/// <summary>
/// CA1816: Dispose methods should call SuppressFinalize
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class CallGCSuppressFinalizeCorrectlyAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1816";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.CallGCSuppressFinalizeCorrectlyTitle), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNotCalledWithFinalizer = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.CallGCSuppressFinalizeCorrectlyMessageNotCalledWithFinalizer), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNotCalled = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.CallGCSuppressFinalizeCorrectlyMessageNotCalled), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNotPassedThis = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.CallGCSuppressFinalizeCorrectlyMessageNotPassedThis), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableMessageOutsideDispose = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.CallGCSuppressFinalizeCorrectlyMessageOutsideDispose), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.CallGCSuppressFinalizeCorrectlyDescription), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
internal static DiagnosticDescriptor NotCalledWithFinalizerRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageNotCalledWithFinalizer,
DiagnosticCategory.Usage,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: "https://msdn.microsoft.com/en-US/library/ms182269.aspx",
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor NotCalledRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageNotCalled,
DiagnosticCategory.Usage,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: "https://msdn.microsoft.com/en-US/library/ms182269.aspx",
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor NotPassedThisRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageNotPassedThis,
DiagnosticCategory.Usage,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: "https://msdn.microsoft.com/en-US/library/ms182269.aspx",
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor OutsideDisposeRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageOutsideDispose,
DiagnosticCategory.Usage,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: true,
description: s_localizableDescription,
helpLinkUri: "https://msdn.microsoft.com/en-US/library/ms182269.aspx",
customTags: WellKnownDiagnosticTags.Telemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(NotCalledWithFinalizerRule, NotCalledRule, NotPassedThisRule, OutsideDisposeRule);
public override void Initialize(AnalysisContext analysisContext)
{
// TODO: Make analyzer thread safe.
//analysisContext.EnableConcurrentExecution();
analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
analysisContext.RegisterCompilationStartAction(compilationContext =>
{
var gcSuppressFinalizeMethodSymbol = compilationContext.Compilation
.GetTypeByMetadataName("System.GC")
?.GetMembers("SuppressFinalize")
.OfType<IMethodSymbol>()
.SingleOrDefault();
if (gcSuppressFinalizeMethodSymbol == null)
{
return;
}
compilationContext.RegisterOperationBlockStartActionInternal(operationBlockContext =>
{
if (operationBlockContext.OwningSymbol.Kind != SymbolKind.Method)
{
return;
}
var methodSymbol = (IMethodSymbol)operationBlockContext.OwningSymbol;
if (methodSymbol.IsExtern || methodSymbol.IsAbstract)
{
return;
}
var analyzer = new SuppressFinalizeAnalyzer(methodSymbol, gcSuppressFinalizeMethodSymbol, compilationContext.Compilation);
operationBlockContext.RegisterOperationActionInternal(analyzer.Analyze, OperationKind.InvocationExpression);
operationBlockContext.RegisterOperationBlockEndAction(analyzer.OperationBlockEndAction);
});
});
}
private class SuppressFinalizeAnalyzer
{
private enum SuppressFinalizeUsage
{
CanCall,
MustCall,
MustNotCall
}
private readonly Compilation _compilation;
private readonly IMethodSymbol _containingMethodSymbol;
private readonly IMethodSymbol _gcSuppressFinalizeMethodSymbol;
private readonly SuppressFinalizeUsage _expectedUsage;
private bool _suppressFinalizeCalled;
private SemanticModel _semanticModel;
public SuppressFinalizeAnalyzer(IMethodSymbol methodSymbol, IMethodSymbol gcSuppressFinalizeMethodSymbol, Compilation compilation)
{
this._compilation = compilation;
this._containingMethodSymbol = methodSymbol;
this._gcSuppressFinalizeMethodSymbol = gcSuppressFinalizeMethodSymbol;
this._expectedUsage = GetAllowedSuppressFinalizeUsage(_containingMethodSymbol);
}
public void Analyze(OperationAnalysisContext analysisContext)
{
var invocationExpression = (IInvocationExpression)analysisContext.Operation;
if (invocationExpression.TargetMethod.OriginalDefinition.Equals(_gcSuppressFinalizeMethodSymbol))
{
_suppressFinalizeCalled = true;
if (_semanticModel == null)
{
_semanticModel = analysisContext.Compilation.GetSemanticModel(analysisContext.Operation.Syntax.SyntaxTree);
}
// Check for GC.SuppressFinalize outside of IDisposable.Dispose()
if (_expectedUsage == SuppressFinalizeUsage.MustNotCall)
{
analysisContext.ReportDiagnostic(invocationExpression.Syntax.CreateDiagnostic(
OutsideDisposeRule,
_containingMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
_gcSuppressFinalizeMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
}
// Checks for GC.SuppressFinalize(this)
if (invocationExpression.ArgumentsInSourceOrder.Count() != 1)
{
return;
}
var parameterSymbol = _semanticModel.GetSymbolInfo(invocationExpression.ArgumentsInSourceOrder.Single().Syntax).Symbol as IParameterSymbol;
if (parameterSymbol == null || !parameterSymbol.IsThis)
{
analysisContext.ReportDiagnostic(invocationExpression.Syntax.CreateDiagnostic(
NotPassedThisRule,
_containingMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
_gcSuppressFinalizeMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
}
}
}
public void OperationBlockEndAction(OperationBlockAnalysisContext context)
{
// Check for absence of GC.SuppressFinalize
if (!_suppressFinalizeCalled && _expectedUsage == SuppressFinalizeUsage.MustCall)
{
var descriptor = _containingMethodSymbol.ContainingType.HasFinalizer() ? NotCalledWithFinalizerRule : NotCalledRule;
context.ReportDiagnostic(_containingMethodSymbol.CreateDiagnostic(
descriptor,
_containingMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
_gcSuppressFinalizeMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
}
}
private SuppressFinalizeUsage GetAllowedSuppressFinalizeUsage(IMethodSymbol method)
{
// We allow constructors in sealed types to call GC.SuppressFinalize.
// This allows types that derive from Component (such SqlConnection)
// to prevent the finalizer they inherit from Component from ever
// being called.
if (method.ContainingType.IsSealed && method.IsConstructor() && !method.IsStatic)
{
return SuppressFinalizeUsage.CanCall;
}
if (!method.IsDisposeImplementation(_compilation))
{
return SuppressFinalizeUsage.MustNotCall;
}
// If the Dispose method is declared in a sealed type, we do
// not require that the method calls GC.SuppressFinalize
var hasFinalizer = method.ContainingType.HasFinalizer();
if (method.ContainingType.IsSealed && !hasFinalizer)
{
return SuppressFinalizeUsage.CanCall;
}
// We don't require that non-public types call GC.SuppressFinalize
// if they don't have a finalizer as the owner of the assembly can
// control whether any finalizable types derive from them.
if (method.ContainingType.DeclaredAccessibility != Accessibility.Public && !hasFinalizer)
{
return SuppressFinalizeUsage.CanCall;
}
// Even if the Dispose method is declared on a type without a
// finalizer, we still require it to call GC.SuppressFinalize to
// prevent derived finalizable types from having to reimplement
// IDisposable.Dispose just to call it.
return SuppressFinalizeUsage.MustCall;
}
}
}
}
| |
namespace DeOps.Services.Board
{
partial class PostMessage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.LinkAdd = new System.Windows.Forms.LinkLabel();
this.LinkRemove = new System.Windows.Forms.LinkLabel();
this.ListFiles = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.ExitButton = new System.Windows.Forms.Button();
this.PostButton = new System.Windows.Forms.Button();
this.MessageBody = new DeOps.Interface.TextInput();
this.SubjectTextBox = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.ScopeLabel = new System.Windows.Forms.Label();
this.ScopeHigh = new System.Windows.Forms.RadioButton();
this.ScopeLow = new System.Windows.Forms.RadioButton();
this.ScopeAll = new System.Windows.Forms.RadioButton();
this.SuspendLayout();
//
// LinkAdd
//
this.LinkAdd.ActiveLinkColor = System.Drawing.Color.Blue;
this.LinkAdd.AutoSize = true;
this.LinkAdd.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LinkAdd.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.LinkAdd.Location = new System.Drawing.Point(56, 40);
this.LinkAdd.Name = "LinkAdd";
this.LinkAdd.Size = new System.Drawing.Size(26, 13);
this.LinkAdd.TabIndex = 32;
this.LinkAdd.TabStop = true;
this.LinkAdd.Text = "Add";
this.LinkAdd.VisitedLinkColor = System.Drawing.Color.Blue;
this.LinkAdd.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkAdd_LinkClicked);
//
// LinkRemove
//
this.LinkRemove.ActiveLinkColor = System.Drawing.Color.Blue;
this.LinkRemove.AutoSize = true;
this.LinkRemove.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LinkRemove.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.LinkRemove.Location = new System.Drawing.Point(81, 40);
this.LinkRemove.Name = "LinkRemove";
this.LinkRemove.Size = new System.Drawing.Size(46, 13);
this.LinkRemove.TabIndex = 31;
this.LinkRemove.TabStop = true;
this.LinkRemove.Text = "Remove";
this.LinkRemove.VisitedLinkColor = System.Drawing.Color.Blue;
this.LinkRemove.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkRemove_LinkClicked);
//
// ListFiles
//
this.ListFiles.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.ListFiles.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.ListFiles.FormattingEnabled = true;
this.ListFiles.Location = new System.Drawing.Point(133, 37);
this.ListFiles.Name = "ListFiles";
this.ListFiles.Size = new System.Drawing.Size(253, 21);
this.ListFiles.TabIndex = 30;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(3, 40);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(32, 13);
this.label4.TabIndex = 29;
this.label4.Text = "Files";
//
// ExitButton
//
this.ExitButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.ExitButton.Location = new System.Drawing.Point(315, 313);
this.ExitButton.Name = "ExitButton";
this.ExitButton.Size = new System.Drawing.Size(75, 23);
this.ExitButton.TabIndex = 28;
this.ExitButton.Text = "Cancel";
this.ExitButton.UseVisualStyleBackColor = true;
this.ExitButton.Click += new System.EventHandler(this.CancelButton_Click);
//
// PostButton
//
this.PostButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.PostButton.Location = new System.Drawing.Point(234, 313);
this.PostButton.Name = "PostButton";
this.PostButton.Size = new System.Drawing.Size(75, 23);
this.PostButton.TabIndex = 27;
this.PostButton.Text = "Post";
this.PostButton.UseVisualStyleBackColor = true;
this.PostButton.Click += new System.EventHandler(this.PostButton_Click);
//
// MessageBody
//
this.MessageBody.AcceptTabs = true;
this.MessageBody.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.MessageBody.EnterClears = false;
this.MessageBody.IMButtons = false;
this.MessageBody.Location = new System.Drawing.Point(6, 68);
this.MessageBody.Name = "MessageBody";
this.MessageBody.PlainTextMode = true;
this.MessageBody.ReadOnly = false;
this.MessageBody.ShowFontStrip = true;
this.MessageBody.Size = new System.Drawing.Size(384, 239);
this.MessageBody.TabIndex = 26;
//
// SubjectTextBox
//
this.SubjectTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.SubjectTextBox.Location = new System.Drawing.Point(59, 7);
this.SubjectTextBox.Name = "SubjectTextBox";
this.SubjectTextBox.Size = new System.Drawing.Size(327, 20);
this.SubjectTextBox.TabIndex = 25;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(3, 10);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(50, 13);
this.label3.TabIndex = 24;
this.label3.Text = "Subject";
//
// ScopeLabel
//
this.ScopeLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.ScopeLabel.AutoSize = true;
this.ScopeLabel.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ScopeLabel.Location = new System.Drawing.Point(3, 318);
this.ScopeLabel.Name = "ScopeLabel";
this.ScopeLabel.Size = new System.Drawing.Size(41, 13);
this.ScopeLabel.TabIndex = 33;
this.ScopeLabel.Text = "Scope";
//
// ScopeHigh
//
this.ScopeHigh.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.ScopeHigh.AutoSize = true;
this.ScopeHigh.Location = new System.Drawing.Point(92, 316);
this.ScopeHigh.Name = "ScopeHigh";
this.ScopeHigh.Size = new System.Drawing.Size(47, 17);
this.ScopeHigh.TabIndex = 34;
this.ScopeHigh.Text = "High";
this.ScopeHigh.UseVisualStyleBackColor = true;
//
// ScopeLow
//
this.ScopeLow.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.ScopeLow.AutoSize = true;
this.ScopeLow.Location = new System.Drawing.Point(145, 316);
this.ScopeLow.Name = "ScopeLow";
this.ScopeLow.Size = new System.Drawing.Size(45, 17);
this.ScopeLow.TabIndex = 35;
this.ScopeLow.Text = "Low";
this.ScopeLow.UseVisualStyleBackColor = true;
//
// ScopeAll
//
this.ScopeAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.ScopeAll.AutoSize = true;
this.ScopeAll.Checked = true;
this.ScopeAll.Location = new System.Drawing.Point(50, 316);
this.ScopeAll.Name = "ScopeAll";
this.ScopeAll.Size = new System.Drawing.Size(36, 17);
this.ScopeAll.TabIndex = 36;
this.ScopeAll.TabStop = true;
this.ScopeAll.Text = "All";
this.ScopeAll.UseVisualStyleBackColor = true;
//
// PostMessage
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.ScopeAll);
this.Controls.Add(this.ScopeLow);
this.Controls.Add(this.ScopeHigh);
this.Controls.Add(this.ScopeLabel);
this.Controls.Add(this.LinkAdd);
this.Controls.Add(this.LinkRemove);
this.Controls.Add(this.ListFiles);
this.Controls.Add(this.label4);
this.Controls.Add(this.ExitButton);
this.Controls.Add(this.PostButton);
this.Controls.Add(this.MessageBody);
this.Controls.Add(this.SubjectTextBox);
this.Controls.Add(this.label3);
this.DoubleBuffered = true;
this.Name = "PostMessage";
this.Size = new System.Drawing.Size(393, 339);
this.Load += new System.EventHandler(this.PostMessage_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.LinkLabel LinkAdd;
private System.Windows.Forms.LinkLabel LinkRemove;
private System.Windows.Forms.ComboBox ListFiles;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button ExitButton;
private System.Windows.Forms.Button PostButton;
public DeOps.Interface.TextInput MessageBody;
public System.Windows.Forms.TextBox SubjectTextBox;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label ScopeLabel;
private System.Windows.Forms.RadioButton ScopeHigh;
private System.Windows.Forms.RadioButton ScopeLow;
private System.Windows.Forms.RadioButton ScopeAll;
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Types;
#if !FEATURE_NUMERICS
using Microsoft.Scripting.Math;
using Complex = Microsoft.Scripting.Math.Complex64;
#else
using System.Numerics;
#endif
namespace IronPython.Runtime.Operations {
public class ExtensibleComplex : Extensible<Complex> {
public ExtensibleComplex() : base() { }
public ExtensibleComplex(double real) : base(MathUtils.MakeReal(real)) { }
public ExtensibleComplex(double real, double imag) : base(new Complex(real, imag)) { }
}
public static partial class ComplexOps {
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls) {
if (cls == TypeCache.Complex) return new Complex();
return cls.CreateInstance(context);
}
[StaticExtensionMethod]
public static object __new__(
CodeContext context,
PythonType cls,
[DefaultParameterValue(null)]object real,
[DefaultParameterValue(null)]object imag
) {
Complex real2, imag2;
real2 = imag2 = new Complex();
if (real == null && imag == null && cls == TypeCache.Complex) throw PythonOps.TypeError("argument must be a string or a number");
if (imag != null) {
if (real is string) throw PythonOps.TypeError("complex() can't take second arg if first is a string");
if (imag is string) throw PythonOps.TypeError("complex() second arg can't be a string");
imag2 = Converter.ConvertToComplex(imag);
}
if (real != null) {
if (real is string) {
real2 = LiteralParser.ParseComplex((string)real);
} else if (real is Extensible<string>) {
real2 = LiteralParser.ParseComplex(((Extensible<string>)real).Value);
} else if (real is Complex) {
if (imag == null && cls == TypeCache.Complex) return real;
else real2 = (Complex)real;
} else {
real2 = Converter.ConvertToComplex(real);
}
}
double real3 = real2.Real - imag2.Imaginary();
double imag3 = real2.Imaginary() + imag2.Real;
if (cls == TypeCache.Complex) {
return new Complex(real3, imag3);
} else {
return cls.CreateInstance(context, real3, imag3);
}
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls, double real) {
if (cls == TypeCache.Complex) {
return new Complex(real, 0.0);
} else {
return cls.CreateInstance(context, real, 0.0);
}
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls, double real, double imag) {
if (cls == TypeCache.Complex) {
return new Complex(real, imag);
} else {
return cls.CreateInstance(context, real, imag);
}
}
[SpecialName, PropertyMethod]
public static double Getreal(Complex self) {
return self.Real;
}
[SpecialName, PropertyMethod]
public static double Getimag(Complex self) {
return self.Imaginary();
}
#region Binary operators
[SpecialName]
public static Complex Add(Complex x, Complex y) {
return x + y;
}
[SpecialName]
public static Complex Subtract(Complex x, Complex y) {
return x - y;
}
[SpecialName]
public static Complex Multiply(Complex x, Complex y) {
return x * y;
}
[SpecialName]
public static Complex Divide(Complex x, Complex y) {
if (y.IsZero()) {
throw new DivideByZeroException("complex division by zero");
}
return x / y;
}
[SpecialName]
public static Complex TrueDivide(Complex x, Complex y) {
return Divide(x, y);
}
[SpecialName]
public static Complex op_Power(Complex x, Complex y) {
if (x.IsZero()) {
if (y.Real < 0.0 || y.Imaginary() != 0.0) {
throw PythonOps.ZeroDivisionError("0.0 to a negative or complex power");
}
return y.IsZero() ? Complex.One : Complex.Zero;
}
#if FEATURE_NUMERICS
// Special case for higher precision with real integer powers
// TODO: A similar check may get added to CLR 4 upon resolution of Dev10 bug 863171,
// in which case this code should go away.
if (y.Imaginary == 0.0) {
int power = (int)y.Real;
if (power >= 0 && y.Real == power) {
Complex res = Complex.One;
if (power == 0) {
return res;
}
Complex factor = x;
while (power != 0) {
if ((power & 1) != 0) {
res = res * factor;
}
factor = factor * factor;
power >>= 1;
}
return res;
}
}
#endif
return x.Pow(y);
}
[PythonHidden]
public static Complex Power(Complex x, Complex y) {
return op_Power(x, y);
}
// floordiv for complex numbers is deprecated in the Python 2.
// specification; this function implements the observable
// functionality in CPython 2.4:
// Let x, y be complex.
// Re(x//y) := floor(Re(x/y))
// Im(x//y) := 0
[SpecialName]
public static Complex FloorDivide(CodeContext context, Complex x, Complex y) {
PythonOps.Warn(context, PythonExceptions.DeprecationWarning, "complex divmod(), // and % are deprecated");
Complex quotient = Divide(x, y);
return MathUtils.MakeReal(PythonOps.CheckMath(Math.Floor(quotient.Real)));
}
// mod for complex numbers is also deprecated. IronPython
// implements the CPython semantics, that is:
// x % y = x - (y * (x//y)).
[SpecialName]
public static Complex Mod(CodeContext context, Complex x, Complex y) {
Complex quotient = FloorDivide(context, x, y);
return x - (quotient * y);
}
[SpecialName]
public static PythonTuple DivMod(CodeContext context, Complex x, Complex y) {
Complex quotient = FloorDivide(context, x, y);
return PythonTuple.MakeTuple(quotient, x - (quotient * y));
}
#endregion
#region Unary operators
public static int __hash__(Complex x) {
if (x.Imaginary() == 0) {
return DoubleOps.__hash__(x.Real);
}
return x.GetHashCode();
}
public static bool __nonzero__(Complex x) {
return !x.IsZero();
}
public static Complex conjugate(Complex x) {
return x.Conjugate();
}
public static object __getnewargs__(CodeContext context, Complex self) {
#if CLR2
if (!Object.ReferenceEquals(self, null)) {
#endif
return PythonTuple.MakeTuple(
PythonOps.GetBoundAttr(context, self, "real"),
PythonOps.GetBoundAttr(context, self, "imag")
);
#if CLR2
}
throw PythonOps.TypeErrorForBadInstance("__getnewargs__ requires a 'complex' object but received a '{0}'", self);
#endif
}
#if !CLR2
public static object __pos__(Complex x) {
return x;
}
#endif
#endregion
public static object __coerce__(Complex x, object y) {
Complex right;
if (Converter.TryConvertToComplex(y, out right)) {
#if !CLR2
if (double.IsInfinity(right.Real) && (y is BigInteger || y is Extensible<BigInteger>)) {
throw new OverflowException("long int too large to convert to float");
}
#endif
return PythonTuple.MakeTuple(x, right);
}
return NotImplementedType.Value;
}
public static string __str__(CodeContext/*!*/ context, Complex x) {
if (x.Real != 0) {
if (x.Imaginary() < 0 || DoubleOps.IsNegativeZero(x.Imaginary())) {
return "(" + FormatComplexValue(context, x.Real) + FormatComplexValue(context, x.Imaginary()) + "j)";
} else /* x.Imaginary() is NaN or >= +0.0 */ {
return "(" + FormatComplexValue(context, x.Real) + "+" + FormatComplexValue(context, x.Imaginary()) + "j)";
}
}
return FormatComplexValue(context, x.Imaginary()) + "j";
}
public static string __repr__(CodeContext/*!*/ context, Complex x) {
return __str__(context, x);
}
// report the same errors as CPython for these invalid conversions
public static double __float__(Complex self) {
throw PythonOps.TypeError("can't convert complex to float; use abs(z)");
}
public static int __int__(Complex self) {
throw PythonOps.TypeError(" can't convert complex to int; use int(abs(z))");
}
public static BigInteger __long__(Complex self) {
throw PythonOps.TypeError("can't convert complex to long; use long(abs(z))");
}
private static string FormatComplexValue(CodeContext/*!*/ context, double x) {
StringFormatter sf = new StringFormatter(context, "%.6g", x);
return sf.Format();
}
// Unary Operations
[SpecialName]
public static double Abs(Complex x) {
double res = x.Abs();
if (double.IsInfinity(res) && !double.IsInfinity(x.Real) && !double.IsInfinity(x.Imaginary())) {
throw PythonOps.OverflowError("absolute value too large");
}
return res;
}
// Binary Operations - Comparisons (eq & ne defined on Complex type as operators)
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "y"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "x"), SpecialName]
public static bool LessThan(Complex x, Complex y) {
throw PythonOps.TypeError("complex is not an ordered type");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "y"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "x"), SpecialName]
public static bool LessThanOrEqual(Complex x, Complex y) {
throw PythonOps.TypeError("complex is not an ordered type");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "x"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "y"), SpecialName]
public static bool GreaterThan(Complex x, Complex y) {
throw PythonOps.TypeError("complex is not an ordered type");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "y"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "x"), SpecialName]
public static bool GreaterThanOrEqual(Complex x, Complex y) {
throw PythonOps.TypeError("complex is not an ordered type");
}
}
}
| |
// 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.PetstoreV2AllSync
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SwaggerPetstoreV2.
/// </summary>
public static partial class SwaggerPetstoreV2Extensions
{
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
public static Pet AddPet(this ISwaggerPetstoreV2 operations, Pet body)
{
return operations.AddPetAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Pet> AddPetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<Pet> AddPetWithHttpMessages(this ISwaggerPetstoreV2 operations, Pet body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.AddPetWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
public static void UpdatePet(this ISwaggerPetstoreV2 operations, Pet body)
{
operations.UpdatePetAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePetAsync(this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse UpdatePetWithHttpMessages(this ISwaggerPetstoreV2 operations, Pet body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.UpdatePetWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
public static IList<Pet> FindPetsByStatus(this ISwaggerPetstoreV2 operations, IList<string> status)
{
return operations.FindPetsByStatusAsync(status).GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstoreV2 operations, IList<string> status, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<IList<Pet>> FindPetsByStatusWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<string> status, Dictionary<string, List<string>> customHeaders = null)
{
return operations.FindPetsByStatusWithHttpMessagesAsync(status, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
public static IList<Pet> FindPetsByTags(this ISwaggerPetstoreV2 operations, IList<string> tags)
{
return operations.FindPetsByTagsAsync(tags).GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstoreV2 operations, IList<string> tags, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<IList<Pet>> FindPetsByTagsWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<string> tags, Dictionary<string, List<string>> customHeaders = null)
{
return operations.FindPetsByTagsWithHttpMessagesAsync(tags, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet to return
/// </param>
public static Pet GetPetById(this ISwaggerPetstoreV2 operations, long petId)
{
return operations.GetPetByIdAsync(petId).GetAwaiter().GetResult();
}
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet to return
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Pet> GetPetByIdAsync(this ISwaggerPetstoreV2 operations, long petId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet to return
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<Pet> GetPetByIdWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, Dictionary<string, List<string>> customHeaders = null)
{
return operations.GetPetByIdWithHttpMessagesAsync(petId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
public static void UpdatePetWithForm(this ISwaggerPetstoreV2 operations, long petId, Stream fileContent, string fileName = default(string), string status = default(string))
{
operations.UpdatePetWithFormAsync(petId, fileContent, fileName, status).GetAwaiter().GetResult();
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdatePetWithFormAsync(this ISwaggerPetstoreV2 operations, long petId, Stream fileContent, string fileName = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse UpdatePetWithFormWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, Stream fileContent, string fileName = default(string), string status = default(string), Dictionary<string, List<string>> customHeaders = null)
{
return operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
public static void DeletePet(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "")
{
operations.DeletePetAsync(petId, apiKey).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeletePetAsync(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse DeletePetWithHttpMessages(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", Dictionary<string, List<string>> customHeaders = null)
{
return operations.DeletePetWithHttpMessagesAsync(petId, apiKey, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IDictionary<string, int?> GetInventory(this ISwaggerPetstoreV2 operations)
{
return operations.GetInventoryAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<IDictionary<string, int?>> GetInventoryWithHttpMessages(this ISwaggerPetstoreV2 operations, Dictionary<string, List<string>> customHeaders = null)
{
return operations.GetInventoryWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
public static Order PlaceOrder(this ISwaggerPetstoreV2 operations, Order body)
{
return operations.PlaceOrderAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Order> PlaceOrderAsync(this ISwaggerPetstoreV2 operations, Order body, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<Order> PlaceOrderWithHttpMessages(this ISwaggerPetstoreV2 operations, Order body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.PlaceOrderWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
public static Order GetOrderById(this ISwaggerPetstoreV2 operations, string orderId)
{
return operations.GetOrderByIdAsync(orderId).GetAwaiter().GetResult();
}
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Order> GetOrderByIdAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<Order> GetOrderByIdWithHttpMessages(this ISwaggerPetstoreV2 operations, string orderId, Dictionary<string, List<string>> customHeaders = null)
{
return operations.GetOrderByIdWithHttpMessagesAsync(orderId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
public static void DeleteOrder(this ISwaggerPetstoreV2 operations, string orderId)
{
operations.DeleteOrderAsync(orderId).GetAwaiter().GetResult();
}
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteOrderAsync(this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse DeleteOrderWithHttpMessages(this ISwaggerPetstoreV2 operations, string orderId, Dictionary<string, List<string>> customHeaders = null)
{
return operations.DeleteOrderWithHttpMessagesAsync(orderId, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
public static void CreateUser(this ISwaggerPetstoreV2 operations, User body)
{
operations.CreateUserAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUserAsync(this ISwaggerPetstoreV2 operations, User body, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse CreateUserWithHttpMessages(this ISwaggerPetstoreV2 operations, User body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.CreateUserWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
public static void CreateUsersWithArrayInput(this ISwaggerPetstoreV2 operations, IList<User> body)
{
operations.CreateUsersWithArrayInputAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUsersWithArrayInputAsync(this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse CreateUsersWithArrayInputWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<User> body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
public static void CreateUsersWithListInput(this ISwaggerPetstoreV2 operations, IList<User> body)
{
operations.CreateUsersWithListInputAsync(body).GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task CreateUsersWithListInputAsync(this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse CreateUsersWithListInputWithHttpMessages(this ISwaggerPetstoreV2 operations, IList<User> body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.CreateUsersWithListInputWithHttpMessagesAsync(body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
public static string LoginUser(this ISwaggerPetstoreV2 operations, string username, string password)
{
return operations.LoginUserAsync(username, password).GetAwaiter().GetResult();
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<string> LoginUserAsync(this ISwaggerPetstoreV2 operations, string username, string password, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<string,LoginUserHeaders> LoginUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, string password, Dictionary<string, List<string>> customHeaders = null)
{
return operations.LoginUserWithHttpMessagesAsync(username, password, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void LogoutUser(this ISwaggerPetstoreV2 operations)
{
operations.LogoutUserAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task LogoutUserAsync(this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse LogoutUserWithHttpMessages(this ISwaggerPetstoreV2 operations, Dictionary<string, List<string>> customHeaders = null)
{
return operations.LogoutUserWithHttpMessagesAsync(customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
public static User GetUserByName(this ISwaggerPetstoreV2 operations, string username)
{
return operations.GetUserByNameAsync(username).GetAwaiter().GetResult();
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<User> GetUserByNameAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse<User> GetUserByNameWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, Dictionary<string, List<string>> customHeaders = null)
{
return operations.GetUserByNameWithHttpMessagesAsync(username, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
public static void UpdateUser(this ISwaggerPetstoreV2 operations, string username, User body)
{
operations.UpdateUserAsync(username, body).GetAwaiter().GetResult();
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateUserAsync(this ISwaggerPetstoreV2 operations, string username, User body, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse UpdateUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, User body, Dictionary<string, List<string>> customHeaders = null)
{
return operations.UpdateUserWithHttpMessagesAsync(username, body, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
public static void DeleteUser(this ISwaggerPetstoreV2 operations, string username)
{
operations.DeleteUserAsync(username).GetAwaiter().GetResult();
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteUserAsync(this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
public static HttpOperationResponse DeleteUserWithHttpMessages(this ISwaggerPetstoreV2 operations, string username, Dictionary<string, List<string>> customHeaders = null)
{
return operations.DeleteUserWithHttpMessagesAsync(username, customHeaders, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
namespace RtmNet
{
/// <summary>
/// Internal class providing certain utility functions to other classes.
/// </summary>
internal sealed class Utils
{
private static readonly DateTime unixStartDate = new DateTime(1970, 1, 1, 0, 0, 0);
private Utils()
{
}
#if !WindowsCE
internal static string UrlEncode(string oldString)
{
if( oldString == null ) return null;
string a = System.Web.HttpUtility.UrlEncode(oldString);
a = a.Replace("&", "%26");
a = a.Replace("=", "%3D");
a = a.Replace(" ", "%20");
return a;
}
#else
internal static string UrlEncode(string oldString)
{
if (oldString == null) return String.Empty;
StringBuilder sb = new StringBuilder(oldString.Length * 2);
Regex reg = new Regex("[a-zA-Z0-9$-_.+!*'(),]");
foreach (char c in oldString)
{
if (reg.IsMatch(c.ToString()))
{
sb.Append(c);
}
else
{
sb.Append(ToHex(c));
}
}
return sb.ToString();
}
private static string ToHex(char c)
{
return ((int)c).ToString("X");
}
#endif
/// <summary>
/// Converts a <see cref="DateTime"/> object into a unix timestamp number.
/// </summary>
/// <param name="date">The date to convert.</param>
/// <returns>A long for the number of seconds since 1st January 1970, as per unix specification.</returns>
internal static long DateToUnixTimestamp(DateTime date)
{
TimeSpan ts = date - unixStartDate;
return (long)ts.TotalSeconds;
}
/// <summary>
/// Converts a string, representing a unix timestamp number into a <see cref="DateTime"/> object.
/// </summary>
/// <param name="timestamp">The timestamp, as a string.</param>
/// <returns>The <see cref="DateTime"/> object the time represents.</returns>
internal static DateTime UnixTimestampToDate(string timestamp)
{
if( timestamp == null || timestamp.Length == 0 ) return DateTime.MinValue;
return UnixTimestampToDate(long.Parse(timestamp));
}
/// <summary>
/// Converts a <see cref="long"/>, representing a unix timestamp number into a <see cref="DateTime"/> object.
/// </summary>
/// <param name="timestamp">The unix timestamp.</param>
/// <returns>The <see cref="DateTime"/> object the time represents.</returns>
internal static DateTime UnixTimestampToDate(long timestamp)
{
return unixStartDate.AddSeconds(timestamp);
}
internal static DateTime DateStringToDateTime(string timestring)
{
if (timestring == null | timestring.Length == 0) return DateTime.MinValue;
DateTime dt = DateTime.Parse(timestring);
return dt;
}
internal static void WriteInt32(Stream s, int i)
{
s.WriteByte((byte) (i & 0xFF));
s.WriteByte((byte) ((i >> 8) & 0xFF));
s.WriteByte((byte) ((i >> 16) & 0xFF));
s.WriteByte((byte) ((i >> 24) & 0xFF));
}
internal static void WriteString(Stream s, string str)
{
WriteInt32(s, str.Length);
foreach (char c in str)
{
s.WriteByte((byte) (c & 0xFF));
s.WriteByte((byte) ((c >> 8) & 0xFF));
}
}
internal static void WriteAsciiString(Stream s, string str)
{
WriteInt32(s, str.Length);
foreach (char c in str)
{
s.WriteByte((byte) (c & 0x7F));
}
}
internal static int ReadInt32(Stream s)
{
int i = 0, b;
for (int j = 0; j < 4; j++)
{
b = s.ReadByte();
if (b == -1)
throw new IOException("Unexpected EOF encountered");
i |= (b << (j * 8));
}
return i;
}
internal static string ReadString(Stream s)
{
int len = ReadInt32(s);
char[] chars = new char[len];
for (int i = 0; i < len; i++)
{
int hi, lo;
lo = s.ReadByte();
hi = s.ReadByte();
if (lo == -1 || hi == -1)
throw new IOException("Unexpected EOF encountered");
chars[i] = (char) (lo | (hi << 8));
}
return new string(chars);
}
internal static string ReadAsciiString(Stream s)
{
int len = ReadInt32(s);
char[] chars = new char[len];
for (int i = 0; i < len; i++)
{
int c = s.ReadByte();
if (c == -1)
throw new IOException("Unexpected EOF encountered");
chars[i] = (char) (c & 0x7F);
}
return new string(chars);
}
private const string photoUrl = "http://farm{0}.static.Rtm.com/{1}/{2}_{3}{4}.{5}";
private static readonly Hashtable _serializers = new Hashtable();
private static XmlSerializer GetSerializer(Type type)
{
if( _serializers.ContainsKey(type.Name) )
return (XmlSerializer)_serializers[type.Name];
else
{
XmlSerializer s = new XmlSerializer(type);
_serializers.Add(type.Name, s);
return s;
}
}
/// <summary>
/// Converts the response string (in XML) into the <see cref="Response"/> object.
/// </summary>
/// <param name="responseString">The response from Rtm.</param>
/// <returns>A <see cref="Response"/> object containing the details of the </returns>
internal static Response Deserialize(string responseString)
{
XmlSerializer serializer = GetSerializer(typeof(RtmNet.Response));
try
{
// Deserialise the web response into the Rtm response object
StringReader responseReader = new StringReader(responseString);
RtmNet.Response response = (RtmNet.Response)serializer.Deserialize(responseReader);
responseReader.Close();
return response;
}
catch(InvalidOperationException ex)
{
// Serialization error occurred!
throw new ResponseXmlException("Invalid response received from Rtm.", ex);
}
}
internal static object Deserialize(System.Xml.XmlNode node, Type type)
{
XmlSerializer serializer = GetSerializer(type);
try
{
// Deserialise the web response into the Rtm response object
System.Xml.XmlNodeReader reader = new System.Xml.XmlNodeReader(node);
object o = serializer.Deserialize(reader);
reader.Close();
return o;
}
catch(InvalidOperationException ex)
{
// Serialization error occurred!
throw new ResponseXmlException("Invalid response received from Rtm.", ex);
}
}
}
}
| |
//
// CMFormatDescription.cs: Implements the managed CMFormatDescription
//
// Authors:
// Miguel de Icaza (miguel@xamarin.com)
// Frank Krueger
// Mono Team
// Marek Safar (marek.safar@gmail.com)
//
// Copyright 2010 Novell, Inc
// Copyright 2012 Xamarin Inc
//
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using MonoMac;
using MonoMac.Foundation;
using MonoMac.CoreFoundation;
using MonoMac.ObjCRuntime;
using MonoMac.CoreVideo;
using MonoMac.AudioToolbox;
namespace MonoMac.CoreMedia {
public enum CMFormatDescriptionError {
None = 0,
InvalidParameter = -12710,
AllocationFailed = -12711,
}
[Since (4,0)]
public class CMFormatDescription : INativeObject, IDisposable {
internal IntPtr handle;
internal CMFormatDescription (IntPtr handle)
{
this.handle = handle;
}
[Preserve (Conditional=true)]
internal CMFormatDescription (IntPtr handle, bool owns)
{
if (!owns)
CFObject.CFRetain (handle);
this.handle = handle;
}
~CMFormatDescription ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
/*[DllImport(Constants.CoreMediaLibrary)]
extern static CFPropertyListRef CMFormatDescriptionGetExtension (
CMFormatDescriptionRef desc,
CFStringRef extensionKey
);*/
[DllImport(Constants.CoreMediaLibrary)]
extern static IntPtr CMFormatDescriptionGetExtensions (IntPtr handle);
#if !COREBUILD
public NSDictionary GetExtensions ()
{
var cfDictRef = CMFormatDescriptionGetExtensions (handle);
if (cfDictRef == IntPtr.Zero)
{
return null;
}
else
{
return (NSDictionary) Runtime.GetNSObject (cfDictRef);
}
}
#endif
[DllImport(Constants.CoreMediaLibrary)]
extern static uint CMFormatDescriptionGetMediaSubType (IntPtr handle);
public uint MediaSubType
{
get
{
return CMFormatDescriptionGetMediaSubType (handle);
}
}
public AudioFormatType AudioFormatType {
get {
return MediaType == CMMediaType.Audio ? (AudioFormatType) MediaSubType : 0;
}
}
public CMSubtitleFormatType SubtitleFormatType {
get {
return MediaType == CMMediaType.Subtitle ? (CMSubtitleFormatType) MediaSubType : 0;
}
}
public CMClosedCaptionFormatType ClosedCaptionFormatType {
get {
return MediaType == CMMediaType.ClosedCaption ? (CMClosedCaptionFormatType) MediaSubType : 0;
}
}
public CMMuxedStreamType MuxedStreamType {
get {
return MediaType == CMMediaType.Muxed ? (CMMuxedStreamType) MediaSubType : 0;
}
}
public CMVideoCodecType VideoCodecType {
get {
return MediaType == CMMediaType.Video ? (CMVideoCodecType) MediaSubType : 0;
}
}
public CMMetadataFormatType MetadataFormatType {
get {
return MediaType == CMMediaType.Metadata ? (CMMetadataFormatType) MediaSubType : 0;
}
}
public CMTimeCodeFormatType TimeCodeFormatType {
get {
return MediaType == CMMediaType.TimeCode ? (CMTimeCodeFormatType) MediaSubType : 0;
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static CMMediaType CMFormatDescriptionGetMediaType (IntPtr handle);
public CMMediaType MediaType
{
get
{
return CMFormatDescriptionGetMediaType (handle);
}
}
[DllImport(Constants.CoreMediaLibrary)]
extern static int CMFormatDescriptionGetTypeID ();
public static int GetTypeID ()
{
return CMFormatDescriptionGetTypeID ();
}
#if !COREBUILD
[DllImport (Constants.CoreMediaLibrary)]
extern static CMFormatDescriptionError CMFormatDescriptionCreate (IntPtr allocator, CMMediaType mediaType, uint mediaSubtype, IntPtr extensions, out IntPtr handle);
public static CMFormatDescription Create (CMMediaType mediaType, uint mediaSubtype, out CMFormatDescriptionError error)
{
IntPtr handle;
error = CMFormatDescriptionCreate (IntPtr.Zero, mediaType, mediaSubtype, IntPtr.Zero, out handle);
if (error != CMFormatDescriptionError.None)
return null;
return Create (mediaType, handle, true);
}
public static CMFormatDescription Create (IntPtr handle, bool owns)
{
return Create (CMFormatDescriptionGetMediaType (handle), handle, owns);
}
static CMFormatDescription Create (CMMediaType type, IntPtr handle, bool owns)
{
switch (type) {
case CMMediaType.Video:
return new CMVideoFormatDescription (handle);
case CMMediaType.Audio:
return new CMAudioFormatDescription (handle);
default:
return new CMFormatDescription (handle);
}
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMAudioFormatDescriptionGetStreamBasicDescription (IntPtr handle);
public AudioStreamBasicDescription? AudioStreamBasicDescription {
get {
var ret = CMAudioFormatDescriptionGetStreamBasicDescription (handle);
if (ret != IntPtr.Zero){
unsafe {
return *((AudioStreamBasicDescription *) ret);
}
}
return null;
}
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMAudioFormatDescriptionGetChannelLayout (IntPtr handle, out int size);
public AudioChannelLayout AudioChannelLayout {
get {
int size;
var res = CMAudioFormatDescriptionGetChannelLayout (handle, out size);
if (res == IntPtr.Zero || size == 0)
return null;
return AudioChannelLayout.FromHandle (res);
}
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMAudioFormatDescriptionGetFormatList (IntPtr handle, out int size);
public AudioFormat [] AudioFormats {
get {
unsafe {
int size;
var v = CMAudioFormatDescriptionGetFormatList (handle, out size);
if (v == IntPtr.Zero)
return null;
var items = size / sizeof (AudioFormat);
var ret = new AudioFormat [items];
var ptr = (AudioFormat *) v;
for (int i = 0; i < items; i++)
ret [i] = ptr [i];
return ret;
}
}
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMAudioFormatDescriptionGetMagicCookie (IntPtr handle, out int size);
public byte [] AudioMagicCookie {
get {
int size;
var h = CMAudioFormatDescriptionGetMagicCookie (handle, out size);
if (h == IntPtr.Zero)
return null;
var result = new byte [size];
for (int i = 0; i < size; i++)
result [i] = Marshal.ReadByte (h, i);
return result;
}
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMAudioFormatDescriptionGetMostCompatibleFormat (IntPtr handle);
public AudioFormat AudioMostCompatibleFormat {
get {
unsafe {
var ret = (AudioFormat *) CMAudioFormatDescriptionGetMostCompatibleFormat (handle);
if (ret == null)
return new AudioFormat ();
return *ret;
}
}
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMAudioFormatDescriptionGetRichestDecodableFormat (IntPtr handle);
public AudioFormat AudioRichestDecodableFormat {
get {
unsafe {
var ret = (AudioFormat *) CMAudioFormatDescriptionGetRichestDecodableFormat (handle);
if (ret == null)
return new AudioFormat ();
return *ret;
}
}
}
[DllImport (Constants.CoreMediaLibrary)]
internal extern static Size CMVideoFormatDescriptionGetDimensions (IntPtr handle);
[Advice ("Use CMVideoFormatDescription")]
public Size VideoDimensions {
get {
return CMVideoFormatDescriptionGetDimensions (handle);
}
}
[DllImport (Constants.CoreMediaLibrary)]
internal extern static RectangleF CMVideoFormatDescriptionGetCleanAperture (IntPtr handle, bool originIsAtTopLeft);
[Advice ("Use CMVideoFormatDescription")]
public RectangleF GetVideoCleanAperture (bool originIsAtTopLeft)
{
return CMVideoFormatDescriptionGetCleanAperture (handle, originIsAtTopLeft);
}
[DllImport (Constants.CoreMediaLibrary)]
extern static IntPtr CMVideoFormatDescriptionGetExtensionKeysCommonWithImageBuffers ();
// Belongs to CMVideoFormatDescription
public static NSObject [] GetExtensionKeysCommonWithImageBuffers ()
{
var arr = CMVideoFormatDescriptionGetExtensionKeysCommonWithImageBuffers ();
return NSArray.ArrayFromHandle<NSString> (arr);
}
[DllImport (Constants.CoreMediaLibrary)]
internal extern static SizeF CMVideoFormatDescriptionGetPresentationDimensions (IntPtr handle, bool usePixelAspectRatio, bool useCleanAperture);
[Advice ("Use CMVideoFormatDescription")]
public SizeF GetVideoPresentationDimensions (bool usePixelAspectRatio, bool useCleanAperture)
{
return CMVideoFormatDescriptionGetPresentationDimensions (handle, usePixelAspectRatio, useCleanAperture);
}
[DllImport (Constants.CoreMediaLibrary)]
extern static int CMVideoFormatDescriptionMatchesImageBuffer (IntPtr handle, IntPtr imageBufferRef);
// Belongs to CMVideoFormatDescription
public bool VideoMatchesImageBuffer (CVImageBuffer imageBuffer)
{
if (imageBuffer == null)
throw new ArgumentNullException ("imageBuffer");
return CMVideoFormatDescriptionMatchesImageBuffer (handle, imageBuffer.Handle) != 0;
}
#endif
}
[Since (4,0)]
public class CMAudioFormatDescription : CMFormatDescription {
internal CMAudioFormatDescription (IntPtr handle)
: base (handle)
{
}
internal CMAudioFormatDescription (IntPtr handle, bool owns)
: base (handle, owns)
{
}
// TODO: Move more audio specific methods here
}
[Since (4,0)]
public class CMVideoFormatDescription : CMFormatDescription {
internal CMVideoFormatDescription (IntPtr handle)
: base (handle)
{
}
internal CMVideoFormatDescription (IntPtr handle, bool owns)
: base (handle, owns)
{
}
[DllImport (Constants.CoreMediaLibrary)]
static extern CMFormatDescriptionError CMVideoFormatDescriptionCreate (IntPtr allocator,
CMVideoCodecType codecType,
int width, int height,
IntPtr extensions,
out IntPtr outDesc);
public CMVideoFormatDescription (CMVideoCodecType codecType, Size size)
: base (IntPtr.Zero)
{
var error = CMVideoFormatDescriptionCreate (IntPtr.Zero, codecType, size.Width, size.Height, IntPtr.Zero, out handle);
if (error != CMFormatDescriptionError.None)
throw new ArgumentException (error.ToString ());
}
#if !COREBUILD
public Size Dimensions {
get {
return CMVideoFormatDescriptionGetDimensions (handle);
}
}
[DllImport (Constants.CoreMediaLibrary)]
static extern CMFormatDescriptionError CMVideoFormatDescriptionCreateForImageBuffer (IntPtr allocator,
IntPtr imageBuffer,
out IntPtr outDesc);
public static CMVideoFormatDescription CreateForImageBuffer (CVImageBuffer imageBuffer, out CMFormatDescriptionError error)
{
if (imageBuffer == null)
throw new ArgumentNullException ("imageBuffer");
IntPtr desc;
error = CMVideoFormatDescriptionCreateForImageBuffer (IntPtr.Zero, imageBuffer.handle, out desc);
if (error != CMFormatDescriptionError.None)
return null;
return new CMVideoFormatDescription (desc, true);
}
[DllImport (Constants.CoreMediaLibrary)]
extern static RectangleF CMVideoFormatDescriptionGetCleanAperture (IntPtr handle, bool originIsAtTopLeft);
public RectangleF GetCleanAperture (bool originIsAtTopLeft)
{
return CMVideoFormatDescriptionGetCleanAperture (handle, originIsAtTopLeft);
}
public SizeF GetPresentationDimensions (bool usePixelAspectRatio, bool useCleanAperture)
{
return CMVideoFormatDescriptionGetPresentationDimensions (handle, usePixelAspectRatio, useCleanAperture);
}
#endif
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using LanguageExt.Common;
using System.Threading.Tasks;
using static LanguageExt.Prelude;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Threading;
using LanguageExt.Effects.Traits;
using LanguageExt.Pipes;
using LanguageExt.Thunks;
namespace LanguageExt
{
/// <summary>
/// Asynchronous effect monad
/// </summary>
public readonly struct Aff<RT, A>
where RT : struct, HasCancel<RT>
{
internal ThunkAsync<RT, A> Thunk => thunk ?? ThunkAsync<RT, A>.Fail(Errors.Bottom);
readonly ThunkAsync<RT, A> thunk;
/// <summary>
/// Constructor
/// </summary>
[MethodImpl(Opt.Default)]
internal Aff(ThunkAsync<RT, A> thunk) =>
this.thunk = thunk ?? throw new ArgumentNullException(nameof(thunk));
/// <summary>
/// Invoke the effect
/// </summary>
[Pure, MethodImpl(Opt.Default)]
public ValueTask<Fin<A>> Run(in RT env) =>
Thunk.Value(env);
/// <summary>
/// Invoke the effect
/// </summary>
[Pure, MethodImpl(Opt.Default)]
public ValueTask<Fin<A>> ReRun(RT env) =>
Thunk.ReValue(env);
/// <summary>
/// Clone the effect
/// </summary>
/// <remarks>
/// If the effect had already run, then this state will be wiped in the clone, meaning it can be re-run
/// </remarks>
[Pure, MethodImpl(Opt.Default)]
public Aff<RT, A> Clone() =>
new Aff<RT, A>(Thunk.Clone());
/// <summary>
/// Invoke the effect
/// </summary>
/// <remarks>
/// Throws on error
/// </remarks>
[MethodImpl(Opt.Default)]
public async ValueTask<Unit> RunUnit(RT env) =>
(await Thunk.Value(env).ConfigureAwait(false)).Case switch
{
A _ => unit,
Error e => e.Throw(),
_ => throw new NotSupportedException()
};
/// <summary>
/// Launch the async computation without awaiting the result
/// </summary>
/// <remarks>
/// If the parent expression has `cancel` called on it, then it will also cancel the forked child
/// expression.
///
/// `Fork` returns an `Eff<Unit>` as its bound result value. If you run it, it will cancel the
/// forked child expression.
/// </remarks>
/// <returns>Returns an `Eff<Unit>` as its bound value. If it runs, it will cancel the
/// forked child expression</returns>
[MethodImpl(Opt.Default)]
public Eff<RT, Eff<Unit>> Fork()
{
var t = Thunk;
return Eff<RT, Eff<Unit>>(
env =>
{
// Create a new local runtime with its own cancellation token
var lenv = env.LocalCancel;
// If the parent cancels, we should too
var reg = env.CancellationToken.Register(() => lenv.CancellationTokenSource.Cancel());
// Run
ignore(t.Value(lenv).Iter(_ => Dispose()));
// Return an effect that cancels the fire-and-forget expression
return Eff<Unit>(() =>
{
lenv.CancellationTokenSource.Cancel();
Dispose();
return unit;
});
void Dispose()
{
try
{
reg.Dispose();
}
catch
{
}
}
});
}
/// <summary>
/// Lift an asynchronous effect into the Aff monad
/// </summary>
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> Effect(Func<RT, ValueTask<A>> f) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(f));
/// <summary>
/// Lift an asynchronous effect into the Aff monad
/// </summary>
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> EffectMaybe(Func<RT, ValueTask<Fin<A>>> f) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(f));
/// <summary>
/// Lift an asynchronous effect into the Aff monad
/// </summary>
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, Unit> Effect(Func<RT, ValueTask> f) =>
new Aff<RT, Unit>(ThunkAsync<RT, Unit>.Lazy(async e =>
{
await f(e).ConfigureAwait(false);
return Fin<Unit>.Succ(default);
}));
/// <summary>
/// Lift a value into the Aff monad
/// </summary>
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> Success(A value) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Success(value));
/// <summary>
/// Lift a failure into the Aff monad
/// </summary>
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> Fail(Error error) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Fail(error));
/// <summary>
/// Force the operation to end after a time out delay
/// </summary>
/// <param name="timeoutDelay">Delay for the time out</param>
/// <returns>Either success if the operation completed before the timeout, or Errors.TimedOut</returns>
[Pure, MethodImpl(Opt.Default)]
public Aff<RT, A> Timeout(TimeSpan timeoutDelay)
{
var t = Thunk;
return AffMaybe<RT, A>(
async env =>
{
using var delayTokSrc = new CancellationTokenSource();
var lenv = env.LocalCancel;
var delay = Task.Delay(timeoutDelay, delayTokSrc.Token);
var task = t.Value(lenv).AsTask();
var completed = await Task.WhenAny(new Task[] {delay, task}).ConfigureAwait(false);
if (completed == delay)
{
lenv.CancellationTokenSource.Cancel();
return FinFail<A>(Errors.TimedOut);
}
else
{
delayTokSrc.Cancel();
return await task;
}
});
}
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Aff<RT, A> ma, Aff<RT, A> mb) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = await ma.ReRun(env).ConfigureAwait(false);
return ra.IsSucc
? ra
: await mb.ReRun(env).ConfigureAwait(false);
}));
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Aff<RT, A> ma, Aff<A> mb) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = await ma.ReRun(env).ConfigureAwait(false);
return ra.IsSucc
? ra
: await mb.ReRun().ConfigureAwait(false);
}));
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Aff<A> ma, Aff<RT, A> mb) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = await ma.ReRun().ConfigureAwait(false);
return ra.IsSucc
? ra
: await mb.ReRun(env).ConfigureAwait(false);
}));
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Aff<RT, A> ma, Eff<RT, A> mb) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = await ma.ReRun(env).ConfigureAwait(false);
return ra.IsSucc
? ra
: mb.ReRun(env);
}));
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Eff<RT, A> ma, Aff<RT, A> mb) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = ma.ReRun(env);
return ra.IsSucc
? ra
: await mb.ReRun(env).ConfigureAwait(false);
}));
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Eff<A> ma, Aff<RT, A> mb) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = ma.ReRun();
return ra.IsSucc
? ra
: await mb.ReRun(env).ConfigureAwait(false);
}));
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Aff<RT, A> ma, Eff<A> mb) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = await ma.ReRun(env).ConfigureAwait(false);
return ra.IsSucc
? ra
: mb.ReRun();
}));
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Aff<RT, A> ma, EffCatch<A> mb) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = await ma.ReRun(env).ConfigureAwait(false);
return ra.IsSucc
? ra
: mb.Run(ra.Error);
}));
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Aff<RT, A> ma, AffCatch<A> mb) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = await ma.ReRun(env).ConfigureAwait(false);
return ra.IsSucc
? ra
: await mb.Run(ra.Error).ConfigureAwait(false);
}));
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Aff<RT, A> ma, EffCatch<RT, A> mb) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = await ma.ReRun(env).ConfigureAwait(false);
return ra.IsSucc
? ra
: mb.Run(env, ra.Error);
}));
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Aff<RT, A> ma, AffCatch<RT, A> mb) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = await ma.ReRun(env).ConfigureAwait(false);
return ra.IsSucc
? ra
: await mb.Run(env, ra.Error).ConfigureAwait(false);
}));
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Aff<RT, A> ma, CatchValue<A> value) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = await ma.ReRun(env).ConfigureAwait(false);
return ra.IsSucc
? ra
: value.Match(ra.Error)
? FinSucc(value.Value(ra.Error))
: ra;
}));
[Pure, MethodImpl(Opt.Default)]
public static Aff<RT, A> operator |(Aff<RT, A> ma, CatchError value) =>
new Aff<RT, A>(ThunkAsync<RT, A>.Lazy(
async env =>
{
var ra = await ma.ReRun(env).ConfigureAwait(false);
return ra.IsSucc
? ra
: value.Match(ra.Error)
? FinFail<A>(value.Value(ra.Error))
: ra;
}));
/// <summary>
/// Implicit conversion from pure Aff
/// </summary>
public static implicit operator Aff<RT, A>(Aff<A> ma) =>
EffectMaybe(env => ma.ReRun());
/// <summary>
/// Implicit conversion from pure Eff
/// </summary>
public static implicit operator Aff<RT, A>(Eff<A> ma) =>
EffectMaybe(env => ma.ReRun().AsValueTask());
/// <summary>
/// Implicit conversion from Eff
/// </summary>
public static implicit operator Aff<RT, A>(Eff<RT, A> ma) =>
EffectMaybe(env => ma.ReRun(env).AsValueTask());
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Avalonia.Collections;
using Avalonia.Controls.Generators;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Controls.Utils;
using Avalonia.Input;
using Avalonia.LogicalTree;
using Avalonia.Metadata;
using Avalonia.VisualTree;
namespace Avalonia.Controls
{
/// <summary>
/// Displays a collection of items.
/// </summary>
[PseudoClasses(":empty", ":singleitem")]
public class ItemsControl : TemplatedControl, IItemsPresenterHost, ICollectionChangedListener, IChildIndexProvider
{
/// <summary>
/// The default value for the <see cref="ItemsPanel"/> property.
/// </summary>
private static readonly FuncTemplate<IPanel> DefaultPanel =
new FuncTemplate<IPanel>(() => new StackPanel());
/// <summary>
/// Defines the <see cref="Items"/> property.
/// </summary>
public static readonly DirectProperty<ItemsControl, IEnumerable> ItemsProperty =
AvaloniaProperty.RegisterDirect<ItemsControl, IEnumerable>(nameof(Items), o => o.Items, (o, v) => o.Items = v);
/// <summary>
/// Defines the <see cref="ItemCount"/> property.
/// </summary>
public static readonly DirectProperty<ItemsControl, int> ItemCountProperty =
AvaloniaProperty.RegisterDirect<ItemsControl, int>(nameof(ItemCount), o => o.ItemCount);
/// <summary>
/// Defines the <see cref="ItemsPanel"/> property.
/// </summary>
public static readonly StyledProperty<ITemplate<IPanel>> ItemsPanelProperty =
AvaloniaProperty.Register<ItemsControl, ITemplate<IPanel>>(nameof(ItemsPanel), DefaultPanel);
/// <summary>
/// Defines the <see cref="ItemTemplate"/> property.
/// </summary>
public static readonly StyledProperty<IDataTemplate> ItemTemplateProperty =
AvaloniaProperty.Register<ItemsControl, IDataTemplate>(nameof(ItemTemplate));
private IEnumerable _items = new AvaloniaList<object>();
private int _itemCount;
private IItemContainerGenerator _itemContainerGenerator;
private EventHandler<ChildIndexChangedEventArgs> _childIndexChanged;
/// <summary>
/// Initializes static members of the <see cref="ItemsControl"/> class.
/// </summary>
static ItemsControl()
{
ItemsProperty.Changed.AddClassHandler<ItemsControl>((x, e) => x.ItemsChanged(e));
ItemTemplateProperty.Changed.AddClassHandler<ItemsControl>((x, e) => x.ItemTemplateChanged(e));
}
/// <summary>
/// Initializes a new instance of the <see cref="ItemsControl"/> class.
/// </summary>
public ItemsControl()
{
UpdatePseudoClasses(0);
SubscribeToItems(_items);
}
/// <summary>
/// Gets the <see cref="IItemContainerGenerator"/> for the control.
/// </summary>
public IItemContainerGenerator ItemContainerGenerator
{
get
{
if (_itemContainerGenerator == null)
{
_itemContainerGenerator = CreateItemContainerGenerator();
if (_itemContainerGenerator != null)
{
_itemContainerGenerator.ItemTemplate = ItemTemplate;
_itemContainerGenerator.Materialized += (_, e) => OnContainersMaterialized(e);
_itemContainerGenerator.Dematerialized += (_, e) => OnContainersDematerialized(e);
_itemContainerGenerator.Recycled += (_, e) => OnContainersRecycled(e);
}
}
return _itemContainerGenerator;
}
}
/// <summary>
/// Gets or sets the items to display.
/// </summary>
[Content]
public IEnumerable Items
{
get { return _items; }
set { SetAndRaise(ItemsProperty, ref _items, value); }
}
/// <summary>
/// Gets the number of items in <see cref="Items"/>.
/// </summary>
public int ItemCount
{
get => _itemCount;
private set => SetAndRaise(ItemCountProperty, ref _itemCount, value);
}
/// <summary>
/// Gets or sets the panel used to display the items.
/// </summary>
public ITemplate<IPanel> ItemsPanel
{
get { return GetValue(ItemsPanelProperty); }
set { SetValue(ItemsPanelProperty, value); }
}
/// <summary>
/// Gets or sets the data template used to display the items in the control.
/// </summary>
public IDataTemplate ItemTemplate
{
get { return GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
/// <summary>
/// Gets the items presenter control.
/// </summary>
public IItemsPresenter Presenter
{
get;
protected set;
}
event EventHandler<ChildIndexChangedEventArgs> IChildIndexProvider.ChildIndexChanged
{
add => _childIndexChanged += value;
remove => _childIndexChanged -= value;
}
/// <inheritdoc/>
void IItemsPresenterHost.RegisterItemsPresenter(IItemsPresenter presenter)
{
if (Presenter is IChildIndexProvider oldInnerProvider)
{
oldInnerProvider.ChildIndexChanged -= PresenterChildIndexChanged;
}
Presenter = presenter;
ItemContainerGenerator.Clear();
if (Presenter is IChildIndexProvider innerProvider)
{
innerProvider.ChildIndexChanged += PresenterChildIndexChanged;
_childIndexChanged?.Invoke(this, new ChildIndexChangedEventArgs());
}
}
void ICollectionChangedListener.PreChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
{
}
void ICollectionChangedListener.Changed(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
{
}
void ICollectionChangedListener.PostChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
{
ItemsCollectionChanged(sender, e);
}
/// <summary>
/// Gets the item at the specified index in a collection.
/// </summary>
/// <param name="items">The collection.</param>
/// <param name="index">The index.</param>
/// <returns>The item at the given index or null if the index is out of bounds.</returns>
protected static object ElementAt(IEnumerable items, int index)
{
if (index != -1 && index < items.Count())
{
return items.ElementAt(index) ?? null;
}
else
{
return null;
}
}
/// <summary>
/// Gets the index of an item in a collection.
/// </summary>
/// <param name="items">The collection.</param>
/// <param name="item">The item.</param>
/// <returns>The index of the item or -1 if the item was not found.</returns>
protected static int IndexOf(IEnumerable items, object item)
{
if (items != null && item != null)
{
var list = items as IList;
if (list != null)
{
return list.IndexOf(item);
}
else
{
int index = 0;
foreach (var i in items)
{
if (Equals(i, item))
{
return index;
}
++index;
}
}
}
return -1;
}
/// <summary>
/// Creates the <see cref="ItemContainerGenerator"/> for the control.
/// </summary>
/// <returns>
/// An <see cref="IItemContainerGenerator"/> or null.
/// </returns>
/// <remarks>
/// Certain controls such as <see cref="TabControl"/> don't actually create item
/// containers; however they want it to be ItemsControls so that they have an Items
/// property etc. In this case, a derived class can override this method to return null
/// in order to disable the creation of item containers.
/// </remarks>
protected virtual IItemContainerGenerator CreateItemContainerGenerator()
{
return new ItemContainerGenerator(this);
}
/// <summary>
/// Called when new containers are materialized for the <see cref="ItemsControl"/> by its
/// <see cref="ItemContainerGenerator"/>.
/// </summary>
/// <param name="e">The details of the containers.</param>
protected virtual void OnContainersMaterialized(ItemContainerEventArgs e)
{
foreach (var container in e.Containers)
{
// If the item is its own container, then it will be added to the logical tree when
// it was added to the Items collection.
if (container.ContainerControl != null && container.ContainerControl != container.Item)
{
LogicalChildren.Add(container.ContainerControl);
}
}
}
/// <summary>
/// Called when containers are dematerialized for the <see cref="ItemsControl"/> by its
/// <see cref="ItemContainerGenerator"/>.
/// </summary>
/// <param name="e">The details of the containers.</param>
protected virtual void OnContainersDematerialized(ItemContainerEventArgs e)
{
foreach (var container in e.Containers)
{
// If the item is its own container, then it will be removed from the logical tree
// when it is removed from the Items collection.
if (container?.ContainerControl != container?.Item)
{
LogicalChildren.Remove(container.ContainerControl);
}
}
}
/// <summary>
/// Called when containers are recycled for the <see cref="ItemsControl"/> by its
/// <see cref="ItemContainerGenerator"/>.
/// </summary>
/// <param name="e">The details of the containers.</param>
protected virtual void OnContainersRecycled(ItemContainerEventArgs e)
{
}
/// <summary>
/// Handles directional navigation within the <see cref="ItemsControl"/>.
/// </summary>
/// <param name="e">The key events.</param>
protected override void OnKeyDown(KeyEventArgs e)
{
if (!e.Handled)
{
var focus = FocusManager.Instance;
var direction = e.Key.ToNavigationDirection();
var container = Presenter?.Panel as INavigableContainer;
if (container == null ||
focus.Current == null ||
direction == null ||
direction.Value.IsTab())
{
return;
}
IVisual current = focus.Current;
while (current != null)
{
if (current.VisualParent == container && current is IInputElement inputElement)
{
IInputElement next = GetNextControl(container, direction.Value, inputElement, false);
if (next != null)
{
focus.Focus(next, NavigationMethod.Directional, e.KeyModifiers);
e.Handled = true;
}
break;
}
current = current.VisualParent;
}
}
base.OnKeyDown(e);
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == ItemCountProperty)
{
UpdatePseudoClasses(change.NewValue.GetValueOrDefault<int>());
}
}
/// <summary>
/// Called when the <see cref="Items"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void ItemsChanged(AvaloniaPropertyChangedEventArgs e)
{
var oldValue = e.OldValue as IEnumerable;
var newValue = e.NewValue as IEnumerable;
if (oldValue is INotifyCollectionChanged incc)
{
CollectionChangedEventManager.Instance.RemoveListener(incc, this);
}
UpdateItemCount();
RemoveControlItemsFromLogicalChildren(oldValue);
AddControlItemsToLogicalChildren(newValue);
if (Presenter != null)
{
Presenter.Items = newValue;
}
SubscribeToItems(newValue);
}
/// <summary>
/// Called when the <see cref="INotifyCollectionChanged.CollectionChanged"/> event is
/// raised on <see cref="Items"/>.
/// </summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event args.</param>
protected virtual void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
UpdateItemCount();
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
AddControlItemsToLogicalChildren(e.NewItems);
break;
case NotifyCollectionChangedAction.Remove:
RemoveControlItemsFromLogicalChildren(e.OldItems);
break;
}
Presenter?.ItemsChanged(e);
}
/// <summary>
/// Given a collection of items, adds those that are controls to the logical children.
/// </summary>
/// <param name="items">The items.</param>
private void AddControlItemsToLogicalChildren(IEnumerable items)
{
var toAdd = new List<ILogical>();
if (items != null)
{
foreach (var i in items)
{
var control = i as IControl;
if (control != null && !LogicalChildren.Contains(control))
{
toAdd.Add(control);
}
}
}
LogicalChildren.AddRange(toAdd);
}
/// <summary>
/// Given a collection of items, removes those that are controls to from logical children.
/// </summary>
/// <param name="items">The items.</param>
private void RemoveControlItemsFromLogicalChildren(IEnumerable items)
{
var toRemove = new List<ILogical>();
if (items != null)
{
foreach (var i in items)
{
var control = i as IControl;
if (control != null)
{
toRemove.Add(control);
}
}
}
LogicalChildren.RemoveAll(toRemove);
}
/// <summary>
/// Subscribes to an <see cref="Items"/> collection.
/// </summary>
/// <param name="items">The items collection.</param>
private void SubscribeToItems(IEnumerable items)
{
if (items is INotifyCollectionChanged incc)
{
CollectionChangedEventManager.Instance.AddListener(incc, this);
}
}
/// <summary>
/// Called when the <see cref="ItemTemplate"/> changes.
/// </summary>
/// <param name="e">The event args.</param>
private void ItemTemplateChanged(AvaloniaPropertyChangedEventArgs e)
{
if (_itemContainerGenerator != null)
{
_itemContainerGenerator.ItemTemplate = (IDataTemplate)e.NewValue;
// TODO: Rebuild the item containers.
}
}
private void UpdateItemCount()
{
if (Items == null)
{
ItemCount = 0;
}
else if (Items is IList list)
{
ItemCount = list.Count;
}
else
{
ItemCount = Items.Count();
}
}
private void UpdatePseudoClasses(int itemCount)
{
PseudoClasses.Set(":empty", itemCount == 0);
PseudoClasses.Set(":singleitem", itemCount == 1);
}
protected static IInputElement GetNextControl(
INavigableContainer container,
NavigationDirection direction,
IInputElement from,
bool wrap)
{
IInputElement result;
var c = from;
do
{
result = container.GetControl(direction, c, wrap);
from = from ?? result;
if (result != null &&
result.Focusable &&
result.IsEffectivelyEnabled &&
result.IsEffectivelyVisible)
{
return result;
}
c = result;
} while (c != null && c != from);
return null;
}
private void PresenterChildIndexChanged(object sender, ChildIndexChangedEventArgs e)
{
_childIndexChanged?.Invoke(this, e);
}
int IChildIndexProvider.GetChildIndex(ILogical child)
{
return Presenter is IChildIndexProvider innerProvider
? innerProvider.GetChildIndex(child) : -1;
}
bool IChildIndexProvider.TryGetTotalCount(out int count)
{
if (Presenter is IChildIndexProvider presenter
&& presenter.TryGetTotalCount(out count))
{
return true;
}
count = ItemCount;
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace ExtendedLibrary.Events
{
public class ParameterWizard : BaseWizard<ParameterWizardValue>
{
public ParameterData[] dataList;
private List<FakeObject> fakeObjects;
private List<SerializedObject> serializedFakeObjects;
private List<SerializedProperty> serializedFakeProperties;
private List<GUIContent> labels;
private ScriptableObject[] cloneObjects;
private FieldInfo[] cloneValueFieldInfos;
private SerializedObject[] serializedCloneObjects;
private SerializedProperty[] serializedCloneProperties;
protected override sealed bool DrawWizardGUI()
{
if (this.fakeObjects == null || this.serializedFakeObjects == null || this.labels == null)
{
this.fakeObjects = new List<FakeObject>();
this.serializedFakeObjects = new List<SerializedObject>();
this.serializedFakeProperties = new List<SerializedProperty>();
this.labels = new List<GUIContent>();
for (var i = 0; i < this.dataList.Length; i++)
{
this.fakeObjects.Add(CreateInstance<FakeObject>());
this.serializedFakeObjects.Add(new SerializedObject(this.fakeObjects[i]));
var param = this.dataList[i];
var valueProperty = this.serializedProperty.GetArrayElementAtIndex(i).GetPropertyOfType(param.returnType);
var fakeProperty = this.serializedFakeObjects[i].FindProperty(FakeObjectFields.Value).GetPropertyOfType(param.returnType);
valueProperty.CopyTo(fakeProperty);
string label;
switch (param.returnType)
{
case ObjectType.LayerMask:
case ObjectType.Color:
case ObjectType.AnimationCurve:
label = param.name;
break;
default:
label = string.Format("{0} : {1}", param.name, param.typeName);
break;
}
this.labels.Add(new GUIContent(label));
this.serializedFakeProperties.Add(fakeProperty);
}
}
if (this.cloneObjects == null || this.cloneObjects.Length != this.dataList.Length)
{
this.cloneObjects = new ScriptableObject[this.dataList.Length];
this.cloneValueFieldInfos = new FieldInfo[this.dataList.Length];
this.serializedCloneObjects = new SerializedObject[this.dataList.Length];
this.serializedCloneProperties = new SerializedProperty[this.dataList.Length];
}
for (var i = 0; i < this.dataList.Length; i++)
{
DrawMember(this.serializedFakeProperties[i], ref i, this.dataList[i]);
}
return true;
}
private void DrawMember(SerializedProperty property, ref int index, ParameterData parameter)
{
var label = this.labels[index];
switch (parameter.returnType)
{
case ObjectType.Boolean:
case ObjectType.Int32:
case ObjectType.Int64:
case ObjectType.Single:
case ObjectType.Double:
case ObjectType.String:
case ObjectType.LayerMask:
case ObjectType.Color:
case ObjectType.AnimationCurve:
EditorGUILayout.PropertyField(property, label, false);
break;
case ObjectType.UInt64:
var oldString = property.stringValue;
var ulongString = EditorGUILayout.TextField(label, property.stringValue);
ulong ulongVal;
if (!ulong.TryParse(ulongString, out ulongVal))
ulongString = oldString;
if (string.IsNullOrEmpty(ulongString))
ulongString = "0";
property.stringValue = ulongString;
break;
case ObjectType.Byte:
property.intValue = EditorFields.ByteField(label, (byte) property.intValue);
break;
case ObjectType.SByte:
property.intValue = EditorFields.SByteField(label, (sbyte) property.intValue);
break;
case ObjectType.Char:
property.intValue = EditorFields.CharField(label, (char) property.intValue);
break;
case ObjectType.Int16:
property.intValue = EditorFields.ShortField(label, (short) property.intValue);
break;
case ObjectType.UInt16:
property.intValue = EditorFields.UShortField(label, (ushort) property.intValue);
break;
case ObjectType.UInt32:
property.longValue = EditorFields.UIntField(label, (uint) property.longValue);
break;
case ObjectType.Enum:
{
var typeOf = Type.GetType(parameter.assemblyQualifiedName);
var flagsAttribute = typeOf.GetCustomAttributes(typeof(FlagsAttribute), false);
Enum enumValue;
if (flagsAttribute != null && flagsAttribute.Length >= 1)
{
enumValue = EditorGUILayout.EnumMaskPopup(label, (Enum) Enum.ToObject(typeOf, property.longValue));
}
else
{
enumValue = EditorGUILayout.EnumPopup(label, (Enum) Enum.ToObject(typeOf, property.longValue));
}
try
{
property.longValue = (int) Enum.ToObject(typeOf, enumValue);
}
catch
{
property.longValue = (long) Enum.ToObject(typeOf, enumValue);
}
}
break;
case ObjectType.Vector2:
property.vector2Value = EditorGUILayout.Vector2Field(label, property.vector2Value);
break;
case ObjectType.Vector3:
property.vector3Value = EditorGUILayout.Vector3Field(label, property.vector3Value);
break;
case ObjectType.Vector4:
property.vector4Value = EditorGUILayout.Vector4Field(label, property.vector4Value);
break;
case ObjectType.Bounds:
property.boundsValue = EditorGUILayout.BoundsField(label, property.boundsValue);
break;
case ObjectType.Rect:
property.rectValue = EditorGUILayout.RectField(label, property.rectValue);
break;
case ObjectType.Quaternion:
property.quaternionValue = EditorFields.QuaternionField(label, property.quaternionValue);
break;
case ObjectType.UnityObject:
{
var typeOf = Type.GetType(parameter.assemblyQualifiedName);
property.objectReferenceValue = EditorGUILayout.ObjectField(label, property.objectReferenceValue, typeOf, true);
}
break;
case ObjectType.Matrix4x4:
{
var matrix = property.stringValue.ToObject<Matrix4x4>();
matrix = EditorFields.Matrix4x4Field(label, matrix);
property.stringValue = matrix.ToJson();
}
break;
case ObjectType.SerializableType:
case ObjectType.Array:
case ObjectType.List:
{
var typeOf = Type.GetType(parameter.assemblyQualifiedName);
if (this.cloneObjects[index] == null)
{
var cloneObjectType = CreateCloneObjectType("CloneObject", FakeObjectFields.Value, typeOf);
this.cloneObjects[index] = CreateInstance(cloneObjectType);
this.cloneValueFieldInfos[index] = cloneObjectType.GetField(FakeObjectFields.Value,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
var cloneObject = this.cloneObjects[index];
var cloneValueFieldInfo = this.cloneValueFieldInfos[index];
var data = property.stringValue.ToObject(typeOf);
if (data == null)
{
if (parameter.returnType == ObjectType.Array)
data = Activator.CreateInstance(typeOf, 0);
else
data = Activator.CreateInstance(typeOf);
}
cloneValueFieldInfo.SetValue(cloneObject, data);
if (this.serializedCloneObjects[index] == null)
{
this.serializedCloneObjects[index] = new SerializedObject(cloneObject);
this.serializedCloneProperties[index] = this.serializedCloneObjects[index].FindProperty(FakeObjectFields.Value);
}
var serializedCloneObject = this.serializedCloneObjects[index];
var serializedCloneProperty = this.serializedCloneProperties[index];
EditorGUI.BeginChangeCheck();
serializedCloneObject.Update();
EditorGUILayout.PropertyField(serializedCloneProperty, label, true);
if (EditorGUI.EndChangeCheck())
{
serializedCloneObject.ApplyModifiedPropertiesWithoutUndo();
data = cloneValueFieldInfo.GetValue(cloneObject);
property.stringValue = data.ToJson(typeOf);
}
}
break;
}
}
private void OnWizardCreate()
{
this.onClose(new ParameterWizardValue()
{
dataList = this.dataList,
serializedObjects = this.serializedFakeObjects,
path = this.path
});
}
}
public class ParameterWizardValue
{
public ParameterData[] dataList;
public List<SerializedObject> serializedObjects;
public string path;
}
}
| |
/* Copyright (c) 2009-11, ReactionGrid Inc. http://reactiongrid.com
* See License.txt for full licence information.
*
* NetworkController.cs Revision 1.4.1106.29
* Controls all interaction with back-end networking infrastructure from Unity code files */
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using ReactionGrid.Jibe;
using System;
using ReactionGrid.JibeAPI;
public class NetworkController : MonoBehaviour
{
public List<GameObject> objectsToCallJibeInitOn = new List<GameObject>();
private static int _nextInstanceId = 0;
private int _instanceId;
public Dictionary<int,string> onlyChatWithGroup = new Dictionary<int, string>(); //key is userId value is group they are chatting with
private IJibeServer jibeServerInstance;
private string defaultRoom;
public IJibePlayer localPlayer;
private IJibePlayer host; // player responsible for syncing other players
public string loaderScene = "Loader";
public string roomToLoad;
public bool useDefaultRoom;
public bool lonely = true; //am i the first one in the world
public int maxRoomSize;
private int timeSinceSpawn = 0;
private string _nextLevel = "";
public float networkWakeup = 60.0f;
private float _networkIdle = 0.0f;
private string _version = "";
public string RemotePlayerGameObjectPrefix = "remote_";
// used for loading up a new jibe instance with an application.loadUrl as called from a web player
private string navigateUrl;
public ChatInput chatController;
private Dictionary<int, List<string>> groups = new Dictionary<int, List<string>>(); //RSO keeps track of what groups each player is in - key is playerid values are the list of the groups
private List<string> spawnedPlayers = new List<string>();
private Dictionary<int, string> pendingLeavingPlayers = new Dictionary<int, string>(); // collection of players recently left, may respawn or may have actually left - pause a few seconds before notifying player leaving.
public float playerLeavingDelay = 3.0f;
private float playerLeavingInterval = 0.0f;
private List<Dictionary<string,string>> dataToSync = new List<Dictionary<string, string>>(); //RSO all of the persistent data - currently has to broadcast this as a message and users selectively ignore it. Eventually may either change the the privatecustomdata that i made in jibesfs2xserver or open up a direct p2p connection and send it around the server
private bool synced =false;
private Dictionary<string, List<string>> destroyTable = new Dictionary<string, List<string>>(); //RSO this keeps track of everything that is to be removed from persistent custom data when people leave
//private UnityP2PNetworkController P2PController;
public UIGrid onlineUserGrid;
private List<Dictionary<string,string>> localDataToSync = new List<Dictionary<string, string>>(); //data to sync that only the localplayer should ever send.
public Transform managementOnlineUsers;
public Transform unionOnlineUsers;
public Transform onlineUserPrefab;
public bool isAdmin;
private bool repositionNextUpdate;
public NetworkController()
{
// Tracking instance IDs is for advanced debugging
_instanceId = _nextInstanceId++;
}
#region Public properties and methods to retrieve player information
/// <summary>
/// Get the current local player's name (or gracefully return an empty string if the user has disconnected)
/// </summary>
/// <returns>The local player's name</returns>
public string GetUserName()
{
return IsConnected ? localPlayer.Name : "";
}
/// <summary>
/// Get the current local player's ID (or gracefully return -1 if the user has disconnected)
/// </summary>
/// <returns>The local player's ID</returns>
public int GetUserId()
{
return IsConnected ? localPlayer.PlayerID : -1;
}
/// <summary>
/// Get the version number of the world so it can be displayed on screen and used in UAT scenarios
/// </summary>
/// <returns>The local player's name</returns>
public string GetVersion()
{
return _version;
}
/// <summary>
/// Public property to determine connection state, using the concept that if a user is connected there will be an instance of a localPlayer object
/// </summary>
public bool IsConnected
{
get
{
return localPlayer != null;
}
}
public string GetMyName()
{
return localPlayer.Name;
}
public IJibePlayer GetLocalPlayer()
{
return localPlayer;
}
public string GetRemoteName(int playerId)
{
IJibePlayer remotePlayer = jibeServerInstance.GetPlayer(playerId);
if (remotePlayer != null)
{
return remotePlayer.Name;
}
else
{
return "Unknown";
}
}
public IEnumerable<IJibePlayer> GetAllUsers()
{
if (jibeServerInstance != null && jibeServerInstance.Players != null)
return jibeServerInstance.Players;
else
return null;
}
#endregion
#region LocalPlayer Events - handle all update information sent by the local player and pass to the Jibe Server for transfer over the network
/// <summary>
/// Update the localPlayer object with a new player object. If there is already a localPlayer object then
/// the localPLayer events need to be unwired completely and rewired to the new player object
/// </summary>
/// <param name="player">An IJibePlayer object representing the local player</param>
private void SetLocalPlayer(IJibePlayer player)
{
if (localPlayer != null)
{
UnwireLocalPlayerEvents();
}
localPlayer = player;
if (localPlayer != null)
{
Debug.Log("wiring up local player event handlers");
WireLocalPlayerEvents();
}
}
/// <summary>
/// Wire up local player event handling - each of these methods will be invoked when the corresponding event is raised
/// </summary>
private void WireLocalPlayerEvents()
{
localPlayer.NameUpdated += localPlayer_NameUpdated;
localPlayer.AnimationUpdated += localPlayer_AnimationUpdated;
localPlayer.AppearanceUpdated += localPlayer_AppearanceUpdated;
localPlayer.TransformUpdated += localPlayer_TransformUpdated;
localPlayer.VoiceUpdated += localPlayer_VoiceUpdated;
}
/// <summary>
/// Unwire event handlers for the local player- this needs to be done whenever a scene is left and whenever a player disconnects.
/// Duplicate event handlers will confuse Jibe quite a lot, and will manifest as duplicate chat messages, ghostly dopplegangers, etc.
/// </summary>
private void UnwireLocalPlayerEvents()
{
localPlayer.NameUpdated -= localPlayer_NameUpdated;
localPlayer.AnimationUpdated -= localPlayer_AnimationUpdated;
localPlayer.AppearanceUpdated -= localPlayer_AppearanceUpdated;
localPlayer.TransformUpdated -= localPlayer_TransformUpdated;
localPlayer.VoiceUpdated -= localPlayer_VoiceUpdated;
}
void localPlayer_TransformUpdated(object sender, EventArgs e)
{
jibeServerInstance.SendTransform(localPlayer.PosX, localPlayer.PosY, localPlayer.PosZ, localPlayer.RotX, localPlayer.RotY, localPlayer.RotZ, localPlayer.RotW);
}
void localPlayer_AnimationUpdated(object sender, EventArgs e)
{
jibeServerInstance.SendAnimation(localPlayer.Animation.ToString());
}
void localPlayer_AppearanceUpdated(object sender, EventArgs e)
{
jibeServerInstance.SendAppearance();
}
void localPlayer_NameUpdated(object sender, EventArgs e)
{
jibeServerInstance.SendName();
}
void localPlayer_VoiceUpdated(object sender, EventArgs e)
{
jibeServerInstance.SendSpeech();
}
#endregion
#region Monobehaviour Events - Events that are part of Unity pipeline
// We start working from here
void Start()
{
Application.runInBackground = true; // Let the application be running while the window is not active.
Debug.Log("NetController instance " + _instanceId);
Debug.Log("About to start processing events in level " + Application.loadedLevelName);
if (JibeComms.IsInitialized())
{
DoInitialization();
}
else
{
JibeConfig config = GetComponent<JibeConfig>();
SingleSceneConfiguration ssc = GetComponent<SingleSceneConfiguration>();
if (config != null && ssc != null)
{
// Network Controller has configuration information attached! Use it and try single-scene Jibe configuration
ssc.RunConfiguration();
}
else
{
Debug.Log("Jibe is null - back to loader");
Application.LoadLevel("Loader");
return;
}
}
//P2PController = GameObject.Find("NetworkController").AddComponent<UnityP2PNetworkController>(); //add it during runtime because the p2p controller is a custom script made by me, not in vanilla jibe and this makes upgrading much easier as we don't have to change the prefabs manually
}
public void DoInitialization()
{
Debug.Log("Jibe initialised - getting config");
JibeComms jibe = JibeComms.Jibe;
defaultRoom = jibe.DefaultRoom;
if (!useDefaultRoom)
{
foreach (string room in jibe.RoomList)
{
if (roomToLoad == room)
{
defaultRoom = roomToLoad;
break;
}
}
}
_version = jibe.Version;
Debug.Log("Setting world version to " + _version);
if (chatController == null)
// chatController = GameObject.Find("ChatBox").GetComponent<ChatInput>();
// Set up connections to the Jibe Server
jibeServerInstance = jibe.Server;
// Jibe server publishes many events - we need to subscribe to these events and handle them in here.
jibeServerInstance.NewRemotePlayer += new RemotePlayerEventHandler(jibeServerInstance_NewRemotePlayer);
jibeServerInstance.LostRemotePlayer += new RemotePlayerEventHandler(jibeServerInstance_LostRemotePlayer);
jibeServerInstance.NewChatMessage += new ChatEventHandler(jibeServerInstance_NewChatMessage);
jibeServerInstance.NewBroadcastChatMessage += new BroadcastChatEventHandler(jibeServerInstance_NewBroadcastChatMessage);
jibeServerInstance.NewPrivateChatMessage += new PrivateChatEventHandler(jibeServerInstance_NewPrivateChatMessage);
jibeServerInstance.RoomJoinResult += new RoomJoinResultEventHandler(RoomJoinResult);
jibeServerInstance.RoomLeaveResult += new RoomLeaveResultEventHandler(RoomLeaveResult);
jibeServerInstance.CustomDataEvent += new CustomDataEventHandler(jibeServerInstance_CustomDataEvent);
// Create the local player and connect to the server
SetLocalPlayer(jibeServerInstance.Connect());
Debug.Log(localPlayer.ToString());
if (!IsConnected)
{
// If there is no connection to the server, go back to the Loader scene
Application.LoadLevel("Loader");
//return;
}
else
{
// now we're connected, join a room
jibeServerInstance.JoinRoom(defaultRoom, jibe.RoomPassword);
}
}
public void GroupInitialization()
{
Debug.Log("Group initialization");
if(!PlayerPrefs.HasKey("Group")) //this is currently not in use, but is here so that if we ever want to disable all group features, we can just remove the assignments to the playerprefs in the dressingroom script and everything will act the same as before groups were added
{
isAdmin=true;
onlineUserPrefab = GetComponent<PlayerSpawnController>().adminOnlineUserPrefab; //make sure that when we spawn online users in different groups they still have the mute button next to them.
SetCurrentGroup("GlobalChat", localPlayer.PlayerID);
}
else
{
string myGroup = PlayerPrefs.GetString("Group");
AddMemberToGroup(myGroup, localPlayer.PlayerID, localPlayer.Name);
SetCurrentGroup("GlobalChat", localPlayer.PlayerID);
Dictionary<string,string> dataToSend = new Dictionary<string, string>();
dataToSend["MethodToCall"] = "AddMemberToGroup";
dataToSend["SendingObjectName"] = "NetworkController";
dataToSend["Group"] = myGroup;
dataToSend["PlayerID"] = localPlayer.PlayerID.ToString();
dataToSend["PlayerName"] = localPlayer.Name;
SendCustomData(dataToSend, false, new string[0], true);
Debug.Log("Sent message containing group info");
foreach(GameObject currentObject in GameObject.FindGameObjectsWithTag("GroupSpecific"))
{
currentObject.SendMessage("GroupInit", myGroup, SendMessageOptions.DontRequireReceiver);
}
Debug.Log("Finished calling GroupInit");
if(myGroup=="GlobalChat")
{
isAdmin=true;
onlineUserPrefab = GetComponent<PlayerSpawnController>().adminOnlineUserPrefab; //make sure that when we spawn online users in different groups they still have the mute button next to them.
}
}
}
void Update()
{
if(repositionNextUpdate==true)
{
onlineUserGrid.repositionNow=true;
}
if (jibeServerInstance == null)
{
return;
}
jibeServerInstance.Update();
localPlayer.Update();
}
void FixedUpdate()
{
if(timeSinceSpawn==90)
{
}
if(timeSinceSpawn<100) //RSO begin - gives time to check if first player in world
{
timeSinceSpawn++;
}
else if(lonely && timeSinceSpawn>=100 && host==null)
{
host=localPlayer;
//P2PController.setMeAsHost();
Debug.Log("I was first to join the room, I am now hosting!");
} //RSO end
else if(timeSinceSpawn>=100 && host==null)
{
Debug.Log("Host left - now setting a new host");
int lowest = 9999999;
if(localPlayer==null)
{
Debug.Log("WTF local player is null");
}
else
{
lowest = localPlayer.PlayerID;
host=localPlayer;
}
foreach (IJibePlayer activeplayer in jibeServerInstance.Players)
{
if(activeplayer.PlayerID<lowest)
{
host=activeplayer;
lowest = activeplayer.PlayerID;
}
}
}
else if(host==null)
{
Debug.Log("host is null");
}
else if(host.Equals(""))
{
Debug.Log("host is empty string");
}
/* else
{
Debug.Log("Host is neither of these");
} */
_networkIdle += Time.deltaTime;
if (_networkIdle > networkWakeup)
{
Debug.Log("Idle wakeup");
_networkIdle = 0;
jibeServerInstance.SendAppearance();
}
playerLeavingInterval += Time.deltaTime;
if (playerLeavingInterval > playerLeavingDelay)
{
playerLeavingInterval = 0.0f;
if (pendingLeavingPlayers.Count > 0)
{
int found = 0;
foreach(int playerId in pendingLeavingPlayers.Keys)
{
foreach (IJibePlayer activeplayer in jibeServerInstance.Players)
{
if (activeplayer.Name == pendingLeavingPlayers[playerId])
{
found++;
// player has reconnected
break;
}
}
if (found == 0)
{
// assume player has left / disconnected for good
//processLogoutEvents(playerId); moved to jibeserverinstance on remoteplayer leaves
//the online users is on top so even though the text in the chat has the same name it will select the onlineuser
}
}
}
// clear out collection
pendingLeavingPlayers = new Dictionary<int, string>();
}
}
void OnApplicationQuit()
{
if(isAdmin)
{
Dictionary<string,string> dataToSend = new Dictionary<string, string>();
dataToSend["SendingObjectName"] = "VivoxHud";
dataToSend["MethodToCall"] = "RemoteUserMute";
dataToSend["Mute"] = "False";
SendCustomData(dataToSend, true, new string[0], false);
}
if (jibeServerInstance != null)
{
jibeServerInstance.Disconnect();
}
}
#endregion Events
#region Jibe Server Event Handlers
/// <summary>
/// Event raised when the local player has successfully joined a network room - at this point we have network presence
/// and it's time to spawn an avatar
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RoomJoinResult(object sender, RoomJoinResultEventArgs e)
{
if (e.Success)
{
Debug.Log("Room join result in NetController " + _instanceId);
GameObject spawnedLocalPlayer = GetComponent<PlayerSpawnController>().SpawnLocalPlayer(localPlayer);
SendTransform(spawnedLocalPlayer.transform);
SendAppearance(localPlayer.Skin, localPlayer.Hair, localPlayer.AvatarModel);
Debug.Log("Calling JibeInit on all Jibe objects");
// Call init methods on all scripts within Jibe and JibeGUI prefabs
SendMessageToAllJibeObjects("JibeInit");
GroupInitialization();
}
else
{
Debug.Log("Room Join FAIL " + e.Message);
}
}
/// <summary>
/// Sends method calls to all game objects that are children of the Jibe or JibeGUI Prefabs
/// </summary>
/// <param name="message">The message (name of method) to call</param>
private void SendMessageToAllJibeObjects(string message)
{
Transform jibeObject = this.transform.parent;
foreach (Transform t in jibeObject.transform)
{
t.SendMessage(message, SendMessageOptions.DontRequireReceiver);
foreach(Transform tt in t.transform)
{
tt.SendMessage(message, SendMessageOptions.DontRequireReceiver);
}
}
GameObject jibeGUI = GameObject.Find("JibeGUI");
if (jibeGUI != null)
{
foreach (Transform t in jibeGUI.transform)
{
t.SendMessage(message, SendMessageOptions.DontRequireReceiver);
}
}
//RSO
foreach(GameObject currentObject in GameObject.FindGameObjectsWithTag("Door"))
{
currentObject.SendMessage("JibeInit");
}
foreach(GameObject currentObject in GameObject.FindGameObjectsWithTag("SitTarget"))
{
currentObject.SendMessage("JibeInit");
}
GameObject.Find("RaiseHand").BroadcastMessage("JibeInit");
GameObject.Find("ChatBox").SendMessage("JibeInit");
foreach(GameObject currentObject in objectsToCallJibeInitOn)
{
currentObject.SendMessage("JibeInit");
}
}
/// <summary>
/// Called in response to leaving a network room - once the room has been left on the server, we can clean up the current scene and prepare
/// to load the next scene.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RoomLeaveResult(object sender, RoomLeaveResultEventArgs e)
{
if (e.Success)
{
// now we can change levels
Debug.Log("Player has now left level");
//TODO zpwh
//send message to GUI_Button to let it know it's okay to reset position
/*GameObject gui = GameObject.FindWithTag("GUI");
gui.GetComponent("GUI_Button").NewLevel();*/
/*GUI_Button someScript;
someScript = GetComponent<GUI_Button>();
someScript.NewLevel();*/
UnwireLocalPlayerEvents();
jibeServerInstance.NewRemotePlayer -= new RemotePlayerEventHandler(jibeServerInstance_NewRemotePlayer);
jibeServerInstance.LostRemotePlayer -= new RemotePlayerEventHandler(jibeServerInstance_LostRemotePlayer);
jibeServerInstance.NewChatMessage -= new ChatEventHandler(jibeServerInstance_NewChatMessage);
jibeServerInstance.NewBroadcastChatMessage -= new BroadcastChatEventHandler(jibeServerInstance_NewBroadcastChatMessage);
jibeServerInstance.NewPrivateChatMessage -= new PrivateChatEventHandler(jibeServerInstance_NewPrivateChatMessage);
jibeServerInstance.RoomJoinResult -= new RoomJoinResultEventHandler(RoomJoinResult);
jibeServerInstance.RoomLeaveResult -= new RoomLeaveResultEventHandler(RoomLeaveResult);
jibeServerInstance.CustomDataEvent -= new CustomDataEventHandler(jibeServerInstance_CustomDataEvent);
if (!string.IsNullOrEmpty(_nextLevel))
{
Debug.Log("Changing to new scene " + _nextLevel);
Application.LoadLevel(_nextLevel);
}
else
{
// If it is null then user is logging out instead of switching levels
localPlayer.RaiseDisconnect();
if (!string.IsNullOrEmpty(navigateUrl))
{
try
{
Application.OpenURL(navigateUrl);
}
catch
{
Debug.Log("Failed to open URL!");
}
}
else
{
// User is quitting - this gives us the option of a "quit" box in the UI
Application.Quit();
}
}
}
else
{
Debug.Log("Room leave FAIL " + e.Message);
}
}
void jibeServerInstance_NewChatMessage(object sender, ChatEventArgs e)
{
ChatMessageReceived(e.Message, e.SendingPlayer);
}
void jibeServerInstance_NewBroadcastChatMessage(object sender, BroadcastChatEventArgs e)
{
BroadcastChatMessageReceived(e.Message);
}
void jibeServerInstance_NewPrivateChatMessage(object sender, PrivateChatEventArgs e)
{
PrivateChatMessageReceived(e.Message, e.SendingPlayer);
}
void jibeServerInstance_LostRemotePlayer(object sender, RemotePlayerEventArgs e)
{
playerLeavingInterval = 0.0f;
pendingLeavingPlayers.Add(e.RemotePlayer.PlayerID, e.RemotePlayer.Name);
GameObject remotePlayerObject = GameObject.Find(RemotePlayerGameObjectPrefix + e.RemotePlayer.PlayerID);
if (remotePlayerObject != null)
{
processLogoutEvents(e.RemotePlayer.PlayerID);
Destroy(remotePlayerObject);
}
}
/// <summary>
/// Handle a new Remote Player joining the scene
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void jibeServerInstance_NewRemotePlayer(object sender, RemotePlayerEventArgs e)
{
lonely=false;
IJibePlayer remotePlayer = e.RemotePlayer;
bool spawned = false;
NetworkReceiver ntr = null;
AnimationSynchronizer anisync = null;
Debug.Log("Spawn new remote player " + remotePlayer.Name + ", ID: " + remotePlayer.PlayerID);
GameObject remotePlayerObject = null;
remotePlayer.AppearanceUpdated += delegate
{
if (!spawned)
{
remotePlayerObject = GetComponent<PlayerSpawnController>().SpawnRemotePlayer(remotePlayer);
ntr = remotePlayerObject.GetComponent<NetworkReceiver>();
anisync = remotePlayerObject.GetComponent<AnimationSynchronizer>();
jibeServerInstance.RequestFullUpdate(remotePlayer);
spawned = true;
}
Texture2D newSkin = (Texture2D)Resources.Load(remotePlayer.Skin);
remotePlayerObject.GetComponent<NetworkReceiver>().SetSkinRemote(newSkin);
};
remotePlayer.TransformUpdated += delegate
{
if (spawned)
{
Vector3 newPosition = new Vector3(remotePlayer.PosX, remotePlayer.PosY, remotePlayer.PosZ);
Quaternion newRotation = new Quaternion(remotePlayer.RotX, remotePlayer.RotY, remotePlayer.RotZ, remotePlayer.RotW);
ntr.ReceiveTransform(newPosition, newRotation);
if (!spawnedPlayers.Contains(remotePlayer.Name))
{
GetComponent<PlayerSpawnController>().ShowSpawnParticles(newPosition, newRotation);
GetComponent<PlayerSpawnController>().PlaySpawnSound();
spawnedPlayers.Add(remotePlayer.Name);
}
}
};
remotePlayer.AnimationUpdated += delegate
{
if (spawned)
{
anisync.PlayAnimation(remotePlayer.Animation.ToString());
}
};
// Jibe doesn't currently do much on a name change event,
// but it is anticipated that in future, this will be used.
remotePlayer.NameUpdated += delegate
{
if (spawned)
{
Debug.Log("Name Updated for " + remotePlayer.Name);
}
};
remotePlayer.VoiceUpdated += delegate
{
if (spawned)
{
//remotePlayerObject.GetComponent<BubblePopup>().SetSpeaking(remotePlayer.Voice == JibePlayerVoice.IsSpeaking);
}
};
remotePlayer.Disconnected += delegate
{
Debug.Log("Remote player leaving");
playerLeavingInterval = 0.0f;
pendingLeavingPlayers.Add(remotePlayer.PlayerID, remotePlayer.Name);
if (remotePlayerObject != null)
{
Destroy(remotePlayerObject);
}
};
}
void jibeServerInstance_CustomDataEvent(object sender, CustomDataEventArgs e)
{
// Debug.Log("Custom data received from " + e.SendingPlayer.Name + "!");
// Handle incoming custom data here!
/*
* Now you have your dictionary of data:
* Dictionary<string, string> dataReceived = e.CustomData;
* And you have the sending player:
* IJibePlayer player = e.SendingPlayer;
*/
// Now you can pass this to the appropriate game object and component.
//GameObject customDataObject = GameObject.Find("SampleCustomData");
//if (customDataObject != null)
// {
// customDataObject.GetComponent<SampleCustomData>().ShowReceivedData(e.CustomData, e.SendingPlayer.Name);
// }
Dictionary<string, string> dataReceived = e.CustomData;
// Debug.Log("Custom data was: " + dataReceived["MethodToCall"]);
if (dataReceived["SendingObjectName"] != null)
{
GameObject customDataObject = GameObject.Find(dataReceived["SendingObjectName"]);
// Debug.Log("SendingObjectName was not null");
// Generic receiver - this should mean you never have to add code directly to Network Controller again!
if (dataReceived["MethodToCall"] != null)
{
// Debug.Log("Calling custom method");
customDataObject.SendMessage(dataReceived["MethodToCall"], e.CustomData);
}
// Specifically for iTween, and also useful sample code!
if (dataReceived["iTweenEventToFire"] != null)
{
customDataObject.GetComponent<JibeiTweenClick>().ProcessEvent(e.CustomData, e.SendingPlayer.Name);
}
else
{
customDataObject.GetComponent<SampleCustomData>().ShowReceivedData(e.CustomData, e.SendingPlayer.Name);
}
}
}
#endregion
#region Middle-man methods - handle calls from other code to do things that require interaction with the server!
/// <summary>
/// Called by scripts to change the current level (a term representing the combination of a 3D scene and a network room)
/// </summary>
/// <param name="levelName">Name of the level to join (the Scene name)</param>
public void ChangeLevel(string levelName)
{
if (levelName != defaultRoom)
{
_nextLevel = levelName;
Debug.Log("-- Leaving level --");
SendMessageToAllJibeObjects("JibeExit");
jibeServerInstance.LeaveRoom();
// now wait for RoomLeaveResult to process before moving to next level
}
else
{
Debug.LogWarning("Can't change to new level - room name is the same as current room!");
}
}
/// <summary>
/// Called by scripts to send a message to disconnect the current local player and leave the room before loading a new URL -
/// clean up dead remote players for other people
/// </summary>
/// <param name="urlOfDestination">Optional url of new jibe space to load, if you just want to leave, pass in null</param>
public void DisconnectLocalPlayer(string urlOfDestination)
{
_nextLevel = null; // force this to null so that the RoomLeaveResult callback doesn't switch levels, and instead it disconnects the player
navigateUrl = urlOfDestination;
SendMessageToAllJibeObjects("JibeExit");
Debug.Log("-- Leaving level --");
jibeServerInstance.LeaveRoom();
// now wait for RoomLeaveResult to process before moving to next level
}
public void SendCustomData(Dictionary<string, string> dataToSend)
{
string[] users = new string[0];
SendCustomData(dataToSend, false, users);
}
public void SendCustomData(Dictionary<string, string> dataToSend, bool clobber)
{
string[] users = new string[0];
SendCustomData(dataToSend, clobber, users);
}
public void SendCustomData(Dictionary<string, string> dataToSend, bool clobber, string[] destroyOnUsersExit, bool isLocallySynced)
{
if(!isLocallySynced)
{
SendCustomData(dataToSend, clobber, destroyOnUsersExit);
}
else
{
if(clobber)
{
bool found=false;
for(int i = 0; i<localDataToSync.Count; i++)
{
if(localDataToSync[i]["MethodToCall"].Equals(dataToSend["MethodToCall"]))
{
if(localDataToSync[i]["SendingObjectName"].Equals(dataToSend["SendingObjectName"]))
{
localDataToSync[i]=dataToSend;
found=true;
break;
}
}
}
if(!found)
{
localDataToSync.Add(dataToSend);
}
}
else
{
localDataToSync.Add(dataToSend);
}
jibeServerInstance.SendCustomData(dataToSend);
}
}
public void SendCustomData(Dictionary<string, string> dataToSend, bool clobber, string[] destroyOnUsersExit) //removed all of jibe code and replaced with my own clobber is used if we want this particular function to only have the latest version stored, e.g. in the tag game where we only need to know the current person who is it. destroyonusersexit is for destroying data when user leaves, i.e. when a user is holding an object
{
if(jibeServerInstance!=null)
{
// Send Custom data here!
/* Sample Code (also see SampleCustomData.cs):
* in your class that calls this method, construct a Dictionary object as follows
* Dictionary<string, string> dataToSend = new Dictionary<string, string>();
* You may need to add "using System.Collections.Generic" to the top of your code
* Then add things to the dictionary:
* dataToSend[key] = value;
* where Key is like a lookup or column value (item1, item2, etc.)
* and a Value is the actual value to send.
* Then, find the NetworkController component of the NetworkController game object, and call this method
* and pass in the dataToSend. Your data is then broadcast to others.
* The incoming messages will arrive in the CustomDataEvent above.
*/
int indexAddedAt=0;
bool send=false;
Dictionary<string, string> destroyDict = new Dictionary<string, string>();
destroyDict["MethodToCall"] = "addToDestroyTable";
destroyDict["SendingObjectName"] = "NetworkController";
destroyDict["Clobber"]="false";
if(dataToSend.ContainsKey("MethodToCall") && !dataToSend.ContainsKey("SyncData")/* && !(dataToSend["SendingObjectName"].Equals("NetworkController") && dataToSend["MethodToCall"]!="AddMemberToGroup")*/) //checking that this is not data being sent to sync another player so that it does not sync the syncing
{
send=true;
if(clobber)
{
bool found = false;
for(int i=0; i<dataToSync.Count; i++)
{
if(dataToSync[i]["MethodToCall"].Equals(dataToSend["MethodToCall"]))
{
dataToSync[i]=dataToSend;
found=true;
indexAddedAt=i;
break;
}
}
if(!found)
{
Debug.Log("Added data to sync queue: " + dataToSend["MethodToCall"]);
dataToSync.Add(dataToSend);
indexAddedAt=dataToSync.Count-1;
}
}
else
{
Debug.Log("Added data to sync queue: " + dataToSend["MethodToCall"]);
dataToSync.Add(dataToSend); //RSO
indexAddedAt=dataToSync.Count-1;
}
destroyDict["DestroyIndex"] = ""+indexAddedAt;
foreach(string currentPlayerID in destroyOnUsersExit)
{
destroyDict[currentPlayerID] = "t";
}
}
if(clobber) //this part here is so that the sender knows it is ok to clobber the code so that both users don't have to do the calculations
{
dataToSend["Clobber"] = "true";
}
else
{
dataToSend["Clobber"] = "false";
}
jibeServerInstance.SendCustomData(dataToSend);
//P2PController.GenericDataSender(dataToSend);
if(send)
{
jibeServerInstance.SendCustomData(destroyDict);
addToDestroyTable(destroyDict);
}
dataToSend["SyncData"] = "true";
}
else
{
Debug.LogWarning("Attempted to send custom data before the server was initialized");
}
}
#endregion
#region Local Player Updates
public void SendTransform(Transform trans)
{
localPlayer.PosX = trans.position.x;
localPlayer.PosY = trans.position.y-2.5f;
localPlayer.PosZ = trans.position.z;
localPlayer.RotX = 0;
localPlayer.RotY = trans.rotation.y;
localPlayer.RotZ = 0;
localPlayer.RotW = trans.rotation.w;
_networkIdle = 0.0f;
}
public void UpdateSkin(string skin)
{
localPlayer.Skin = skin;
_networkIdle = 0.0f;
}
public void UpdateHair(string hair)
{
localPlayer.Hair = hair;
_networkIdle = 0.0f;
}
public void UpdateAvatar(int avatar)
{
localPlayer.AvatarModel = avatar;
_networkIdle = 0.0f;
}
public void SetVoice(JibePlayerVoice voiceStatus)
{
localPlayer.Voice = voiceStatus;
_networkIdle = 0.0f;
}
public void SendAppearance(string skin, string hair, int avatar)
{
localPlayer.Skin = skin;
localPlayer.Hair = hair;
localPlayer.AvatarModel = avatar;
jibeServerInstance.SendAppearance();
_networkIdle = 0.0f;
}
public void SendAnimation(string animationToPlay)
{
localPlayer.Animation = animationToPlay;
jibeServerInstance.SendAnimation(animationToPlay);
_networkIdle = 0.0f;
}
#endregion
#region Incoming Chat Messages
public void ChatMessageReceived(string message, IJibePlayer fromUser)
{
Debug.Log("Received message from player with id: " + fromUser.PlayerID);
int userId = fromUser.PlayerID;
if(userId != localPlayer.PlayerID)
{
/*if(onlyChatWithGroup[localPlayer.PlayerID].Equals("GlobalChat")) //non group chat - changed so that the globalchat is the same as any other group, and it is only that all users are able to view its contents sop this part should be obsolete
{
Debug.Log("Sender was in GlobalChat");
string spokenMessage = fromUser.Name + ": " + message;
// Send chat message to the Chat Controller
chatController.AddChatMessage(message, fromUser.Name);
//Find player object with such Id
GameObject user = GameObject.Find(RemotePlayerGameObjectPrefix + userId);
//If found - send bubble message
if (user != null)
{
user.SendMessage("ShowBubble", spokenMessage);
}
}
else //groupchat
{*/
bool inGroup=false;
if(!onlyChatWithGroup.ContainsKey(fromUser.PlayerID))
{
onlyChatWithGroup[fromUser.PlayerID]="GlobalChat";
}
if(onlyChatWithGroup[localPlayer.PlayerID].Equals(onlyChatWithGroup[fromUser.PlayerID]))
{
inGroup=true;
}
if(!inGroup)
{
chatController.AddMessage(message, fromUser.Name, onlyChatWithGroup[fromUser.PlayerID]);
Debug.Log("Received chat message from non group member:"+fromUser.Name+" - storing it in group: " + onlyChatWithGroup[fromUser.PlayerID]);
}
if (inGroup)
{ // If it's not myself
string spokenMessage = fromUser.Name + ": " + message;
// Send chat message to the Chat Controller
chatController.AddMessage(message, fromUser.Name, onlyChatWithGroup[fromUser.PlayerID]);
//Find player object with such Id
GameObject user = GameObject.Find(RemotePlayerGameObjectPrefix + userId);
//If found - send bubble message
if (user != null)
{
user.SendMessage("ShowBubble", spokenMessage);
}
//}
}
}
_networkIdle = 0.0f;
}
public void BroadcastChatMessageReceived(string message)
{
// Send chat message to the Chat Controller
chatController.AddMessage(message, "GlobalChat", "SYSTEM");
_networkIdle = 0.0f;
}
public void PrivateChatMessageReceived(string message, IJibePlayer fromUser)
{
int userId = fromUser.PlayerID;
if (fromUser.PlayerID != localPlayer.PlayerID)
{
string spokenMessage = fromUser.Name + ": " + message;
// Send chat message to the Chat Controller
chatController.AddPrivateChatMessage(message, fromUser.Name, fromUser.PlayerID);
//Find player object with such Id
GameObject user = GameObject.Find(RemotePlayerGameObjectPrefix + userId);
//If found - send bubble message
if (user != null)
{
user.SendMessage("ShowBubble", spokenMessage);
}
}
}
#endregion
#region Outgoing Chat Messages
public void SendChatMessage(string chatMessage)
{
jibeServerInstance.SendChatMessage(chatMessage);
_networkIdle = 0.0f;
}
public void SendPrivateChatMessage(string chatMessage, int recipient)
{
Debug.Log("Sending private message " + chatMessage + " to " + recipient);
jibeServerInstance.SendPrivateChatMessage(chatMessage, recipient);
_networkIdle = 0.0f;
}
#endregion
//RSO begin
public void Synchronize()
{
if(!synced && host!=localPlayer)
{
Debug.Log("Sending synchronization request");
Dictionary<string,string> dataToSend= new Dictionary<string, string>();
dataToSend["SendingObjectName"] = "NetworkController";
dataToSend["MethodToCall"] = "RespondSynchronization";
SendCustomData(dataToSend);
synced=true;
}
}
public void RespondSynchronization(Dictionary<string,string> data)
{
Debug.Log("Responding");
if(host==localPlayer)
{
Debug.Log("Recieved sync request");
for(int i=0;i<dataToSync.Count;i++)
{
SendCustomData(dataToSync[i]);
Debug.Log("Sending sync data " + dataToSync[i]["MethodToCall"]);
}
Dictionary<string, string> hostData = new Dictionary<string, string>();
hostData["SendingObjectName"] = "NetworkController";
hostData["MethodToCall"] = "setHost";
hostData["host"] = "" + host.PlayerID;
SendCustomData(hostData);
Debug.Log("Sent sync");
}
else
{
Debug.Log("It isn't my job to sync you!");
}
foreach(Dictionary<string,string> currentDict in localDataToSync)
{
Debug.Log("syncing local data: " + currentDict["MethodToCall"]);
SendCustomData(currentDict);
}
}
public void setHost(Dictionary<string, string> hostData) //we need to assign a host to do all the calculations that should be server side, but since we can only do client side calculations we have the host pretend to be the server
{
Debug.Log("host is now" + hostData["host"]);
foreach (IJibePlayer activeplayer in jibeServerInstance.Players)
{
if((""+activeplayer.PlayerID).Equals(hostData["host"]))
{
host=activeplayer;
break;
}
}
}
public void processLogoutEvents(int id)
{
try
{
Debug.Log("Player left - cleaning up networked data they left behind");
if(host==null) //assigning new host
{
int lowest = localPlayer.PlayerID;
host=localPlayer;
foreach (IJibePlayer activeplayer in jibeServerInstance.Players)
{
if(activeplayer.PlayerID<lowest)
{
host=activeplayer;
lowest = activeplayer.PlayerID;
}
}
}
if(destroyTable.ContainsKey(""+id)) //checks if any items should be removed from syncing now that player left
{
foreach(string methodToDestroy in destroyTable[""+id])
{
Debug.Log("Removing a method now that player has left");
int index;
bool success = Int32.TryParse(methodToDestroy, out index);
if(success)
{
if(dataToSync.Count>index) //in case it was already destroyed by another player leaving
{
dataToSync[index]=null; //can't remove or all other indexes will be confused
}
}
else
{
Debug.Log(methodToDestroy+ " is not a valid index");
}
}
destroyTable.Remove(""+id); //clean up
}
if(managementOnlineUsers.FindChild(""+id)!=null)
{
Destroy(managementOnlineUsers.FindChild(""+id).gameObject);
}
if(unionOnlineUsers.FindChild(""+id)!=null)
{
Destroy(unionOnlineUsers.FindChild(""+id).gameObject);
}
groups.Remove(id);
Destroy(onlineUserGrid.transform.FindChild(""+id).gameObject); // this should be the online user gameobject
repositionNextUpdate=true; //we can't reposition the grid now because the gameobject will not be destroyed until the next update so we destroy it then.
// onlineUserGrid.repositionNow=true;
}
catch(Exception e)
{
Debug.LogError(e);
}
}
public void addToDestroyTable(Dictionary<string,string>destroyDict)
{
string index = destroyDict["DestroyIndex"];
Dictionary<string,string>.KeyCollection keys = destroyDict.Keys; //need to turn into a KeyCollection so that it is iterable
foreach(string playerToAdd in keys) //removing keys for index etc. not worth time it takes to check, just add and ignore them
{
if(destroyTable.ContainsKey(playerToAdd)) //checking if this is first instance of player having item in removetable
{
destroyTable[playerToAdd].Add(index);
}
else
{
destroyTable[playerToAdd]=new List<string>();
destroyTable[playerToAdd].Add(index);
}
}
}
//RSO Group stuff
public void AddMemberToGroup(Dictionary<string,string> groupInfo)
{
AddMemberToGroup(groupInfo["Group"],Int32.Parse(groupInfo["PlayerID"]), groupInfo["PlayerName"]);
}
public void AddMemberToGroup(string groupName, int playerIDToAdd, string playerNameToAdd)
{
bool addToOnlineUsers=false;
Debug.Log("Attempting to add member to a group");
if(groups.ContainsKey(playerIDToAdd))
{
if(!groups[playerIDToAdd].Contains(groupName))
{
addToOnlineUsers=true;
groups[playerIDToAdd].Add(groupName);
Debug.Log("Successfully added player with ID:" + playerIDToAdd + "to group:" +groupName);
}
}
else
{
addToOnlineUsers=true;
groups[playerIDToAdd] = new List<string>();
groups[playerIDToAdd].Add(groupName);
Debug.Log("Successfully added player with ID:" + playerIDToAdd + " to group:" +groupName);
}
if(playerNameToAdd!=localPlayer.Name && addToOnlineUsers==true)
{
if(groupName=="Management")
{
Transform newOnlineUser = GameObject.Instantiate(onlineUserPrefab) as Transform;
newOnlineUser.parent=managementOnlineUsers;
newOnlineUser.name=""+playerIDToAdd;
newOnlineUser.localPosition=new Vector3(newOnlineUser.localPosition.x,newOnlineUser.localPosition.y, -17f);
newOnlineUser.GetComponentInChildren<UILabel>().text=playerNameToAdd;
managementOnlineUsers.GetComponent<UIGrid>().repositionNow=true;
}
else if(groupName=="Union")
{
Transform newOnlineUser = GameObject.Instantiate(onlineUserPrefab) as Transform;
newOnlineUser.parent=unionOnlineUsers;
newOnlineUser.name=""+playerIDToAdd;
newOnlineUser.localPosition=new Vector3(newOnlineUser.localPosition.x,newOnlineUser.localPosition.y, -17f);
newOnlineUser.GetComponentInChildren<UILabel>().text=playerNameToAdd;
unionOnlineUsers.GetComponent<UIGrid>().repositionNow=true;
}
}
}
public void RemoveMemberFromGroup(string groupName, int playerIDToAdd)
{
if(groups[playerIDToAdd]!=null)
{
groups[playerIDToAdd].Remove(groupName);
}
}
public void SetCurrentGroup(string groupName, int playerID)
{
Debug.Log("Received an update to my current group");
onlyChatWithGroup[playerID] = groupName;
Dictionary<string,string> syncCurrentGroup = new Dictionary<string, string>();
syncCurrentGroup["MethodToCall"] = "SetCurrentGroup2";
syncCurrentGroup["SendingObjectName"] = "NetworkController";
syncCurrentGroup["Group"] = groupName;
syncCurrentGroup["ID"] = playerID.ToString();
SendCustomData(syncCurrentGroup, true, new string[0], true);
if(playerID==localPlayer.PlayerID)
{
/*if(groupName.Equals("GlobalChat"))
{
Application.ExternalCall("DisplayChatBox", "UnionPlaque");
Application.ExternalCall("DisplayChatBox", "ManagementPlaque");
}
else
{
Application.ExternalCall("DisplayChatBox", groupName+"Plaque");
}*/
}
}
public void SetCurrentGroup2(Dictionary<string,string> data)// this does the same thing as the above script, but it won't let me have helper methods for some reason when i use sendmessage
{
Debug.Log("Received an update to current group from another player");
onlyChatWithGroup[Int32.Parse(data["ID"])] = data["Group"];
}
public bool CheckIfLocalPlayerIsInGroup(string groupName)
{
if(groups!=null && localPlayer!=null && groups.ContainsKey(localPlayer.PlayerID)) //so it doesn't crash if the localPlayer hasn't finished initializing yet
{
foreach(string currentGroup in groups[localPlayer.PlayerID])
{
if(currentGroup.Equals(groupName))
{
return true;
}
}
}
return false;
}
//rso end
}
| |
/*
* Trace.cs - Implementation of the
* "System.Diagnostics.Trace" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define TRACE
namespace System.Diagnostics
{
#if !ECMA_COMPAT
using System.Configuration;
using System.Collections;
public sealed class Trace
{
// Internal state.
private static bool initialized = false;
private static bool autoFlush;
private static int indentLevel;
private static int indentSize = 4;
private static TraceListenerCollection listeners;
internal static Hashtable switches;
// This class cannot be instantiated.
private Trace() {}
// Make sure that the trace configuration is loaded.
internal static void Initialize()
{
// Bail out if already initialized, or called recursively.
if(initialized)
{
return;
}
initialized = true;
// Create the default trace listener.
DefaultTraceListener defListener =
new DefaultTraceListener();
// Create the initial listeners collection.
listeners = new TraceListenerCollection();
listeners.Add(defListener);
// Get the diagnostics configuration options.
Hashtable options = (Hashtable)
ConfigurationSettings.GetConfig
("system.diagnostics",
new DiagnosticsConfigurationHandler());
if(options == null)
{
options = new Hashtable();
}
// Process the options for the default trace listener.
Object value = options["assertuienabled"];
if(value != null)
{
defListener.AssertUiEnabled = (bool)value;
}
value = options["logfilename"];
if(value != null)
{
defListener.LogFileName = (String)value;
}
// Process the trace options.
value = options["autoflush"];
if(value != null)
{
autoFlush = (bool)value;
}
value = options["indentsize"];
if(value != null)
{
indentSize = (int)value;
}
switches = (Hashtable)(options["switches"]);
}
// Global trace properties.
public static bool AutoFlush
{
get
{
lock(typeof(Trace))
{
Initialize();
return autoFlush;
}
}
set
{
lock(typeof(Trace))
{
Initialize();
autoFlush = value;
}
}
}
public static int IndentLevel
{
get
{
lock(typeof(Trace))
{
Initialize();
return indentLevel;
}
}
set
{
lock(typeof(Trace))
{
Initialize();
if(value < 0)
{
value = 0;
}
indentLevel = value;
foreach(TraceListener listener in Listeners)
{
listener.IndentLevel = value;
}
}
}
}
public static int IndentSize
{
get
{
lock(typeof(Trace))
{
Initialize();
return indentSize;
}
}
set
{
lock(typeof(Trace))
{
Initialize();
if(value < 0)
{
value = 0;
}
indentSize = value;
foreach(TraceListener listener in Listeners)
{
listener.IndentSize = value;
}
}
}
}
public static TraceListenerCollection Listeners
{
get
{
lock(typeof(Trace))
{
Initialize();
return listeners;
}
}
}
// Assert on a particular condition.
[Conditional("TRACE")]
public static void Assert(bool condition)
{
if(!condition)
{
Fail(String.Empty, null);
}
}
[Conditional("TRACE")]
public static void Assert(bool condition, String message)
{
if(!condition)
{
Fail(message, null);
}
}
[Conditional("TRACE")]
public static void Assert(bool condition, String message,
String detailMessage)
{
if(!condition)
{
Fail(message, detailMessage);
}
}
// Flush and close all listeners.
[Conditional("TRACE")]
public static void Close()
{
foreach(TraceListener listener in Listeners)
{
listener.Close();
}
}
// Record that some condition has failed.
[Conditional("TRACE")]
public static void Fail(String message)
{
Fail(message, null);
}
[Conditional("TRACE")]
public static void Fail(String message, String detailMessage)
{
foreach(TraceListener listener in Listeners)
{
listener.Fail(message, detailMessage);
}
}
// Flush all trace listeners.
[Conditional("TRACE")]
public static void Flush()
{
foreach(TraceListener listener in Listeners)
{
listener.Flush();
}
}
// Increase the indent level by one.
[Conditional("TRACE")]
public static void Indent()
{
IndentLevel = IndentLevel + 1;
}
// Decrease the indent level by one.
[Conditional("TRACE")]
public static void Unindent()
{
int level = IndentLevel - 1;
if(level >= 0)
{
IndentLevel = level;
}
}
// Write a message to all trace listeners.
[Conditional("TRACE")]
public static void Write(Object value)
{
foreach(TraceListener listener in Listeners)
{
listener.Write(value);
if(AutoFlush)
{
listener.Flush();
}
}
}
[Conditional("TRACE")]
public static void Write(String message)
{
foreach(TraceListener listener in Listeners)
{
listener.Write(message);
if(AutoFlush)
{
listener.Flush();
}
}
}
[Conditional("TRACE")]
public static void Write(Object value, String category)
{
foreach(TraceListener listener in Listeners)
{
listener.Write(value, category);
if(AutoFlush)
{
listener.Flush();
}
}
}
[Conditional("TRACE")]
public static void Write(String message, String category)
{
foreach(TraceListener listener in Listeners)
{
listener.Write(message, category);
if(AutoFlush)
{
listener.Flush();
}
}
}
// Write a message to all trace listeners if a condition is true.
[Conditional("TRACE")]
public static void WriteIf(bool condition, Object value)
{
if(condition)
{
Write(value);
}
}
[Conditional("TRACE")]
public static void WriteIf(bool condition, String message)
{
if(condition)
{
Write(message);
}
}
[Conditional("TRACE")]
public static void WriteIf(bool condition, Object value, String category)
{
if(condition)
{
Write(value, category);
}
}
[Conditional("TRACE")]
public static void WriteIf(bool condition, String message, String category)
{
if(condition)
{
Write(message, category);
}
}
// Write a message to all trace listeners.
[Conditional("TRACE")]
public static void WriteLine(Object value)
{
foreach(TraceListener listener in Listeners)
{
listener.WriteLine(value);
if(AutoFlush)
{
listener.Flush();
}
}
}
[Conditional("TRACE")]
public static void WriteLine(String message)
{
foreach(TraceListener listener in Listeners)
{
listener.WriteLine(message);
if(AutoFlush)
{
listener.Flush();
}
}
}
[Conditional("TRACE")]
public static void WriteLine(Object value, String category)
{
foreach(TraceListener listener in Listeners)
{
listener.WriteLine(value, category);
if(AutoFlush)
{
listener.Flush();
}
}
}
[Conditional("TRACE")]
public static void WriteLine(String message, String category)
{
foreach(TraceListener listener in Listeners)
{
listener.WriteLine(message, category);
if(AutoFlush)
{
listener.Flush();
}
}
}
// Write a message to all trace listeners if a condition is true.
[Conditional("TRACE")]
public static void WriteLineIf(bool condition, Object value)
{
if(condition)
{
WriteLine(value);
}
}
[Conditional("TRACE")]
public static void WriteLineIf(bool condition, String message)
{
if(condition)
{
WriteLine(message);
}
}
[Conditional("TRACE")]
public static void WriteLineIf
(bool condition, Object value, String category)
{
if(condition)
{
WriteLine(value, category);
}
}
[Conditional("TRACE")]
public static void WriteLineIf
(bool condition, String message, String category)
{
if(condition)
{
WriteLine(message, category);
}
}
}; // class Trace
#endif // !ECMA_COMPAT
}; // namespace System.Diagnostics
| |
// 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.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Threading.Tests
{
public static class ReaderWriterLockSlimTests
{
[Fact]
public static void Ctor()
{
ReaderWriterLockSlim rwls;
using (rwls = new ReaderWriterLockSlim())
{
Assert.Equal(LockRecursionPolicy.NoRecursion, rwls.RecursionPolicy);
}
using (rwls = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion))
{
Assert.Equal(LockRecursionPolicy.NoRecursion, rwls.RecursionPolicy);
}
using (rwls = new ReaderWriterLockSlim((LockRecursionPolicy)12345))
{
Assert.Equal(LockRecursionPolicy.NoRecursion, rwls.RecursionPolicy);
}
using (rwls = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion))
{
Assert.Equal(LockRecursionPolicy.SupportsRecursion, rwls.RecursionPolicy);
}
}
[Fact]
public static void Dispose()
{
ReaderWriterLockSlim rwls;
rwls = new ReaderWriterLockSlim();
rwls.Dispose();
Assert.Throws<ObjectDisposedException>(() => rwls.TryEnterReadLock(0));
Assert.Throws<ObjectDisposedException>(() => rwls.TryEnterUpgradeableReadLock(0));
Assert.Throws<ObjectDisposedException>(() => rwls.TryEnterWriteLock(0));
rwls.Dispose();
for (int i = 0; i < 3; i++)
{
rwls = new ReaderWriterLockSlim();
switch (i)
{
case 0: rwls.EnterReadLock(); break;
case 1: rwls.EnterUpgradeableReadLock(); break;
case 2: rwls.EnterWriteLock(); break;
}
Assert.Throws<SynchronizationLockException>(() => rwls.Dispose());
}
}
[Fact]
public static void EnterExit()
{
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Assert.False(rwls.IsReadLockHeld);
rwls.EnterReadLock();
Assert.True(rwls.IsReadLockHeld);
rwls.ExitReadLock();
Assert.False(rwls.IsReadLockHeld);
Assert.False(rwls.IsUpgradeableReadLockHeld);
rwls.EnterUpgradeableReadLock();
Assert.True(rwls.IsUpgradeableReadLockHeld);
rwls.ExitUpgradeableReadLock();
Assert.False(rwls.IsUpgradeableReadLockHeld);
Assert.False(rwls.IsWriteLockHeld);
rwls.EnterWriteLock();
Assert.True(rwls.IsWriteLockHeld);
rwls.ExitWriteLock();
Assert.False(rwls.IsWriteLockHeld);
Assert.False(rwls.IsUpgradeableReadLockHeld);
rwls.EnterUpgradeableReadLock();
Assert.False(rwls.IsWriteLockHeld);
Assert.True(rwls.IsUpgradeableReadLockHeld);
rwls.EnterWriteLock();
Assert.True(rwls.IsWriteLockHeld);
rwls.ExitWriteLock();
Assert.False(rwls.IsWriteLockHeld);
Assert.True(rwls.IsUpgradeableReadLockHeld);
rwls.ExitUpgradeableReadLock();
Assert.False(rwls.IsUpgradeableReadLockHeld);
Assert.True(rwls.TryEnterReadLock(0));
rwls.ExitReadLock();
Assert.True(rwls.TryEnterReadLock(Timeout.InfiniteTimeSpan));
rwls.ExitReadLock();
Assert.True(rwls.TryEnterUpgradeableReadLock(0));
rwls.ExitUpgradeableReadLock();
Assert.True(rwls.TryEnterUpgradeableReadLock(Timeout.InfiniteTimeSpan));
rwls.ExitUpgradeableReadLock();
Assert.True(rwls.TryEnterWriteLock(0));
rwls.ExitWriteLock();
Assert.True(rwls.TryEnterWriteLock(Timeout.InfiniteTimeSpan));
rwls.ExitWriteLock();
}
}
[Fact]
public static void DeadlockAvoidance()
{
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
rwls.EnterReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterReadLock());
Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock());
Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock());
rwls.ExitReadLock();
rwls.EnterUpgradeableReadLock();
rwls.EnterReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterReadLock());
rwls.ExitReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock());
rwls.EnterWriteLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock());
rwls.ExitWriteLock();
rwls.ExitUpgradeableReadLock();
rwls.EnterWriteLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterReadLock());
Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock());
Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock());
rwls.ExitWriteLock();
}
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion))
{
rwls.EnterReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterWriteLock());
rwls.EnterReadLock();
Assert.Throws<LockRecursionException>(() => rwls.EnterUpgradeableReadLock());
rwls.ExitReadLock();
rwls.ExitReadLock();
rwls.EnterUpgradeableReadLock();
rwls.EnterReadLock();
rwls.EnterUpgradeableReadLock();
rwls.ExitUpgradeableReadLock();
rwls.EnterReadLock();
rwls.ExitReadLock();
rwls.ExitReadLock();
rwls.EnterWriteLock();
rwls.EnterWriteLock();
rwls.ExitWriteLock();
rwls.ExitWriteLock();
rwls.ExitUpgradeableReadLock();
rwls.EnterWriteLock();
rwls.EnterReadLock();
rwls.ExitReadLock();
rwls.EnterUpgradeableReadLock();
rwls.ExitUpgradeableReadLock();
rwls.EnterWriteLock();
rwls.ExitWriteLock();
rwls.ExitWriteLock();
}
}
[Theory]
[InlineData(LockRecursionPolicy.NoRecursion)]
[InlineData(LockRecursionPolicy.SupportsRecursion)]
public static void InvalidExits(LockRecursionPolicy policy)
{
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim(policy))
{
Assert.Throws<SynchronizationLockException>(() => rwls.ExitReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitUpgradeableReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock());
rwls.EnterReadLock();
Assert.Throws<SynchronizationLockException>(() => rwls.ExitUpgradeableReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock());
rwls.ExitReadLock();
rwls.EnterUpgradeableReadLock();
Assert.Throws<SynchronizationLockException>(() => rwls.ExitReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock());
rwls.ExitUpgradeableReadLock();
rwls.EnterWriteLock();
Assert.Throws<SynchronizationLockException>(() => rwls.ExitReadLock());
Assert.Throws<SynchronizationLockException>(() => rwls.ExitUpgradeableReadLock());
rwls.ExitWriteLock();
using (Barrier barrier = new Barrier(2))
{
Task t = Task.Factory.StartNew(() =>
{
rwls.EnterWriteLock();
barrier.SignalAndWait();
barrier.SignalAndWait();
rwls.ExitWriteLock();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
barrier.SignalAndWait();
Assert.Throws<SynchronizationLockException>(() => rwls.ExitWriteLock());
barrier.SignalAndWait();
t.GetAwaiter().GetResult();
}
}
}
[Fact]
public static void InvalidTimeouts()
{
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterReadLock(-2));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterUpgradeableReadLock(-3));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterWriteLock(-4));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterReadLock(TimeSpan.MaxValue));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterUpgradeableReadLock(TimeSpan.MinValue));
Assert.Throws<ArgumentOutOfRangeException>(() => rwls.TryEnterWriteLock(TimeSpan.FromMilliseconds(-2)));
}
}
[Fact]
public static void WritersAreMutuallyExclusiveFromReaders()
{
using (Barrier barrier = new Barrier(2))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Task.WaitAll(
Task.Run(() =>
{
rwls.EnterWriteLock();
barrier.SignalAndWait();
Assert.True(rwls.IsWriteLockHeld);
barrier.SignalAndWait();
rwls.ExitWriteLock();
}),
Task.Run(() =>
{
barrier.SignalAndWait();
Assert.False(rwls.TryEnterReadLock(0));
Assert.False(rwls.IsReadLockHeld);
barrier.SignalAndWait();
}));
}
}
[Fact]
public static void WritersAreMutuallyExclusiveFromWriters()
{
using (Barrier barrier = new Barrier(2))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Task.WaitAll(
Task.Run(() =>
{
rwls.EnterWriteLock();
barrier.SignalAndWait();
Assert.True(rwls.IsWriteLockHeld);
barrier.SignalAndWait();
rwls.ExitWriteLock();
}),
Task.Run(() =>
{
barrier.SignalAndWait();
Assert.False(rwls.TryEnterWriteLock(0));
Assert.False(rwls.IsReadLockHeld);
barrier.SignalAndWait();
}));
}
}
[Fact]
public static void ReadersMayBeConcurrent()
{
using (Barrier barrier = new Barrier(2))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
Assert.Equal(0, rwls.CurrentReadCount);
Task.WaitAll(
Task.Run(() =>
{
rwls.EnterReadLock();
barrier.SignalAndWait(); // 1
Assert.True(rwls.IsReadLockHeld);
barrier.SignalAndWait(); // 2
Assert.Equal(2, rwls.CurrentReadCount);
barrier.SignalAndWait(); // 3
barrier.SignalAndWait(); // 4
rwls.ExitReadLock();
}),
Task.Run(() =>
{
barrier.SignalAndWait(); // 1
rwls.EnterReadLock();
barrier.SignalAndWait(); // 2
Assert.True(rwls.IsReadLockHeld);
Assert.Equal(0, rwls.WaitingReadCount);
barrier.SignalAndWait(); // 3
rwls.ExitReadLock();
barrier.SignalAndWait(); // 4
}));
Assert.Equal(0, rwls.CurrentReadCount);
}
}
[Fact]
public static void WriterToWriterChain()
{
using (AutoResetEvent are = new AutoResetEvent(false))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
rwls.EnterWriteLock();
Task t = Task.Factory.StartNew(() =>
{
Assert.False(rwls.TryEnterWriteLock(10));
Task.Run(() => are.Set()); // ideally this won't fire until we've called EnterWriteLock, but it's a benign race in that the test will succeed either way
rwls.EnterWriteLock();
rwls.ExitWriteLock();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
are.WaitOne();
rwls.ExitWriteLock();
t.GetAwaiter().GetResult();
}
}
[Fact]
public static void WriterToReaderChain()
{
using (AutoResetEvent are = new AutoResetEvent(false))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
rwls.EnterWriteLock();
Task t = Task.Factory.StartNew(() =>
{
Assert.False(rwls.TryEnterReadLock(TimeSpan.FromMilliseconds(10)));
Task.Run(() => are.Set()); // ideally this won't fire until we've called EnterReadLock, but it's a benign race in that the test will succeed either way
rwls.EnterReadLock();
rwls.ExitReadLock();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
are.WaitOne();
rwls.ExitWriteLock();
t.GetAwaiter().GetResult();
}
}
[Fact]
public static void WriterToUpgradeableReaderChain()
{
using (AutoResetEvent are = new AutoResetEvent(false))
using (ReaderWriterLockSlim rwls = new ReaderWriterLockSlim())
{
rwls.EnterWriteLock();
Task t = Task.Factory.StartNew(() =>
{
Assert.False(rwls.TryEnterUpgradeableReadLock(TimeSpan.FromMilliseconds(10)));
Task.Run(() => are.Set()); // ideally this won't fire until we've called EnterReadLock, but it's a benign race in that the test will succeed either way
rwls.EnterUpgradeableReadLock();
rwls.ExitUpgradeableReadLock();
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
are.WaitOne();
rwls.ExitWriteLock();
t.GetAwaiter().GetResult();
}
}
[Fact]
[OuterLoop]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot, "dotnet/corefx #3364, #5839 and #21585")] // Hangs in desktop and in UapAot
public static void ReleaseReadersWhenWaitingWriterTimesOut()
{
using (var rwls = new ReaderWriterLockSlim())
{
// Enter the read lock
rwls.EnterReadLock();
// Typical order of execution: 0
Thread writeWaiterThread;
using (var beforeTryEnterWriteLock = new ManualResetEvent(false))
{
writeWaiterThread =
new Thread(() =>
{
// Typical order of execution: 1
// Add a writer to the wait list for enough time to allow successive readers to enter the wait list while this
// writer is waiting
beforeTryEnterWriteLock.Set();
if (rwls.TryEnterWriteLock(1000))
{
// The typical order of execution is not guaranteed, as sleep times are not guaranteed. For
// instance, before this write lock is added to the wait list, the two new read locks may be
// acquired. In that case, the test may complete before or while the write lock is taken.
rwls.ExitWriteLock();
}
// Typical order of execution: 4
});
writeWaiterThread.IsBackground = true;
writeWaiterThread.Start();
beforeTryEnterWriteLock.WaitOne();
}
Thread.Sleep(500); // wait for TryEnterWriteLock to enter the wait list
// A writer should now be waiting, add readers to the wait list. Since a read lock is still acquired, the writer
// should time out waiting, then these readers should enter and exit the lock.
ThreadStart EnterAndExitReadLock = () =>
{
// Typical order of execution: 2, 3
rwls.EnterReadLock();
// Typical order of execution: 5, 6
rwls.ExitReadLock();
};
var readerThreads =
new Thread[]
{
new Thread(EnterAndExitReadLock),
new Thread(EnterAndExitReadLock)
};
foreach (var readerThread in readerThreads)
{
readerThread.IsBackground = true;
readerThread.Start();
}
foreach (var readerThread in readerThreads)
{
readerThread.Join();
}
rwls.ExitReadLock();
// Typical order of execution: 7
writeWaiterThread.Join();
}
}
[Fact]
[OuterLoop]
public static void DontReleaseWaitingReadersWhenThereAreWaitingWriters()
{
using(var rwls = new ReaderWriterLockSlim())
{
rwls.EnterUpgradeableReadLock();
rwls.EnterWriteLock();
// Typical order of execution: 0
// Add a waiting writer
var threads = new Thread[2];
using(var beforeEnterWriteLock = new ManualResetEvent(false))
{
var thread =
new Thread(() =>
{
beforeEnterWriteLock.Set();
rwls.EnterWriteLock();
// Typical order of execution: 3
rwls.ExitWriteLock();
});
thread.IsBackground = true;
thread.Start();
threads[0] = thread;
beforeEnterWriteLock.WaitOne();
}
// Add a waiting reader
using(var beforeEnterReadLock = new ManualResetEvent(false))
{
var thread =
new Thread(() =>
{
beforeEnterReadLock.Set();
rwls.EnterReadLock();
// Typical order of execution: 4
rwls.ExitReadLock();
});
thread.IsBackground = true;
thread.Start();
threads[1] = thread;
beforeEnterReadLock.WaitOne();
}
// Wait for the background threads to block waiting for their locks
Thread.Sleep(1000);
// Typical order of execution: 1
rwls.ExitWriteLock();
// At this point there is still one reader and one waiting writer, so the reader-writer lock should not try to
// release any of the threads waiting for a lock
// Typical order of execution: 2
rwls.ExitUpgradeableReadLock();
// At this point, the waiting writer should be released, and the waiting reader should not
foreach(var thread in threads)
thread.Join();
// Typical order of execution: 5
}
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Collections;
using OpenSource.UPnP.AV;
using System.Diagnostics;
using System.Runtime.Serialization;
using OpenSource.UPnP.AV.CdsMetadata;
namespace OpenSource.UPnP.AV.MediaServer.DV
{
/// <summary>
/// Defines additional methods and properties for a <see cref="DvMediaResource"/>.
/// </summary>
public interface IDvResource : IMediaResource
{
/// <summary>
/// Provides the relative path as reported by resource when listed in the CDS.
/// The string value is a properly escaped UTF8 encoded URI.
/// </summary>
string RelativeContentUri { get; }
/// <summary>
/// Provides the resource ID, which uniquely identifies a resource in a device-implementation
/// of a CDS. This field is not normative to UPnP-AV, and is used specifically for
/// this implementation of CDS on device-side implementations.
/// </summary>
string ResourceID { get; }
/// <summary>
/// Set this to true if the importUri attribute should be displayed in Browse/Search responses.
/// Determines generally if the resource allows control points to post/import/replace a resource with a new binary.
/// </summary>
bool AllowImport { get; set; }
/// <summary>
/// Method takes the current ContentUri value and checks
/// to see if the uri is an automapped file using the <see cref="MediaResource.AUTOMAPFILE"/> convention
/// and also that the automapped file exists. If both are true
/// then the result is true.
/// </summary>
/// <returns></returns>
bool CheckLocalFileExists();
}
/// <summary>
/// <para>
/// This class is a
/// <see cref="OpenSource.UPnP.AV.CdsMetadata.MediaResource"/>
/// implementation intended for use with the
/// <see cref="MediaServerDevice"/>
/// class. DvMediaResource objects can be added to
/// <see cref="DvMediaContainer"/>
/// and
/// <see cref="DvMediaItem"/>
/// objects.
/// </para>
///
/// <para>
/// This class inherits all of the metadata properties for a resource,
/// but adds methods to modify the values associated with the metadata.
/// </para>
///
/// <para>
/// A public programmer can instantiate a DvMediaResource object
/// by using the
/// <see cref="ResourceBuilder"/>.CreateDvXXX
/// methods, or can instantiate one using a
/// constructor and setting values manually.
/// </para>
/// </summary>
[Serializable()]
public class DvMediaResource : MediaResource, IDvResource
{
/// <summary>
/// This delegate is used when a DvMediaResource needs to know if
/// an automapped file still exists.
/// </summary>
public delegate bool Delegate_AutomapFileExists(DvMediaResource res);
/// <summary>
/// This delegate field is executed when a DvMediaResource needs to know
/// if an automapped file still exists. This method is only called when
/// the contentUri does not translate into a local file (after removing the AUTOMAPFILE
/// string and a trailing query string).
///
/// <para>
/// For example the framework cannot tell if
/// AUTOMAPFILE + "nonExistentLocalFile.jpg?res=x,y" exists, so it asks the application layer
/// to provide the answer. It may actually be that the application layer determined
/// that nonExistentLocalFile.jpg actually does exist.
/// </para>
///
/// <para>
/// On the other hand, if the path was AUTOMAPFILE+"c:\temp.mp3" or AUTOMAPFILE+"c:\temp.mp3?transcode=wav"
/// and temp.mp3 actually existed, then either path representation will automatically be
/// detected by the framework as being a file that exists.
/// </para>
/// </summary>
public Delegate_AutomapFileExists CheckAutomapFileExists;
/// <summary>
/// Returns the relative URI path for a resource that uses the
/// <see cref="MediaResource.AUTOMAPFILE"/> convention.
/// Added primarily as a hook so that <see cref="TagExtractor"/>
/// can properly extract the ContentUri value for an automapped
/// resource so that <see cref="MediaSorter"/> can compare
/// the values as they are actually seen from the perspective
/// of a control point.
/// </summary>
public string RelativeContentUri
{
get
{
return EnsureNonAutoMapProtocol("");
}
}
/// <summary>
/// Returns a listing of attributes that have been set.
/// Override is used to check the value of the
/// <see cref="DvMediaResource.HasImportUri"/>
/// override to determine if the importUri attribute is valid.
/// </summary>
public override IList ValidAttributes
{
get
{
IList attribs = base.ValidAttributes;
if (this.HasImportUri)
{
if (attribs.Contains(T[_RESATTRIB.importUri]) == false)
{
attribs.Add(T[_RESATTRIB.importUri]);
}
}
return attribs;
}
}
/// <summary>
/// Adds extra protection on base class implementation
/// to prevent AUTOMAPPED FILES from having the importUri attribute
/// set.
/// </summary>
/// <param name="newMetadata"></param>
public override void UpdateResource (IMediaResource newMetadata)
{
if (this.m_ContentUri.StartsWith(MediaResource.AUTOMAPFILE))
{
if (newMetadata[T[_RESATTRIB.importUri]] != null)
{
throw new ApplicationException("Cannot set the importUri attribute for a resource that is automapped.");
}
}
base.UpdateResource(newMetadata);
}
/// <summary>
/// Tells the owning object that something has changed.
/// </summary>
/// <exception cref="InvalidCastException">
/// thrown if the owner is not a <see cref="IDvMedia"/> object.
/// </exception>
private void NotifyOwnerOfChange()
{
if (this.Owner != null)
{
IDvMedia owner = (IDvMedia) this.Owner;
owner.NotifyRootOfChange();
}
}
/// <summary>
/// Override set: Notifies the owner of change after calling
/// base class implementation.
/// </summary>
public override object this[_RESATTRIB attrib]
{
set
{
base[attrib] = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Override set: Notifies the owner of change after calling
/// base class implementation.
/// </summary>
public override object this[string attrib]
{
set
{
base[attrib] = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// <para>
/// This property does nothing different from the inherited version, but
/// some additional semantics are added in a DvMediaResource.
/// </para>
///
/// <para>
/// The set() method is exactly the same as using the SetContentUri() method.
/// </para>
///
/// <para>
/// <see cref="MediaServerDevice"/>
/// has an implementation detail designed to optimize the webserving
/// of ContentDirectory resources mapped local binaries. If public
/// programmers instantiate a DvMediaResource such that the
/// ContentUri returns a string in the format of
/// "<see cref="OpenSource.UPnP.AV.CdsMetadata.MediaResource.AUTOMAPFILE"/>+[full local path]"
/// then
/// <see cref="MediaServerDevice"/>
/// will automatically translate the URI into an appropriate
/// http URL and serve the file when requests are made for the specified URL.
/// </para>
/// </summary>
public override string ContentUri
{
set
{
this.SetContentUri(value);
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Method takes the current ContentUri value and checks
/// to see if the uri is an automapped file and also
/// that the automapped file exists. If both are true
/// then the result is true.
/// <para>
/// This method could potentially be a performance bottleneck
/// when translating automapped files into relative Uris.
/// I've opted to use this solution because the alternative
/// would be that MediaServerDevice be modified to track
/// all
/// </para>
/// </summary>
/// <returns></returns>
public bool CheckLocalFileExists()
{
string full = this.ContentUri;
bool fileExists = false;
if (full.StartsWith(MediaResource.AUTOMAPFILE))
{
string filename = full.Substring(MediaResource.AUTOMAPFILE.Length);
if (Directory.Exists(filename))
{
fileExists = true;
}
else if (File.Exists(filename))
{
fileExists = true;
}
else if (this.MakeStreamAtHttpGetTime)
{
int queryPos = full.IndexOf("?");
if (queryPos > 0)
{
filename = filename.Remove(queryPos, filename.Length-queryPos);
if (Directory.Exists(filename) == false)
{
fileExists = true;
}
else if (File.Exists(filename))
{
fileExists = true;
}
}
if (fileExists == false)
{
if (this.CheckAutomapFileExists != null)
{
fileExists = this.CheckAutomapFileExists(this);
}
}
}
}
this.m_LocalFileExists = fileExists;
return this.m_LocalFileExists;
}
/// <summary>
/// This property indicates if the contentUri value of
/// the resource maps to a binary stream generated at
/// run-time when handling an HTTP-GET request, contrasted
/// with a binary that's stored on the local file.
/// </summary>
public bool MakeStreamAtHttpGetTime
{
get
{
return this.m_bools[(int) Bits.MakeStreamAtHttpGetTime];
}
set
{
this.m_bools[(int) Bits.MakeStreamAtHttpGetTime] = value;
this.CheckLocalFileExists();
}
}
/// <summary>
/// Since URI's are dynamically mapped for resources that
/// have a mapping through <see cref="MediaResource.AUTOMAPFILE"/>,
/// importUri really has no meaning for the programmer.
/// For resources not mapped in such a way, the base implementation is called.
/// </summary>
/// <summary>
/// The property returns one of the following.
/// <list type="bullet">
/// <item>
/// <term>relative URL path (dynamically generated by system)</term>
/// <description>
/// Resources that map to local files that are served through http-get are given
/// a relative path to the file, from the
/// <see cref="MediaServerDevice"/>'s
/// relative web path for content.
/// </description>
/// </item>
/// <item>
/// <term>URI path (specified explicitly)</term>
/// <description>Resources that were explicitly set with a URI are</description>
/// </item>
/// </list>
/// </summary>
/// <exception cref="Error_CannotSetImportUri">
/// Thrown when attempting to set the URI of a resource that maps to
/// a local file intended for serving with http-get from the internal
/// webserver of a
/// <see cref="MediaServerDevice"/>
/// object.
/// </exception>
public override string ImportUri
{
get
{
if (this.AllowImport)
{
if (
(this.m_ContentUri.StartsWith(AUTOMAPFILE)) ||
(this.m_ContentUri == "")
)
{
StringBuilder path = new StringBuilder(20);
path.AppendFormat ("/{0}/{1}/", this.m_ResourceID, this.m_Owner.ID);
return path.ToString();
}
else
{
return base.ImportUri;
}
}
else
{
return "";
}
}
set
{
if (this.m_ContentUri.StartsWith(AUTOMAPFILE))
{
throw new ApplicationException("Cannot set the importUri for a resource that is mapped through MediaResource.AUTOMAPFILE.");
}
base.ImportUri = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Override set: Notifies the owner of change after calling
/// base class implementation.
/// </summary>
public override ProtocolInfoString ProtocolInfo
{
set
{
base.ProtocolInfo = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Override set: Notifies the owner of change after calling
/// base class implementation.
/// </summary>
public override _UInt Bitrate
{
set
{
base.Bitrate = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Override set: Notifies the owner of change after calling
/// base class implementation.
/// </summary>
public override _UInt BitsPerSample
{
set
{
base.BitsPerSample = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Override set: Notifies the owner of change after calling
/// base class implementation.
/// </summary>
public override _UInt ColorDepth
{
set
{
base.ColorDepth = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Override set: Notifies the owner of change after calling
/// base class implementation.
/// </summary>
public override _TimeSpan Duration
{
set
{
base.Duration = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Override set: Notifies the owner of change after calling
/// base class implementation.
/// </summary>
public override _UInt nrAudioChannels
{
set
{
base.nrAudioChannels = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Override set: Notifies the owner of change after calling
/// base class implementation.
/// </summary>
public override string Protection
{
set
{
base.Protection = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Override set: Notifies the owner of change after calling
/// base class implementation.
/// </summary>
public override ImageDimensions Resolution
{
set
{
base.Resolution = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Override set: Notifies the owner of change after calling
/// base class implementation.
/// </summary>
public override _UInt SampleFrequency
{
set
{
base.SampleFrequency = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Override set: Notifies the owner of change after calling
/// base class implementation.
/// </summary>
public override _ULong Size
{
set
{
base.Size = value;
this.NotifyOwnerOfChange();
}
}
/// <summary>
/// Override set: Checks protection access through this.Owner.CheckProtection()
/// and then calls base class implementation.
/// </summary>
public override IUPnPMedia Owner
{
set
{
#if (DEBUG)
if (this.Owner != null)
{
this.Owner.CheckRuntimeBindings(new StackTrace());
}
#endif
base.m_Owner = value;
}
}
/// <summary>
/// Returns the same value as AllowImport.
/// </summary>
public override bool HasImportUri
{
get
{
return this.AllowImport;
}
}
/// <summary>
/// Set this to true if the ImportUri field should be displayed.
/// Determines generally if the resource allows control points
/// to post/import/replace a resource with a new binary.
/// </summary>
public bool AllowImport { get { return this._AllowImport; } set { this._AllowImport = value; } }
/// <summary>
/// Stores value of <see cref="DvMediaResource.AllowImport"/>.
/// </summary>
private bool _AllowImport = false;
/// <summary>
/// Set this to true if the ContentUri should not be reported in browse/search
/// requests. This is necessary when creating items from a control point and the
/// related local file does not yet exist.
/// </summary>
public bool HideContentUri = false;
/// <summary>
/// Allows a public programmer to set the URI of an object.
/// </summary>
/// <param name="newUri"></param>
/// <exception cref="Error_CannotSetContentUri">
/// Thrown when the newUri string begins with
/// <see cref="OpenSource.UPnP.AV.CdsMetadata.MediaResource.AUTOMAPFILE"/>
/// and the
/// protocol is not "http-get".
/// </exception>
public void SetContentUri(string newUri)
{
if (newUri.StartsWith(AUTOMAPFILE))
{
if (string.Compare (this.ProtocolInfo.Protocol, "http-get") != 0)
{
if (string.Compare (this.ProtocolInfo.Protocol, "*") == 0)
{
this.ProtocolInfo = new ProtocolInfoString("http-get:" + this.ProtocolInfo.Network + ":" + this.ProtocolInfo.MimeType + ":" + this.ProtocolInfo.Info);
}
else
{
throw new Error_CannotSetContentUri(this.ProtocolInfo, newUri);
}
}
}
this.m_ContentUri = newUri;
this.CheckLocalFileExists();
}
/// <summary>
/// Allows a programmet to set the "protocolInfo" string.
/// </summary>
/// <param name="protocolInfo">
/// A valid protocolInfo string must have the format
/// "[protocol]:[network]:[mime type]:[info]".
/// </param>
/// <exception cref="Error_CannotSetProtocolInfo">
/// Thrown if the protocolInfo string is not "http-get", when the contentUri
/// starts with
/// <see cref="OpenSource.UPnP.AV.CdsMetadata.MediaResource.AUTOMAPFILE"/>.
/// </exception>
public void SetProtocolInfo(ProtocolInfoString protocolInfo)
{
if (this.ContentUri.StartsWith(AUTOMAPFILE))
{
if (string.Compare (protocolInfo.Protocol, "http-get") != 0)
{
throw new Error_CannotSetProtocolInfo(this.ContentUri, protocolInfo);
}
}
this.m_ProtocolInfo = protocolInfo;
}
/// <summary>
/// Instantiates a DvMediaResource.
/// </summary>
/// <param name="contentUri">
/// The URI of a resource, or a string with the format
/// "<see cref="OpenSource.UPnP.AV.CdsMetadata.MediaResource.AUTOMAPFILE"/>+[full local path]"
/// and is intended to be served through the http-get
/// protocol).
/// </param>
/// <param name="protocolInfo">
/// A valid protocolInfo string must have the format
/// "[protocol]:[network]:[mime type]:[info]".
/// </param>
/// <param name="allowImport">
/// True, if the resource allows control points to replace the resource.
/// If false, then "importUri" attribute is not exposed in ContentDirectory's Browse/Search
/// responses.
/// </param>
/// <exception cref="Error_CannotSetProtocolInfo">
/// Thrown if the contentUri value maps to a local file,
/// but the protocolInfo string indicates a protocol other than "http-get".
/// </exception>
public DvMediaResource(string contentUri, string protocolInfo, bool allowImport)
: base(contentUri, protocolInfo)
{
InitBools();
this.m_ResourceID = GetResourceID();
this.AllowImport = allowImport;
// Set the protocolInfo string again, this time throwing
// exception if there's an http-get conflict with a locally mapped content uri.
this.SetProtocolInfo(new ProtocolInfoString(protocolInfo));
}
internal DvMediaResource ()
{
InitBools();
this.m_ResourceID = GetResourceID();
}
/// <summary>
/// DvMediaResources can be instantiated from an XmlElement that matches
/// the ContentDirectory's schema for resource metadata. This method
/// is for internal use only because of instability from improper use
/// of the method. If enough demand ensues for its relase as a public
/// method, I can oblige.
/// </summary>
/// <param name="xml">
/// An XML element conforming to the syntax and semantics of a ContentDirectory resource.
/// </param>
public DvMediaResource (XmlElement xml)
: base(xml)
{
InitBools();
this.AllowImport = false;
if (this.ContentUri != null)
{
if (this.ContentUri == "")
{
this.AllowImport = true;
}
}
this.m_ResourceID = GetResourceID();
}
/// <summary>
/// Instructs the "xmlWriter" argument to start the "res" element.
/// Override properly allows mapping of local paths to relative URIs
/// using the <see cref="MediaResource.AUTOMAPFILE"/> convention.
/// </summary>
/// <param name="formatter">
/// A <see cref="ToXmlFormatter"/> object that
/// specifies method implementations for printing
/// media objects and metadata.
/// </param>
/// <param name="data">
/// This object should be a <see cref="ToXmlData"/>
/// object that contains additional instructions used
/// by the "formatter" argument.
/// </param>
/// <param name="xmlWriter">
/// The <see cref="XmlTextWriter"/> object that
/// will format the representation in an XML
/// valid way.
/// </param>
/// <exception cref="InvalidCastException">
/// Thrown if the "data" argument is not a <see cref="ToXmlData"/> object.
/// </exception>
/// <exception cref="ApplicationException">
/// Thrown if the resource's importUri attribute has been explicitly set for
/// a resource that uses the <see cref="MediaResource.AUTOMAPFILE"/> convention.
/// </exception>
public override void StartElement(ToXmlFormatter formatter, object data, XmlTextWriter xmlWriter)
{
ToXmlData _d = (ToXmlData) data;
this.StartResourceXml(_d.DesiredProperties, xmlWriter);
this.WriteAttributesXml(data, _d.DesiredProperties, xmlWriter);
this.WriteImportUriXml(_d.BaseUri, _d.DesiredProperties, xmlWriter);
}
/// <summary>
/// Overrides the base class method so that the importUri field can be dynamically generated
/// based on a local file path.
/// </summary>
/// <param name="baseUriInfo">a string that has the base URL in form: http:[ip address: port]/[virtualdir]</param>
/// <param name="desiredProperties"></param>
/// <param name="xmlWriter"></param>
private void WriteImportUriXml(string baseUriInfo, ArrayList desiredProperties, XmlTextWriter xmlWriter)
{
if (desiredProperties != null)
{
if (this.HasImportUri)
{
string key = T[_ATTRIB.importUri];
if (this.m_ContentUri.StartsWith(MediaResource.AUTOMAPFILE))
{
if (base[key] != null)
{
throw new ApplicationException("The ImportUri attribute has been explicitly set for a resource that is automapped, which is illegal.");
}
}
if (desiredProperties.Contains(Tags.PropertyAttributes.res_importUri) || desiredProperties.Count == 0)
{
string importUri = baseUriInfo;
importUri += this.ImportUri;
xmlWriter.WriteAttributeString(key, importUri);
}
}
}
}
/// <summary>
/// Overrides the base class method so that the contentUri can be dynamically generated
/// based on a local file path.
/// </summary>
/// <param name="baseUriInfo">a string that has the base URL in form: http:[ip address: port]/[virtualdir]</param>
/// <param name="xmlWriter"></param>
protected override void WriteContentUriXml(string baseUriInfo, XmlTextWriter xmlWriter)
{
xmlWriter.WriteString(this.EnsureNonAutoMapProtocol(baseUriInfo));
}
/// <summary>
/// This method returns a resource URI in string form, such that the
/// URI is not a URI using the
/// <see cref="MediaResource.AUTOMAPFILE"/>
/// protocol.
/// </summary>
/// <param name="baseUri">the base http URL. If null, then the original local path is printed. If empty string, then only the relative portion of URI is printed.</param>
/// <returns>A URI not using the
/// <see cref="MediaResource.AUTOMAPFILE"/>
/// protocol.
/// </returns>
internal string EnsureNonAutoMapProtocol(string baseUri)
{
IUPnPMedia item = this.m_Owner;
if (this.ContentUri.StartsWith(AUTOMAPFILE))
{
if (baseUri == null)
{
return this.ContentUri;
}
if (this.m_LocalFileExists)
{
StringBuilder uri = new StringBuilder(this.ContentUri.Length);
int dotpos = this.ContentUri.LastIndexOf('.');
string ext = "";
if (this.OverrideFileExtenstion == null)
{
if ((dotpos > 0) && (dotpos < this.ContentUri.Length - 1))
{
ext = this.ContentUri.Substring(dotpos);
}
int querypos = ext.IndexOf('?');
if ((querypos > 0) && (querypos < ext.Length - 1))
{
ext = ext.Substring(0, querypos);
}
}
else
{
if (this.OverrideFileExtenstion.StartsWith("."))
{
ext = this.OverrideFileExtenstion;
}
else
{
ext = "." + this.OverrideFileExtenstion;
}
}
uri.Append(baseUri);
uri.AppendFormat("/{0}/{1}/{2} - {3}{4}", this.m_ResourceID, item.ID, item.Creator, item.Title, ext);
string uriString = HTTPMessage.EscapeString(uri.ToString());
return uriString;
}
else
{
return "";
}
}
else
{
return this.ContentUri;
}
}
/// <summary>
/// Public programmers can use this method to acquire a unique name for
/// a binary associated with a resource created by a control-point.
/// The method attempts to provide a name using the resource owner's
/// creator, title, and a few additional numbers. Applications
/// are not required to use this method to generate a name.
/// </summary>
/// <param name="baseDirectory">the base directory with where the </param>
/// <returns></returns>
public string GenerateLocalFilePath(string baseDirectory)
{
StringBuilder filePath = new StringBuilder(256);
string base_name = "";
try
{
base_name = this.Owner.Creator.Trim() +" -- "+ this.Owner.Title.Trim();
base_name = base_name.Replace("/", "_");
base_name = base_name.Replace("\\", "_");
base_name = base_name.Replace(":", "-");
base_name = base_name.Replace("*", "_");
base_name = base_name.Replace("?", "_");
base_name = base_name.Replace(">", "_");
base_name = base_name.Replace("<", "_");
base_name = base_name.Replace("|", "_");
}
catch
{
}
filePath.AppendFormat("{0}{1}{2} -- {3}", AUTOMAPFILE, baseDirectory, base_name, this.ResourceID);
if ((this.ProtocolInfo.MimeType != "*") && (this.ProtocolInfo.MimeType != ""))
{
filePath.AppendFormat("{0}", MimeTypes.MimeToExtension(this.ProtocolInfo.MimeType));
}
/// Ensure the file is unique.
///
if (File.Exists(filePath.ToString()))
{
int x = 1;
while (File.Exists(filePath.ToString() + x.ToString()))
{
x++;
}
filePath.AppendFormat("_{0}", x);
}
return filePath.ToString();
}
/// <summary>
/// <see cref="MediaServerDevice"/>
/// uses a ResourceID value to enforce uniqueness of resources served
/// through it's HTTP server. This method ensures that unique
/// ID's are given to each resource.
/// </summary>
/// <returns></returns>
private static string GetResourceID()
{
lock (TheNextID)
{
int n = (int)TheNextID;
n++;
TheNextID = n;
}
return TheNextID.ToString();
}
/// <summary>
/// Provides the resource ID, which uniquely identifies a resource in a device-implementation
/// of a CDS. This field is not normative to UPnP-AV, and is used specifically for
/// this implementation of CDS on device-side implementations.
/// <para>
/// To ensure that resources are unique, we use
/// a ResourceID value. Public programmers
/// should not depend on this value, as it is
/// a system value.
/// </para>
/// </summary>
public string ResourceID { get { return this.m_ResourceID; } }
/// <summary>
/// The resourceID... available for internal use only.
/// Either has the format of "[long]" or "[long]_[long]".
/// </summary>
internal string m_ResourceID;
/// <summary>
/// If true, then an automapped file has been
/// determined to have been an existing file
/// (at least at one point).
/// </summary>
private bool m_LocalFileExists
{
get
{
return this.m_bools[(int) Bits.LocalFileExists];
}
set
{
this.m_bools[(int) Bits.LocalFileExists] = value;
}
}
/// <summary>
/// Enumeration indexer into m_bools.
/// </summary>
private enum Bits
{
LocalFileExists = 0,
MakeStreamAtHttpGetTime
}
/// <summary>
/// Initializes values in m_bools.
/// </summary>
/// <returns></returns>
protected virtual void InitBools()
{
this.m_bools[(int) Bits.LocalFileExists] = false;
this.m_bools[(int) Bits.MakeStreamAtHttpGetTime] = false;
}
/// <summary>
/// Use a bit array instead of individual booleans to save space.
/// The BitArray seems to have some weird bugs. Switching
/// back to bools.
/// </summary>
//private BitArray m_bools = new BitArray(2);
private bool[] m_bools = new bool[2];
private static object TheNextID = 0;
/// <summary>
/// Set this field if the contentUri contains an AUTOMAPFILE location,
/// and the file extension associated with the file isn't the one
/// you want to advertise. This is used primarily for resources that
/// are transcoded.
///
/// <para>
/// Developers are encouraged to use this, as it has positive performance benefits.
/// If left equal to null, the library's translation from a an automapped file path
/// to a relative uri will involve parsing out the first file extension before a
/// query (?) symbol.
/// </para>
/// </summary>
public string OverrideFileExtenstion = null;
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.Globalization;
using mshtml;
using OpenLiveWriter.Api;
using OpenLiveWriter.Extensibility.ImageEditing;
using OpenLiveWriter.Mshtml;
namespace OpenLiveWriter.PostEditor
{
// Though center is a value, img tags do not support align=center
public enum ImgAlignment { NONE, LEFT, RIGHT, BOTTOM, TOP, BASELINE, TEXTTOP, MIDDLE, ABSMIDDLE, CENTER };
public class HtmlAlignDecoratorSettings
{
private static readonly string DEFAULT_ALIGNMENT = "DefaultAlignment";
private IHTMLElement _element;
IProperties Settings;
private ImageDecoratorInvocationSource _invocationSource = ImageDecoratorInvocationSource.Unknown;
public HtmlAlignDecoratorSettings(IHTMLElement element)
{
_element = element;
Settings = null;
}
public HtmlAlignDecoratorSettings(IProperties settings, IHTMLElement element)
{
_element = element;
Settings = settings;
}
public HtmlAlignDecoratorSettings(IProperties settings, IHTMLElement element, ImageDecoratorInvocationSource invocationSource)
{
_element = element;
Settings = settings;
_invocationSource = invocationSource;
}
public ImgAlignment DefaultAlignment
{
get
{
string align = Settings.GetString(DEFAULT_ALIGNMENT, ImgAlignment.NONE.ToString());
try
{
return (ImgAlignment)ImgAlignment.Parse(typeof(ImgAlignment), align);
}
catch (Exception)
{
return ImgAlignment.NONE;
}
}
set
{
Settings.SetString(DEFAULT_ALIGNMENT, value.ToString());
}
}
public ImgAlignment Alignment
{
get
{
return GetAlignmentFromHtml();
}
set
{
SetImageHtmlFromAlignment(value);
}
}
// Set the alignment of the image
internal void SetImageHtmlFromAlignment(ImgAlignment value)
{
bool needToSelectImage = false;
switch (value)
{
case ImgAlignment.NONE:
// If we removed the centering node, we need to reselect the image since the selection
// is invalidated/changed as a result of removing the node.
needToSelectImage = RemoveCenteringNode();
_element.removeAttribute("align", 0);
_element.style.display = "inline";
_element.style.styleFloat = null;
if (_element.style.marginLeft != null && _element.style.marginLeft.ToString() == "auto")
_element.style.marginLeft = 0;
if (_element.style.marginRight != null && _element.style.marginRight.ToString() == "auto")
_element.style.marginRight = 0;
break;
case ImgAlignment.LEFT:
case ImgAlignment.RIGHT:
// If we removed the centering node, we need to reselect the image since the selection
// is invalidated/changed as a result of removing the node.
needToSelectImage = RemoveCenteringNode();
_element.style.display = "inline";
_element.style.styleFloat = value.ToString().ToLower(CultureInfo.InvariantCulture);
if (_element.style.marginLeft != null && _element.style.marginLeft.ToString() == "auto")
_element.style.marginLeft = 0;
if (_element.style.marginRight != null && _element.style.marginRight.ToString() == "auto")
_element.style.marginRight = 0;
// For all other types of alignment we just set the align property on the image
_element.setAttribute("align", value.ToString().ToLower(CultureInfo.InvariantCulture), 0);
break;
case ImgAlignment.CENTER:
_element.removeAttribute("align", 0);
_element.style.styleFloat = null;
if (GlobalEditorOptions.SupportsFeature(ContentEditorFeature.CenterImageWithParagraph))
{
IHTMLElement element = FindCenteringNode();
if (element == null)
{
// There is no existing centering node, we need to create a new one.
// Creating the new centering node invalidates/changes the existing selection
// so we need to reselect the image.
needToSelectImage = true;
element = CreateNodeForCentering();
}
if (element != null)
{
element.setAttribute("align", "center", 0);
}
}
else
{
_element.style.display = "block";
_element.style.styleFloat = "none";
_element.style.marginLeft = "auto";
_element.style.marginRight = "auto";
}
break;
default:
Trace.Fail("Unknown image alignment: " + value.ToString());
break;
}
if (needToSelectImage)
{
// If we need to reselect the image, do it after we have set the right
// alignment in the element above so that when the selection change event
// refreshes the ribbon commands using the html doc, it sees the new values.
SelectImage();
}
}
private void SelectImage()
{
// We don't want a selection changed event to fire during the initial insert.
if (_invocationSource == ImageDecoratorInvocationSource.InitialInsert)
return;
IHTMLTextContainer textContainer = ((IHTMLDocument2)_element.document).body as IHTMLTextContainer;
IHTMLControlRange controlRange = textContainer.createControlRange() as IHTMLControlRange;
controlRange.add(_element as IHTMLControlElement);
controlRange.select();
}
// Detects the alignment of an element, which could be an image or smart content div
internal ImgAlignment GetAlignmentFromHtml()
{
// Try and see if this is an img, if it is we will be able to read
// the align attribute right off of it.
IHTMLImgElement image = (_element as IHTMLImgElement);
if (image != null)
{
// Check and see if the align attribute has been set
string align = image.align;
if (align != null)
{
align = align.ToLower(CultureInfo.InvariantCulture).Trim();
// If it has been, then just check to see what type
// of alignment has already been set.
switch (align)
{
case "left":
return ImgAlignment.LEFT;
case "right":
return ImgAlignment.RIGHT;
case "top":
return ImgAlignment.TOP;
case "bottom":
return ImgAlignment.BOTTOM;
case "middle":
return ImgAlignment.MIDDLE;
case "absmiddle":
return ImgAlignment.ABSMIDDLE;
case "baseline":
return ImgAlignment.BASELINE;
case "texttop":
return ImgAlignment.TEXTTOP;
}
}
}
// Check to see if the element has a float right on it
if (_element.style.styleFloat == "right")
{
return ImgAlignment.RIGHT;
}
// Check to see if the element has a float left
if (_element.style.styleFloat == "left")
{
return ImgAlignment.LEFT;
}
if ((_element.style.styleFloat == "none" || String.IsNullOrEmpty(_element.style.styleFloat)) && _element.style.display == "block" && _element.style.marginLeft as string == "auto" && _element.style.marginRight as string == "auto")
{
return ImgAlignment.CENTER;
}
IHTMLElement centeringNode = FindCenteringNode();
if (centeringNode != null)
{
if (IsCenteringNode(centeringNode))
return ImgAlignment.CENTER;
}
// We didnt find anything, so no alignment could be found.
return ImgAlignment.NONE;
}
private int CountVisibleElements(IHTMLElement node)
{
if (node == null)
return 0;
int count = 0;
IHTMLElementCollection all = (IHTMLElementCollection)node.all;
foreach (IHTMLElement child in all)
{
if (ElementFilters.IsVisibleEmptyElement(child))
{
count++;
}
}
return count;
}
internal IHTMLElement FindCenteringNode()
{
// Create markup services using the element's document that we are analyzing
MshtmlMarkupServices MarkupServices = new MshtmlMarkupServices(_element.document as IMarkupServicesRaw);
// Create a pointer and move it to before the begining of its opening tag
MarkupPointer start = MarkupServices.CreateMarkupPointer();
start.MoveAdjacentToElement(_element, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
// Find the block parent of this node.
IHTMLElement blockParent = start.CurrentBlockScope();
// Check to see if the block parent is actually a centering node.
if (IsBodyElement((IHTMLElement3)blockParent) || !IsCenteringNode(blockParent))
{
blockParent = null;
}
// Make sure that if we do have a block parents, we are the only thing inside it.
// Since we are going to edit the block, we dont want other stuff in there that
// will also be changed
if (blockParent != null)
{
string innerHtml = ((IHTMLElement)blockParent).innerText ?? "";
if (!string.IsNullOrEmpty(innerHtml.Trim()))
{
blockParent = null;
}
else
{
int numElements = CountVisibleElements((IHTMLElement)blockParent);
if (numElements != 1)
{
blockParent = null;
}
}
}
return blockParent;
}
private bool IsCenteringNode(IHTMLElement element)
{
return GlobalEditorOptions.SupportsFeature(ContentEditorFeature.CenterImageWithParagraph) && element != null &&
element is IHTMLParaElement && element.getAttribute("align", 2) as string == "center";
}
private bool IsBodyElement(IHTMLElement3 element)
{
return element != null && element.contentEditable == "true" &&
(((IHTMLElement)element).className == "postBody" || element is IHTMLBodyElement);
}
private IHTMLElement CreateNodeForCentering()
{
// Create markup services using the element's document that we are analyzing
MshtmlMarkupServices MarkupServices = new MshtmlMarkupServices(_element.document as IMarkupServicesRaw);
MarkupPointer end = MarkupServices.CreateMarkupPointer();
MarkupPointer start = MarkupServices.CreateMarkupPointer();
// Find the element that we will want to wrap.
IHTMLElement elementToEncapsulate = _element;
// If the elements parent is an A, we will also want to
// wrap the A and not just the image inside
if (_element.parentElement.tagName == "A")
{
elementToEncapsulate = _element.parentElement;
}
// Move the starting pointer to before the begining of the element we want to wrap
start.MoveAdjacentToElement(elementToEncapsulate, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
// Find this elements parent
IHTMLElement3 currentBlockScope = start.CurrentBlockScope() as IHTMLElement3;
// If its parent is also the div that is around the post
// we need to actually create a new div and just put it around the element
// If it is splittable block, split it
// e.g "<DIV>Blah<IMG/>Blah</DIV>" => "<DIV>Blah</DIV><DIV><IMG/></DIV><DIV>Blah</DIV>"
if (!IsBodyElement(currentBlockScope))
{
// We are in a block that can be split so split it at the begining and end
MarkupHelpers.SplitBlockForInsertionOrBreakout(MarkupServices, null, start);
end.MoveAdjacentToElement(elementToEncapsulate, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
MarkupHelpers.SplitBlockForInsertionOrBreakout(MarkupServices, null, end);
// Position start back to the beginning of our element
start.MoveAdjacentToElement(elementToEncapsulate, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
}
// Now we can wrap it in an P tag (centering node)
end.MoveAdjacentToElement(elementToEncapsulate, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
IHTMLElement centeringElement = MarkupServices.CreateElement(_ELEMENT_TAG_ID.TAGID_P, string.Empty);
MarkupServices.InsertElement(centeringElement, start, end);
return centeringElement;
}
internal bool RemoveCenteringNode()
{
MshtmlMarkupServices MarkupServices = new MshtmlMarkupServices(_element.document as IMarkupServicesRaw);
IHTMLElement element = FindCenteringNode();
// We couldnt find a parent, so nothing to remove
if (element == null) return false;
MarkupPointer start = MarkupServices.CreateMarkupPointer();
MarkupPointer end = MarkupServices.CreateMarkupPointer();
MarkupPointer target = MarkupServices.CreateMarkupPointer();
// Move the stuff inside the smart content container ouside of itself
start.MoveAdjacentToElement(element, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterBegin);
end.MoveAdjacentToElement(element, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeEnd);
target.MoveAdjacentToElement(element, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
MarkupServices.Move(start, end, target);
// remove the empty smart content container
start.MoveAdjacentToElement(element, _ELEMENT_ADJACENCY.ELEM_ADJ_BeforeBegin);
end.MoveAdjacentToElement(element, _ELEMENT_ADJACENCY.ELEM_ADJ_AfterEnd);
MarkupServices.Remove(start, end);
return true;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Reflection;
namespace System.Management.Classes
{
[Guid("a3d024ed-a234-4b76-b909-f17a75f28327")]
internal class Meta_Class : IUnixWbemClassHandler
{
private Dictionary<string, object> _prop = new Dictionary<string, object>();
private readonly Dictionary<string, UnixWbemPropertyInfo> _propInfos;
private readonly Dictionary<string, UnixWbemPropertyInfo> _systemPropInfos;
private readonly Dictionary<string, UnixWbemQualiferInfo> _qualifiers;
private Dictionary<string, UnixCimMethodInfo> _methods;
private IEnumerator<UnixCimMethodInfo> _methodEnumerator;
public Meta_Class ()
{
_propInfos = new Dictionary<string, UnixWbemPropertyInfo>();
_systemPropInfos = new Dictionary<string, UnixWbemPropertyInfo>();
_qualifiers = new Dictionary<string, UnixWbemQualiferInfo>();
_methods = new Dictionary<string, UnixCimMethodInfo>();
RegisterProperies();
}
public virtual IUnixWbemClassHandler New()
{
return (IUnixWbemClassHandler)Activator.CreateInstance (this.GetType ());
}
protected virtual void RegisterProperies()
{
RegisterSystemProperty ("__GENUS", CimType.SInt32, 0);
RegisterSystemProperty ("__UID", CimType.Object, 0);
RegisterSystemProperty ("__SERVER", CimType.String, 0);
RegisterSystemProperty ("__NAMESPACE", CimType.String, 0);
RegisterSystemProperty ("__CLASS", CimType.String, 0);
RegisterSystemProperty ("__IMPLEMENTATION_TYPE", CimType.String, 0);
RegisterSystemProperty ("__DERIVATION", CimType.String, 0);
RegisterSystemProperty ("__RELATIVE_PATH", CimType.String, 0);
RegisterSystemProperty ("__PATH", CimType.String, 0);
RegisterSystemProperty ("__KEY_FIELD", CimType.String, 0);
}
protected virtual void RegisterProperty(string name, CimType type, int flavor)
{
if (_propInfos.ContainsKey (name))
_propInfos[name] = new UnixWbemPropertyInfo { Name = name, Type = type, Flavor = flavor};
else
_propInfos.Add (name, new UnixWbemPropertyInfo { Name = name, Type = type, Flavor = flavor});
}
protected virtual void RegisterSystemProperty(string name, CimType type, int flavor)
{
if (_propInfos.ContainsKey (name))
_systemPropInfos[name] = new UnixWbemPropertyInfo { Name = name, Type = type, Flavor = flavor};
else
_systemPropInfos.Add (name, new UnixWbemPropertyInfo { Name = name, Type = type, Flavor = flavor});
}
#region IUnixWbemClassHandler implementation
public System.Collections.Generic.IEnumerable<object> Get (string strQuery)
{
var queryable = (IQueryable<UnixMetaClass>)new QueryParser<UnixMetaClass>().Parse (WMIDatabaseFactory.GetMetaClasses ("root/cimv2").AsQueryable (), strQuery);
return queryable.Select (x => New().Get(x));
}
public IUnixWbemClassHandler WithProperty(string key, object obj)
{
AddProperty (key, obj);
return this;
}
public IUnixWbemClassHandler WithMethod (string key, UnixCimMethodInfo methodInfo)
{
AddMethod (key, methodInfo);
return this;
}
public object Get (object nativeObj)
{
var obj = nativeObj as UnixMetaClass;
Type targetType = Type.GetType (obj.ImplementationType, false, true);
if (targetType != null)
{
IUnixWbemClassHandler targetHandler = WMIDatabaseFactory.GetHandler (targetType);
foreach (var p in targetHandler.PropertyInfos)
{
RegisterProperty (p.Name, p.Type, p.Flavor);
_prop.Add (p.Name, null);
}
foreach(var qualifierName in targetHandler.QualifierNames)
{
_qualifiers.Add (qualifierName, targetHandler.GetQualifier (qualifierName));
}
foreach(var method in targetHandler.Methods)
{
AddMethod (method.Name, method);
}
_prop.Add ("__KEY_FIELD", targetHandler.PathField);
}
if (obj != null)
{
_prop.Add ("__GENUS", 1);
_prop.Add ("__SERVER", System.Net.Dns.GetHostName ().ToLower ());
_prop.Add ("__NAMESPACE", obj.Namespace);
_prop.Add ("__UID", obj.Id);
_prop.Add ("__CLASS", obj.ClassName);
_prop.Add ("__IMPLEMENTATION_TYPE", obj.ImplementationType);
_prop.Add ("__DERIVATION", GetDerivations (targetType));
_prop.Add ("__PATH", string.Format ("//{0}/{1}/{2}/{3}={4}", _prop ["__SERVER"], _prop ["__NAMESPACE"], "META_CLASS", PathField, FormatPropertyValue(_prop [PathField])));
_prop.Add ("__RELATIVE_PATH", string.Format ("{0}/{1}={2}", "META_CLASS", PathField, FormatPropertyValue(_prop [PathField])));
}
return this;
}
private static string FormatPropertyValue(object obj)
{
if (obj is String)
{
if (obj == null)
{
return "\"\"";
}
return "\"" + obj.ToString () + "\"";
}
if (obj == null) return "";
return obj.ToString ();
}
private string[] GetDerivations(Type targetType)
{
Type type = targetType;
var list = new List<string>();
do
{
list.Add (type.BaseType.Name);
type = type.BaseType;
}
while(type.BaseType != null && type.BaseType != typeof(object));
return list.ToArray ();
}
/// <summary>
/// Adds the property.
/// </summary>
/// <param name='key'>
/// Key.
/// </param>
/// <param name='obj'>
/// Object.
/// </param>
public virtual void AddProperty (string key, object obj)
{
if (_prop.ContainsKey (key)) {
_prop [key] = obj;
} else {
_prop.Add (key, obj);
}
}
public void AddMethod (string key, UnixCimMethodInfo method)
{
if (_methods.ContainsKey (key)) {
_methods [key] = method;
} else {
_methods.Add (key, method);
}
}
/// <summary>
/// Gets the property.
/// </summary>
/// <returns>
/// The property.
/// </returns>
/// <param name='key'>
/// Key.
/// </param>
public virtual object GetProperty (string key)
{
var realKey = _prop.Keys.FirstOrDefault (x => x.Equals (key, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty (realKey))
{
return _prop[realKey];
}
return null;
}
/// <summary>
/// Invokes the method.
/// </summary>
/// <returns>
/// The method.
/// </returns>
/// <param name='obj'>
/// Object.
/// </param>
public virtual IUnixWbemClassHandler InvokeMethod (string methodName, IUnixWbemClassHandler obj)
{
return null;
}
public virtual IDictionary<string, object> Properties { get { return _prop; } }
public string PathField {
get { return "__CLASS"; }
}
public UnixWbemQualiferInfo GetQualifier (string name)
{
return _qualifiers[name];
}
public UnixWbemQualiferInfo GetQualifier (int index)
{
return _qualifiers.ElementAt (index).Value;
}
public IEnumerable<UnixWbemQualiferInfo> GetQualifiers ()
{
return _qualifiers.Values;
}
public virtual IEnumerable<string> QualifierNames { get { return _qualifiers.Keys; } }
public virtual IEnumerable<string> PropertyNames { get { return _propInfos.Keys; } }
public virtual IEnumerable<UnixWbemPropertyInfo> PropertyInfos { get { return _propInfos.Values; } }
public virtual IEnumerable<UnixWbemPropertyInfo> SystemPropertyInfos { get { return _systemPropInfos.Values; } }
public virtual IEnumerable<string> SystemPropertyNames { get { return _systemPropInfos.Keys; } }
public IEnumerable<string> MethodNames { get { return _methods.Keys; } }
public IEnumerable<UnixCimMethodInfo> Methods { get { return _methods.Values; } }
public UnixCimMethodInfo NextMethod ()
{
if (_methodEnumerator == null)
_methodEnumerator = Methods.GetEnumerator ();
if (_methodEnumerator.MoveNext ()) {
return _methodEnumerator.Current;
} else {
_methodEnumerator = null;
}
return default(UnixCimMethodInfo);
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 11/17/2008 8:57:29 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.ComponentModel;
using System.Drawing;
using GeoAPI.Geometries;
namespace DotSpatial.Symbology
{
[TypeConverter(typeof (ExpandableObjectConverter))]
public interface ILabelSymbolizer : ICloneable
{
#region Properties
/// <summary>
/// Gets or sets the the multi-line text alignment in the box.
/// </summary>
[Category("General"), Description("Gets or sets the horizontal relationship of the text to the anchorpoint.")]
StringAlignment Alignment { get; set; }
/// <summary>
/// Gets or set the angle that the font should be drawn in
/// </summary>
[Category("General"), Description("Gets or sets the angle that the font should be drawn in.")]
double Angle { get; set; }
/// <summary>
/// Gets or sets the background color
/// </summary>
[Category("General"), Description("Gets or sets the background color of a rectangle around the label.")]
Color BackColor { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether or not a background color should be used
/// </summary>
[Category("General"),
Description("Gets or sets a boolean indicating whether or not a background color should be used.")]
bool BackColorEnabled { get; set; }
/// <summary>
/// Gets or sets the border color
/// </summary>
[Category("Border"), Description("Gets or sets the border color")]
Color BorderColor { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether or not a border should be drawn around the label.
/// </summary>
[Category("Border"),
Description("Gets or sets a boolean indicating whether or not a border should be drawn around the label.")]
bool BorderVisible { get; set; }
/// <summary>
/// Gets or sets the color of the actual shadow. Use the alpha channel to specify opacity.
/// </summary>
[Category("Shadow"),
Description("Gets or sets the color of the actual shadow. Use the alpha channel to specify opacity.")]
Color DropShadowColor { get; set; }
/// <summary>
/// Gets or sets a boolean that will force a shadow to be drawn if this is true.
/// </summary>
[Category("Shadow"), Description("Gets or sets a boolean that will force a shadow to be drawn if this is true.")
]
bool DropShadowEnabled { get; set; }
/// <summary>
/// Gets or sets an X and Y geographic offset that is only used if ScaleMode is set to Geographic
/// </summary>
[Category("Shadow"),
Description("Gets or sets an X and Y geographic offset that is only used if ScaleMode is set to Geographic.")]
Coordinate DropShadowGeographicOffset { get; set; }
/// <summary>
/// Gets or sets an X and Y pixel offset that is used if the ScaleMode is set to Symbolic or Simple.
/// </summary>
[Category("Shadow"),
Description("Gets or sets an X and Y pixel offset that is used if the ScaleMode is set to Symbolic or Simple.")
]
PointF DropShadowPixelOffset { get; set; }
/// <summary>
/// Gets or sets format string used to draw float fields. E.g.:
/// #.##, 0.000. If empty - then format not used.
/// </summary>
string FloatingFormat { get; set; }
/// <summary>
/// Gets or set the color that the font should be drawn in.
/// </summary>
[Category("General"), Description("Gets or sets the color that the font should be drawn in.")]
Color FontColor { get; set; }
/// <summary>
/// Gets or sets the string font family name
/// </summary>
string FontFamily { get; set; }
/// <summary>
/// gets or sets the font size
/// </summary>
float FontSize { get; set; }
/// <summary>
/// Gets or sets the font style.
/// </summary>
FontStyle FontStyle { get; set; }
/// <summary>
/// Gets or sets the color of the halo that surrounds the text.
/// </summary>
[Category("Halo"), Description("Gets or sets the color of the halo that surrounds the text.")]
Color HaloColor { get; set; }
/// <summary>
/// Gets or sets a boolean that governs whether or not to draw a halo.
/// </summary>
[Category("Halo"), Description("Gets or sets a boolean that governs whether or not to draw a halo.")]
bool HaloEnabled { get; set; }
/// <summary>
/// Gets or set the field with angle to draw label
/// </summary>
[Category("General"), Description("Gets or set the field with angle to draw label.")]
string LabelAngleField { get; set; }
/// <summary>
/// Gets or sets the labeling method
/// </summary>
[Category("General"), Description("Gets or sets the labeling method.")]
LabelPlacementMethod LabelPlacementMethod { get; set; }
/// <summary>
/// Gets or sets the labeling method
/// </summary>
[Category("General"), Description("Gets or sets the labeling method for line labels.")]
LineLabelPlacementMethod LineLabelPlacementMethod { get; set; }
/// <summary>
/// Gets or sets the orientation of line labels.
/// </summary>
[Category("General"), Description("Gets or sets the orientation of line labels.")]
LineOrientation LineOrientation { get; set; }
/// <summary>
/// Gets or sets the X offset in pixels from the center of each feature.
/// </summary>
[Category("General"), Description("Gets or sets the X offset in pixels from the center of each feature.")]
float OffsetX { get; set; }
/// <summary>
/// Gets or sets the Y offset in pixels from the center of each feature.
/// </summary>
[Category("General"), Description("Gets or sets the Y offset in pixels from the center of each feature.")]
float OffsetY { get; set; }
/// <summary>
/// Gets or sets the position of the label relative to the placement point
/// </summary>
[Category("General"), Description("Gets or sets the position of the label relative to the placement point.")]
ContentAlignment Orientation { get; set; }
/// <summary>
/// Gets or sets the way features with multiple parts are labeled
/// </summary>
[Category("General"), Description("Gets or sets the way features with multiple parts are labeled.")]
PartLabelingMethod PartsLabelingMethod { get; set; }
/// <summary>
/// Gets or sets a boolean. If true, as high priority labels are placed, they
/// take up space and will not allow low priority labels that conflict for the
/// space to be placed.
/// </summary>
bool PreventCollisions { get; set; }
/// <summary>
/// Gets or sets a boolean. Normally high values from the field are given
/// a higher priority. If this is true, low values are given priority instead.
/// </summary>
bool PrioritizeLowValues { get; set; }
/// <summary>
/// Gets or sets the string field name for the field that controls which labels
/// get placed first. If collision detection is on, a higher priority means
/// will get placed first. If it is off, higher priority will be labeled
/// on top of lower priority.
/// </summary>
string PriorityField { get; set; }
/// <summary>
/// Gets or sets the scaling behavior for the text
/// </summary>
[Category("General"), Description(" Gets or sets the scaling behavior for the text.")]
ScaleMode ScaleMode { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether or not <see cref="Angle"/> should be used
/// </summary>
[Category("General"), Description("Gets or sets a boolean indicating whether or not Angle should be used.")]
bool UseAngle { get; set; }
/// <summary>
/// Gets or set a boolean indicating whether or not <see cref="LabelAngleField"/> should be used
/// </summary>
[Category("General"),
Description("Gets or set a boolean indicating whether or not LabelAngleField should be used.")]
bool UseLabelAngleField { get; set; }
/// <summary>
/// Gets or sets a boolean indicating whether or not the LineOrientation gets used.
/// </summary>
[Category("General"),
Description("Gets or sets a boolean indicating whether or not LineOrientation should be used.")]
bool UseLineOrientation { get; set; }
#endregion
#region Methods
/// <summary>
/// Uses the properties defined on this symbolizer to return a font.
/// </summary>
/// <returns>A new font</returns>
Font GetFont();
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ExpressRouteServiceProvidersOperations operations.
/// </summary>
internal partial class ExpressRouteServiceProvidersOperations : IServiceOperations<NetworkManagementClient>, IExpressRouteServiceProvidersOperations
{
/// <summary>
/// Initializes a new instance of the ExpressRouteServiceProvidersOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ExpressRouteServiceProvidersOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// The List ExpressRouteServiceProvider operation retrieves all the available
/// ExpressRouteServiceProviders.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteServiceProvider>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.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("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteServiceProviders").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteServiceProvider>>();
_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 = SafeJsonConvert.DeserializeObject<Page<ExpressRouteServiceProvider>>(_responseContent, this.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>
/// The List ExpressRouteServiceProvider operation retrieves all the available
/// ExpressRouteServiceProviders.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<ExpressRouteServiceProvider>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<ExpressRouteServiceProvider>>();
_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 = SafeJsonConvert.DeserializeObject<Page<ExpressRouteServiceProvider>>(_responseContent, this.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;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.Formula.Atp
{
using System;
using NPOI.SS.Formula.Eval;
/// <summary>
/// Internal calculation methods for Excel 'Analysis ToolPak' function YEARFRAC()
/// Algorithm inspired by www.dwheeler.com/yearfrac
/// @author Josh Micich
/// </summary>
/// <remarks>
/// Date Count convention
/// http://en.wikipedia.org/wiki/Day_count_convention
/// </remarks>
/// <remarks>
/// Office Online Help on YEARFRAC
/// http://office.microsoft.com/en-us/excel/HP052093441033.aspx
/// </remarks>
public class YearFracCalculator
{
/** use UTC time-zone to avoid daylight savings issues */
//private static readonly TimeZone UTC_TIME_ZONE = TimeZone.GetTimeZone("UTC");
private const int MS_PER_HOUR = 60 * 60 * 1000;
private const int MS_PER_DAY = 24 * MS_PER_HOUR;
private const int DAYS_PER_NORMAL_YEAR = 365;
private const int DAYS_PER_LEAP_YEAR = DAYS_PER_NORMAL_YEAR + 1;
/** the length of normal long months i.e. 31 */
private const int LONG_MONTH_LEN = 31;
/** the length of normal short months i.e. 30 */
private const int SHORT_MONTH_LEN = 30;
private const int SHORT_FEB_LEN = 28;
private const int LONG_FEB_LEN = SHORT_FEB_LEN + 1;
/// <summary>
/// Calculates YEARFRAC()
/// </summary>
/// <param name="pStartDateVal">The start date.</param>
/// <param name="pEndDateVal">The end date.</param>
/// <param name="basis">The basis value.</param>
/// <returns></returns>
public static double Calculate(double pStartDateVal, double pEndDateVal, int basis)
{
if (basis < 0 || basis >= 5)
{
// if basis is invalid the result is #NUM!
throw new EvaluationException(ErrorEval.NUM_ERROR);
}
// common logic for all bases
// truncate day values
int startDateVal = (int)Math.Floor(pStartDateVal);
int endDateVal = (int)Math.Floor(pEndDateVal);
if (startDateVal == endDateVal)
{
// when dates are equal, result is zero
return 0;
}
// swap start and end if out of order
if (startDateVal > endDateVal)
{
int temp = startDateVal;
startDateVal = endDateVal;
endDateVal = temp;
}
switch (basis)
{
case 0: return Basis0(startDateVal, endDateVal);
case 1: return Basis1(startDateVal, endDateVal);
case 2: return Basis2(startDateVal, endDateVal);
case 3: return Basis3(startDateVal, endDateVal);
case 4: return Basis4(startDateVal, endDateVal);
}
throw new InvalidOperationException("cannot happen");
}
/// <summary>
/// Basis 0, 30/360 date convention
/// </summary>
/// <param name="startDateVal">The start date value assumed to be less than or equal to endDateVal.</param>
/// <param name="endDateVal">The end date value assumed to be greater than or equal to startDateVal.</param>
/// <returns></returns>
public static double Basis0(int startDateVal, int endDateVal)
{
SimpleDate startDate = CreateDate(startDateVal);
SimpleDate endDate = CreateDate(endDateVal);
int date1day = startDate.day;
int date2day = endDate.day;
// basis zero has funny adjustments to the day-of-month fields when at end-of-month
if (date1day == LONG_MONTH_LEN && date2day == LONG_MONTH_LEN)
{
date1day = SHORT_MONTH_LEN;
date2day = SHORT_MONTH_LEN;
}
else if (date1day == LONG_MONTH_LEN)
{
date1day = SHORT_MONTH_LEN;
}
else if (date1day == SHORT_MONTH_LEN && date2day == LONG_MONTH_LEN)
{
date2day = SHORT_MONTH_LEN;
// Note: If date2day==31, it STAYS 31 if date1day < 30.
// Special fixes for February:
}
else if (startDate.month == 2 && IsLastDayOfMonth(startDate))
{
// Note - these assignments deliberately set Feb 30 date.
date1day = SHORT_MONTH_LEN;
if (endDate.month == 2 && IsLastDayOfMonth(endDate))
{
// only adjusted when first date is last day in Feb
date2day = SHORT_MONTH_LEN;
}
}
return CalculateAdjusted(startDate, endDate, date1day, date2day);
}
/// <summary>
/// Basis 1, Actual/Actual date convention
/// </summary>
/// <param name="startDateVal">The start date value assumed to be less than or equal to endDateVal.</param>
/// <param name="endDateVal">The end date value assumed to be greater than or equal to startDateVal.</param>
/// <returns></returns>
public static double Basis1(int startDateVal, int endDateVal)
{
SimpleDate startDate = CreateDate(startDateVal);
SimpleDate endDate = CreateDate(endDateVal);
double yearLength;
if (IsGreaterThanOneYear(startDate, endDate))
{
yearLength = AverageYearLength(startDate.year, endDate.year);
}
else if (ShouldCountFeb29(startDate, endDate))
{
yearLength = DAYS_PER_LEAP_YEAR;
}
else
{
yearLength = DAYS_PER_NORMAL_YEAR;
}
return DateDiff(startDate.ticks, endDate.ticks) / yearLength;
}
/// <summary>
/// Basis 2, Actual/360 date convention
/// </summary>
/// <param name="startDateVal">The start date value assumed to be less than or equal to endDateVal.</param>
/// <param name="endDateVal">The end date value assumed to be greater than or equal to startDateVal.</param>
/// <returns></returns>
public static double Basis2(int startDateVal, int endDateVal)
{
return (endDateVal - startDateVal) / 360.0;
}
/// <summary>
/// Basis 3, Actual/365 date convention
/// </summary>
/// <param name="startDateVal">The start date value assumed to be less than or equal to endDateVal.</param>
/// <param name="endDateVal">The end date value assumed to be greater than or equal to startDateVal.</param>
/// <returns></returns>
public static double Basis3(double startDateVal, double endDateVal)
{
return (endDateVal - startDateVal) / 365.0;
}
/// <summary>
/// Basis 4, European 30/360 date convention
/// </summary>
/// <param name="startDateVal">The start date value assumed to be less than or equal to endDateVal.</param>
/// <param name="endDateVal">The end date value assumed to be greater than or equal to startDateVal.</param>
/// <returns></returns>
public static double Basis4(int startDateVal, int endDateVal)
{
SimpleDate startDate = CreateDate(startDateVal);
SimpleDate endDate = CreateDate(endDateVal);
int date1day = startDate.day;
int date2day = endDate.day;
// basis four has funny adjustments to the day-of-month fields when at end-of-month
if (date1day == LONG_MONTH_LEN)
{
date1day = SHORT_MONTH_LEN;
}
if (date2day == LONG_MONTH_LEN)
{
date2day = SHORT_MONTH_LEN;
}
// Note - no adjustments for end of Feb
return CalculateAdjusted(startDate, endDate, date1day, date2day);
}
/// <summary>
/// Calculates the adjusted.
/// </summary>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
/// <param name="date1day">The date1day.</param>
/// <param name="date2day">The date2day.</param>
/// <returns></returns>
private static double CalculateAdjusted(SimpleDate startDate, SimpleDate endDate, int date1day,
int date2day)
{
double dayCount
= (endDate.year - startDate.year) * 360
+ (endDate.month - startDate.month) * SHORT_MONTH_LEN
+ (date2day - date1day) * 1;
return dayCount / 360;
}
/// <summary>
/// Determines whether [is last day of month] [the specified date].
/// </summary>
/// <param name="date">The date.</param>
/// <returns>
/// <c>true</c> if [is last day of month] [the specified date]; otherwise, <c>false</c>.
/// </returns>
private static bool IsLastDayOfMonth(SimpleDate date)
{
if (date.day < SHORT_FEB_LEN)
{
return false;
}
return date.day == GetLastDayOfMonth(date);
}
/// <summary>
/// Gets the last day of month.
/// </summary>
/// <param name="date">The date.</param>
/// <returns></returns>
private static int GetLastDayOfMonth(SimpleDate date)
{
switch (date.month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return LONG_MONTH_LEN;
case 4:
case 6:
case 9:
case 11:
return SHORT_MONTH_LEN;
}
if (IsLeapYear(date.year))
{
return LONG_FEB_LEN;
}
return SHORT_FEB_LEN;
}
/// <summary>
/// Assumes dates are no more than 1 year apart.
/// </summary>
/// <param name="start">The start.</param>
/// <param name="end">The end.</param>
/// <returns><c>true</c>
/// if dates both within a leap year, or span a period including Feb 29</returns>
private static bool ShouldCountFeb29(SimpleDate start, SimpleDate end)
{
bool startIsLeapYear = IsLeapYear(start.year);
if (startIsLeapYear && start.year == end.year)
{
// note - dates may not actually span Feb-29, but it gets counted anyway in this case
return true;
}
bool endIsLeapYear = IsLeapYear(end.year);
if (!startIsLeapYear && !endIsLeapYear)
{
return false;
}
if (startIsLeapYear)
{
switch (start.month)
{
case SimpleDate.JANUARY:
case SimpleDate.FEBRUARY:
return true;
}
return false;
}
if (endIsLeapYear)
{
switch (end.month)
{
case SimpleDate.JANUARY:
return false;
case SimpleDate.FEBRUARY:
break;
default:
return true;
}
return end.day == LONG_FEB_LEN;
}
return false;
}
/// <summary>
/// return the whole number of days between the two time-stamps. Both time-stamps are
/// assumed to represent 12:00 midnight on the respective day.
/// </summary>
/// <param name="startDateTicks">The start date ticks.</param>
/// <param name="endDateTicks">The end date ticks.</param>
/// <returns></returns>
private static double DateDiff(long startDateTicks, long endDateTicks)
{
return new TimeSpan(endDateTicks - startDateTicks).TotalDays;
}
/// <summary>
/// Averages the length of the year.
/// </summary>
/// <param name="startYear">The start year.</param>
/// <param name="endYear">The end year.</param>
/// <returns></returns>
private static double AverageYearLength(int startYear, int endYear)
{
int dayCount = 0;
for (int i = startYear; i <= endYear; i++)
{
dayCount += DAYS_PER_NORMAL_YEAR;
if (IsLeapYear(i))
{
dayCount++;
}
}
double numberOfYears = endYear - startYear + 1;
return dayCount / numberOfYears;
}
/// <summary>
/// determine Leap Year
/// </summary>
/// <param name="i">the year</param>
/// <returns></returns>
private static bool IsLeapYear(int i)
{
// leap years are always divisible by 4
if (i % 4 != 0)
{
return false;
}
// each 4th century is a leap year
if (i % 400 == 0)
{
return true;
}
// all other centuries are *not* leap years
if (i % 100 == 0)
{
return false;
}
return true;
}
/// <summary>
/// Determines whether [is greater than one year] [the specified start].
/// </summary>
/// <param name="start">The start date.</param>
/// <param name="end">The end date.</param>
/// <returns>
/// <c>true</c> if [is greater than one year] [the specified start]; otherwise, <c>false</c>.
/// </returns>
private static bool IsGreaterThanOneYear(SimpleDate start, SimpleDate end)
{
if (start.year == end.year)
{
return false;
}
if (start.year + 1 != end.year)
{
return true;
}
if (start.month > end.month)
{
return false;
}
if (start.month < end.month)
{
return true;
}
return start.day < end.day;
}
/// <summary>
/// Creates the date.
/// </summary>
/// <param name="dayCount">The day count.</param>
/// <returns></returns>
private static SimpleDate CreateDate(int dayCount)
{
var dt= NPOI.SS.UserModel.DateUtil.SetCalendar(dayCount, 0, false, false);
return new SimpleDate(dt);
}
/// <summary>
/// Simple Date Wrapper
/// </summary>
private class SimpleDate
{
public const int JANUARY = 1;
public const int FEBRUARY = 2;
public int year;
/** 1-based month */
public int month;
/** day of month */
public int day;
/** milliseconds since 1970 */
public long ticks;
public SimpleDate(DateTime date)
{
year = date.Year;
month = date.Month;
day = date.Day;
ticks = date.Ticks;
}
}
}
}
| |
namespace Gu.Wpf.UiAutomation
{
using System;
using System.Collections.Generic;
using System.Windows.Automation;
public static class ItemContainerPatternExt
{
public static AutomationElement? FirstOrDefault(this ItemContainerPattern pattern)
{
if (pattern is null)
{
throw new ArgumentNullException(nameof(pattern));
}
var item = pattern.FindItemByProperty(null, null, null);
if (item is { } &&
item.TryGetVirtualizedItemPattern(out var virtualizedItemPattern))
{
virtualizedItemPattern.Realize();
}
return item;
}
public static AutomationElement? LastOrDefault(this ItemContainerPattern pattern)
{
if (pattern is null)
{
throw new ArgumentNullException(nameof(pattern));
}
var item = pattern.FindItemByProperty(null, null, null);
if (item is null)
{
return null;
}
while (true)
{
var temp = pattern.FindItemByProperty(item, null, null);
if (temp is null)
{
if (item.TryGetVirtualizedItemPattern(out var virtualizedItemPattern))
{
virtualizedItemPattern.Realize();
}
return item;
}
item = temp;
}
}
public static IEnumerable<AutomationElement> AllItems(this ItemContainerPattern pattern)
{
if (pattern is null)
{
throw new ArgumentNullException(nameof(pattern));
}
AutomationElement? item = null;
while (true)
{
item = pattern.FindItemByProperty(item, null, null);
if (item is null)
{
break;
}
if (item.TryGetVirtualizedItemPattern(out var virtualizedItemPattern))
{
virtualizedItemPattern.Realize();
}
yield return item;
}
}
public static IEnumerable<T> AllItems<T>(this ItemContainerPattern pattern, Func<AutomationElement, T> wrap)
{
if (pattern is null)
{
throw new ArgumentNullException(nameof(pattern));
}
if (wrap is null)
{
throw new ArgumentNullException(nameof(wrap));
}
AutomationElement? item = null;
while (true)
{
item = pattern.FindItemByProperty(item, null, null);
if (item is null)
{
break;
}
if (item.TryGetVirtualizedItemPattern(out var virtualizedItemPattern))
{
virtualizedItemPattern.Realize();
}
yield return wrap(item);
}
}
public static AutomationElement FindAtIndex(this ItemContainerPattern pattern, int index)
{
if (pattern is null)
{
throw new ArgumentNullException(nameof(pattern));
}
var current = 0;
AutomationElement? item = null;
while (true)
{
item = pattern.FindItemByProperty(item, null, null);
if (item is null)
{
throw new ArgumentOutOfRangeException(nameof(index), index, "Could not get item at index.");
}
if (current == index)
{
if (item.TryGetVirtualizedItemPattern(out var virtualizedItemPattern))
{
virtualizedItemPattern.Realize();
}
return item;
}
current++;
}
}
public static T FindAtIndex<T>(this ItemContainerPattern pattern, int index, Func<AutomationElement, T> wrap)
{
if (pattern is null)
{
throw new ArgumentNullException(nameof(pattern));
}
if (wrap is null)
{
throw new ArgumentNullException(nameof(wrap));
}
return wrap(FindAtIndex(pattern, index));
}
public static AutomationElement FindByText(this ItemContainerPattern pattern, string text)
{
if (pattern is null)
{
throw new ArgumentNullException(nameof(pattern));
}
if (text is null)
{
throw new ArgumentNullException(nameof(text));
}
var item = pattern.FindItemByProperty(null, AutomationElement.NameProperty, text);
if (item is { })
{
return item;
}
var byNameCondition = new PropertyCondition(AutomationElement.NameProperty, text);
while (true)
{
item = pattern.FindItemByProperty(item, null, null);
if (item is null)
{
throw new InvalidOperationException($"Did not find an item by text {text}");
}
if (item.TryGetVirtualizedItemPattern(out var virtualizedItemPattern))
{
virtualizedItemPattern.Realize();
}
if (item.Name() == text)
{
return item;
}
if (item.IsContentElement() &&
item.TryFindFirst(TreeScope.Children, byNameCondition, out _))
{
return item;
}
}
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System.Data;
using FluentMigrator.Runner.Announcers;
using FluentMigrator.Runner.Generators.Postgres;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Runner.Processors.Postgres;
using FluentMigrator.Tests.Helpers;
using Npgsql;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Integration.Processors
{
[TestFixture]
public class PostgresProcessorTests
{
private readonly PostgresQuoter quoter = new PostgresQuoter();
public NpgsqlConnection Connection { get; set; }
public PostgresProcessor Processor { get; set; }
[SetUp]
public void SetUp()
{
Connection = new NpgsqlConnection(IntegrationTestOptions.Postgres.ConnectionString);
Processor = new PostgresProcessor(Connection, new PostgresGenerator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new PostgresDbFactory());
}
[TearDown]
public void TearDown()
{
Processor.CommitTransaction();
}
[Test]
public void CallingSchemaExistsReturnsTrueIfSchemaExists()
{
Processor.SchemaExists("public").ShouldBeTrue();
}
[Test]
public void CallingSchemaExistsCanAcceptSchemaNameWithSingleQuote()
{
using (new PostgresTestTable(Processor, "Test'Schema", "id int"))
Processor.SchemaExists("Test'Schema").ShouldBeTrue();
}
[Test]
public void CallingSchemaExistsReturnsFalseIfSchemaDoesNotExist()
{
Processor.SchemaExists("DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingTableExistsReturnsTrueIfTableExists()
{
using (var table = new PostgresTestTable(Processor, null, "id int"))
Processor.TableExists(null, table.Name).ShouldBeTrue();
}
[Test]
public void CallingTableExistsReturnsFalseIfTableDoesNotExist()
{
Processor.TableExists(null, "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingColumnExistsReturnsTrueIfColumnExists()
{
using (var table = new PostgresTestTable(Processor, null, "id int"))
Processor.ColumnExists(null, table.Name, "id").ShouldBeTrue();
}
[Test]
public void CallingColumnExistsReturnsFalseIfTableDoesNotExist()
{
Processor.ColumnExists(null, "DoesNotExist", "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingColumnExistsReturnsFalseIfColumnDoesNotExist()
{
using (var table = new PostgresTestTable(Processor, null, "id int"))
Processor.ColumnExists(null, table.Name, "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingContraintExistsReturnsTrueIfConstraintExists()
{
using (var table = new PostgresTestTable(Processor, null, "id int", "wibble int CONSTRAINT c1 CHECK(wibble > 0)"))
Processor.ConstraintExists(null, table.Name,"c1").ShouldBeTrue();
}
[Test]
public void CallingConstraintExistsReturnsFalseIfTableDoesNotExist()
{
Processor.ConstraintExists(null, "DoesNotExist", "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingConstraintExistsReturnsFalseIfConstraintDoesNotExist()
{
using (var table = new PostgresTestTable(Processor, null, "id int"))
Processor.ConstraintExists(null, table.Name, "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingIndexExistsReturnsTrueIfIndexExists()
{
using (var table = new PostgresTestTable(Processor, null, "id int"))
{
var idxName = string.Format("\"idx_{0}\"", quoter.UnQuote(table.Name));
var cmd = table.Connection.CreateCommand();
cmd.Transaction = table.Transaction;
cmd.CommandText = string.Format("CREATE INDEX {0} ON {1} (id)", idxName, table.Name);
cmd.ExecuteNonQuery();
Processor.IndexExists(null, table.Name, idxName).ShouldBeTrue();
}
}
[Test]
public void CallingIndexExistsReturnsFalseIfTableDoesNotExist()
{
Processor.IndexExists(null, "DoesNotExist", "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingIndexExistsReturnsFalseIfIndexDoesNotExist()
{
using (var table = new PostgresTestTable(Processor, null, "id int"))
Processor.IndexExists(null, table.Name, "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingIndexExistsCanAcceptIndexNameWithSingleQuote()
{
using (var table = new PostgresTestTable(Processor, null, "id int"))
{
var idxName = string.Format("\"id'x_{0}\"", quoter.UnQuote(table.Name));
var cmd = table.Connection.CreateCommand();
cmd.Transaction = table.Transaction;
cmd.CommandText = string.Format("CREATE INDEX {0} ON {1} (id)", idxName, table.Name);
cmd.ExecuteNonQuery();
Processor.IndexExists(null, table.Name, idxName).ShouldBeTrue();
}
}
[Test]
public void CallingIndexExistsCanAcceptTableNameWithSingleQuote()
{
using (var table = new PostgresTestTable(null, "TestSingle'Quote", Processor, "id int"))
{
var idxName = string.Format("\"idx_{0}\"", quoter.UnQuote(table.Name));
var cmd = table.Connection.CreateCommand();
cmd.Transaction = table.Transaction;
cmd.CommandText = string.Format("CREATE INDEX {0} ON {1} (id)", idxName, table.Name);
cmd.ExecuteNonQuery();
Processor.IndexExists(null, table.Name, idxName).ShouldBeTrue();
}
}
[Test]
public void CallingIndexExistsCanAcceptSchemaNameWithSingleQuote()
{
using (var table = new PostgresTestTable(Processor, "Test'Schema", "id int"))
{
var idxName = string.Format("\"idx_{0}\"", quoter.UnQuote(table.Name));
var cmd = table.Connection.CreateCommand();
cmd.Transaction = table.Transaction;
cmd.CommandText = string.Format("CREATE INDEX {0} ON {1} (id)", idxName, table.NameWithSchema);
cmd.ExecuteNonQuery();
Processor.IndexExists("Test'Schema", table.Name, idxName).ShouldBeTrue();
}
}
[Test]
public void CanReadData()
{
using (var table = new PostgresTestTable(Processor, null, "id int"))
{
AddTestData(table);
DataSet ds = Processor.Read("SELECT * FROM {0}", table.Name);
ds.ShouldNotBeNull();
ds.Tables.Count.ShouldBe(1);
ds.Tables[0].Rows.Count.ShouldBe(3);
ds.Tables[0].Rows[2][0].ShouldBe(2);
}
}
[Test]
public void CanReadTableData()
{
using (var table = new PostgresTestTable(Processor, null, "id int"))
{
AddTestData(table);
DataSet ds = Processor.ReadTableData(null, table.Name);
ds.ShouldNotBeNull();
ds.Tables.Count.ShouldBe(1);
ds.Tables[0].Rows.Count.ShouldBe(3);
ds.Tables[0].Rows[2][0].ShouldBe(2);
}
}
private void AddTestData(PostgresTestTable table)
{
for (int i = 0; i < 3; i++)
{
var cmd = table.Connection.CreateCommand();
cmd.Transaction = table.Transaction;
cmd.CommandText = string.Format("INSERT INTO {0} (id) VALUES ({1})", table.NameWithSchema, i);
cmd.ExecuteNonQuery();
}
}
[Test]
public void CallingTableExistsReturnsTrueIfTableExistsWithSchema()
{
using (var table = new PostgresTestTable(Processor, "TestSchema", "id int"))
Processor.TableExists("TestSchema", table.Name).ShouldBeTrue();
}
[Test]
public void CallingTableExistsReturnsFalseIfTableDoesNotExistWithSchema()
{
Processor.TableExists("TestSchema", "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingTableExistsReturnsFalseIfTableExistsInDifferentSchema()
{
using (var table = new PostgresTestTable(Processor, "TestSchema1", "id int"))
Processor.TableExists("TestSchema2", table.Name).ShouldBeFalse();
}
[Test]
public void CallingTableExistsCanAcceptTableNameWithSingleQuote()
{
using (var table = new PostgresTestTable(null, "TestSingle'Quote", Processor, "id int"))
Processor.TableExists(null, table.Name).ShouldBeTrue();
}
[Test]
public void CallingTableExistsCanAcceptSchemaNameWithSingleQuote()
{
using (var table = new PostgresTestTable(Processor, "Test'Schema", "id int"))
Processor.TableExists("Test'Schema", table.Name).ShouldBeTrue();
}
[Test]
public void CallingColumnExistsReturnsTrueIfColumnExistsWithSchema()
{
using (var table = new PostgresTestTable(Processor, "TestSchema", "id int"))
Processor.ColumnExists("TestSchema", table.Name, "id").ShouldBeTrue();
}
[Test]
public void CallingColumnExistsReturnsFalseIfColumnExistsInDifferentSchema()
{
using (var table = new PostgresTestTable(Processor, "TestSchema1", "id int"))
Processor.ColumnExists("TestSchema2", table.Name, "id").ShouldBeFalse();
}
[Test]
public void CallingColumnExistsReturnsFalseIfTableDoesNotExistWithSchema()
{
Processor.ColumnExists("TestSchema", "DoesNotExist", "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingColumnExistsReturnsFalseIfColumnDoesNotExistWithSchema()
{
using (var table = new PostgresTestTable(Processor, "TestSchema", "id int"))
Processor.ColumnExists("TestSchema", table.Name, "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingColumnExistsCanAcceptColumnNameWithSingleQuote()
{
var columnNameWithSingleQuote = quoter.Quote("i'd");
using (var table = new PostgresTestTable(Processor, null, string.Format("{0} int", columnNameWithSingleQuote)))
Processor.ColumnExists(null, table.Name, "i'd").ShouldBeTrue();
}
[Test]
public void CallingColumnExistsCanAcceptTableNameWithSingleQuote()
{
using (var table = new PostgresTestTable("TestSchema", "TestSingle'Quote", Processor, "id int"))
Processor.ColumnExists("TestSchema", table.Name, "id").ShouldBeTrue();
}
[Test]
public void CallingColumnExistsCanAcceptSchemaNameWithSingleQuote()
{
using (var table = new PostgresTestTable("Test'Schema", "TestSingle'Quote", Processor, "id int"))
Processor.ColumnExists("Test'Schema", table.Name, "id").ShouldBeTrue();
}
[Test]
public void CallingConstraintExistsCanAcceptConstraintNameWithSingleQuote()
{
using (var table = new PostgresTestTable(Processor, "TestSchema", "id int", @"wibble int CONSTRAINT ""c'1"" CHECK(wibble > 0)"))
Processor.ConstraintExists("TestSchema", table.Name, "c'1").ShouldBeTrue();
}
[Test]
public void CallingConstraintExistsCanAcceptTableNameWithSingleQuote()
{
using (var table = new PostgresTestTable("TestSchema", "TestSingle'Quote", Processor, "id int", "wibble int CONSTRAINT c1 CHECK(wibble > 0)"))
Processor.ConstraintExists("TestSchema", table.Name, "c1").ShouldBeTrue();
}
[Test]
public void CallingConstraintExistsCanAcceptSchemaNameWithSingleQuote()
{
using (var table = new PostgresTestTable(Processor, "Test'Schema", "id int", "wibble int CONSTRAINT c1 CHECK(wibble > 0)"))
Processor.ConstraintExists("Test'Schema", table.Name, "c1").ShouldBeTrue();
}
[Test]
public void CallingConstraintExistsReturnsTrueIfConstraintExistsWithSchema()
{
using (var table = new PostgresTestTable(Processor, "TestSchema", "id int", "wibble int CONSTRAINT c1 CHECK(wibble > 0)"))
Processor.ConstraintExists("TestSchema", table.Name, "c1").ShouldBeTrue();
}
[Test]
public void CallingConstraintExistsReturnsFalseIfTableDoesNotExistWithSchema()
{
Processor.ConstraintExists("TestSchema", "DoesNotExist", "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingContraintExistsReturnsFalseIfConstraintExistsInDifferentSchema()
{
using (var table = new PostgresTestTable(Processor, "TestSchema1", "id int", "wibble int CONSTRAINT c1 CHECK(wibble > 0)"))
Processor.ConstraintExists("TestSchema2", table.Name, "c1").ShouldBeFalse();
}
[Test]
public void CallingConstraintExistsReturnsFalseIfConstraintDoesNotExistWithSchema()
{
using (var table = new PostgresTestTable(Processor, "TestSchema", "id int"))
Processor.ConstraintExists("TestSchema", table.Name, "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingIndexExistsReturnsTrueIfIndexExistsWithSchema()
{
using (var table = new PostgresTestTable(Processor, "TestSchema", "id int"))
{
var idxName = string.Format("\"idx_{0}\"", quoter.UnQuote(table.Name));
var cmd = table.Connection.CreateCommand();
cmd.Transaction = table.Transaction;
cmd.CommandText = string.Format("CREATE INDEX {0} ON {1} (id)", idxName,table.NameWithSchema);
cmd.ExecuteNonQuery();
Processor.IndexExists("TestSchema", table.Name, idxName).ShouldBeTrue();
}
}
[Test]
public void CallingIndexExistsReturnsFalseIfTableDoesNotExistWithSchema()
{
Processor.IndexExists("TestSchema", "DoesNotExist", "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CallingIndexExistsReturnsFalseIfIndexDoesNotExistWithSchema()
{
using (var table = new PostgresTestTable(Processor, "TestSchema", "id int"))
Processor.IndexExists("TestSchema", table.Name, "DoesNotExist").ShouldBeFalse();
}
[Test]
public void CanReadDataWithSchema()
{
using (var table = new PostgresTestTable(Processor, "TestSchema", "id int"))
{
AddTestData(table);
DataSet ds = Processor.Read("SELECT * FROM {0}", table.NameWithSchema);
ds.ShouldNotBeNull();
ds.Tables.Count.ShouldBe(1);
ds.Tables[0].Rows.Count.ShouldBe(3);
ds.Tables[0].Rows[2][0].ShouldBe(2);
}
}
[Test]
public void CanReadTableDataWithSchema()
{
using (var table = new PostgresTestTable(Processor, "TestSchema", "id int"))
{
AddTestData(table);
DataSet ds = Processor.ReadTableData("TestSchema", table.Name);
ds.ShouldNotBeNull();
ds.Tables.Count.ShouldBe(1);
ds.Tables[0].Rows.Count.ShouldBe(3);
ds.Tables[0].Rows[2][0].ShouldBe(2);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Collections.Specialized
{
/// <devdoc>
/// <para>
/// OrderedDictionary offers IDictionary syntax with ordering. Objects
/// added or inserted in an IOrderedDictionary must have both a key and an index, and
/// can be retrieved by either.
/// OrderedDictionary is used by the ParameterCollection because MSAccess relies on ordering of
/// parameters, while almost all other DBs do not. DataKeyArray also uses it so
/// DataKeys can be retrieved by either their name or their index.
/// </para>
/// </devdoc>
public class OrderedDictionary : IOrderedDictionary
{
private ArrayList _objectsArray;
private Hashtable _objectsTable;
private readonly int _initialCapacity;
private readonly IEqualityComparer _comparer;
private readonly bool _readOnly;
private Object _syncRoot;
public OrderedDictionary() : this(0)
{
}
public OrderedDictionary(int capacity) : this(capacity, null)
{
}
public OrderedDictionary(IEqualityComparer comparer) : this(0, comparer)
{
}
public OrderedDictionary(int capacity, IEqualityComparer comparer)
{
_initialCapacity = capacity;
_comparer = comparer;
}
private OrderedDictionary(OrderedDictionary dictionary)
{
Debug.Assert(dictionary != null);
_readOnly = true;
_objectsArray = dictionary._objectsArray;
_objectsTable = dictionary._objectsTable;
_comparer = dictionary._comparer;
_initialCapacity = dictionary._initialCapacity;
}
/// <devdoc>
/// Gets the size of the table.
/// </devdoc>
public int Count
{
get
{
return objectsArray.Count;
}
}
/// <devdoc>
/// Indicates that the collection can grow.
/// </devdoc>
bool IDictionary.IsFixedSize
{
get
{
return _readOnly;
}
}
/// <devdoc>
/// Indicates that the collection is not read-only
/// </devdoc>
public bool IsReadOnly
{
get
{
return _readOnly;
}
}
/// <devdoc>
/// Indicates that this class is not synchronized
/// </devdoc>
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
/// <devdoc>
/// Gets the collection of keys in the table in order.
/// </devdoc>
public ICollection Keys
{
get
{
return new OrderedDictionaryKeyValueCollection(objectsArray, true);
}
}
private ArrayList objectsArray
{
get
{
if (_objectsArray == null)
{
_objectsArray = new ArrayList(_initialCapacity);
}
return _objectsArray;
}
}
private Hashtable objectsTable
{
get
{
if (_objectsTable == null)
{
_objectsTable = new Hashtable(_initialCapacity, _comparer);
}
return _objectsTable;
}
}
/// <devdoc>
/// The SyncRoot object. Not used because IsSynchronized is false
/// </devdoc>
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
/// <devdoc>
/// Gets or sets the object at the specified index
/// </devdoc>
public object this[int index]
{
get
{
return ((DictionaryEntry)objectsArray[index]).Value;
}
set
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index < 0 || index >= objectsArray.Count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
object key = ((DictionaryEntry)objectsArray[index]).Key;
objectsArray[index] = new DictionaryEntry(key, value);
objectsTable[key] = value;
}
}
/// <devdoc>
/// Gets or sets the object with the specified key
/// </devdoc>
public object this[object key]
{
get
{
return objectsTable[key];
}
set
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (objectsTable.Contains(key))
{
objectsTable[key] = value;
objectsArray[IndexOfKey(key)] = new DictionaryEntry(key, value);
}
else
{
Add(key, value);
}
}
}
/// <devdoc>
/// Returns an arrayList of the values in the table
/// </devdoc>
public ICollection Values
{
get
{
return new OrderedDictionaryKeyValueCollection(objectsArray, false);
}
}
/// <devdoc>
/// Adds a new entry to the table with the lowest-available index.
/// </devdoc>
public void Add(object key, object value)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
objectsTable.Add(key, value);
objectsArray.Add(new DictionaryEntry(key, value));
}
/// <devdoc>
/// Clears all elements in the table.
/// </devdoc>
public void Clear()
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
objectsTable.Clear();
objectsArray.Clear();
}
/// <devdoc>
/// Returns a readonly OrderedDictionary for the given OrderedDictionary.
/// </devdoc>
public OrderedDictionary AsReadOnly()
{
return new OrderedDictionary(this);
}
/// <devdoc>
/// Returns true if the key exists in the table, false otherwise.
/// </devdoc>
public bool Contains(object key)
{
return objectsTable.Contains(key);
}
/// <devdoc>
/// Copies the table to an array. This will not preserve order.
/// </devdoc>
public void CopyTo(Array array, int index)
{
objectsTable.CopyTo(array, index);
}
private int IndexOfKey(object key)
{
for (int i = 0; i < objectsArray.Count; i++)
{
object o = ((DictionaryEntry)objectsArray[i]).Key;
if (_comparer != null)
{
if (_comparer.Equals(o, key))
{
return i;
}
}
else
{
if (o.Equals(key))
{
return i;
}
}
}
return -1;
}
/// <devdoc>
/// Inserts a new object at the given index with the given key.
/// </devdoc>
public void Insert(int index, object key, object value)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index > Count || index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
objectsTable.Add(key, value);
objectsArray.Insert(index, new DictionaryEntry(key, value));
}
/// <devdoc>
/// Removes the entry at the given index.
/// </devdoc>
public void RemoveAt(int index)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (index >= Count || index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
object key = ((DictionaryEntry)objectsArray[index]).Key;
objectsArray.RemoveAt(index);
objectsTable.Remove(key);
}
/// <devdoc>
/// Removes the entry with the given key.
/// </devdoc>
public void Remove(object key)
{
if (_readOnly)
{
throw new NotSupportedException(SR.OrderedDictionary_ReadOnly);
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
int index = IndexOfKey(key);
if (index < 0)
{
return;
}
objectsTable.Remove(key);
objectsArray.RemoveAt(index);
}
#region IDictionary implementation
public virtual IDictionaryEnumerator GetEnumerator()
{
return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry);
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator()
{
return new OrderedDictionaryEnumerator(objectsArray, OrderedDictionaryEnumerator.DictionaryEntry);
}
#endregion
/// <devdoc>
/// OrderedDictionaryEnumerator works just like any other IDictionaryEnumerator, but it retrieves DictionaryEntries
/// in the order by index.
/// </devdoc>
private class OrderedDictionaryEnumerator : IDictionaryEnumerator
{
private int _objectReturnType;
internal const int Keys = 1;
internal const int Values = 2;
internal const int DictionaryEntry = 3;
private IEnumerator _arrayEnumerator;
internal OrderedDictionaryEnumerator(ArrayList array, int objectReturnType)
{
_arrayEnumerator = array.GetEnumerator();
_objectReturnType = objectReturnType;
}
/// <devdoc>
/// Retrieves the current DictionaryEntry. This is the same as Entry, but not strongly-typed.
/// </devdoc>
public object Current
{
get
{
if (_objectReturnType == Keys)
{
return ((DictionaryEntry)_arrayEnumerator.Current).Key;
}
if (_objectReturnType == Values)
{
return ((DictionaryEntry)_arrayEnumerator.Current).Value;
}
return Entry;
}
}
/// <devdoc>
/// Retrieves the current DictionaryEntry
/// </devdoc>
public DictionaryEntry Entry
{
get
{
return new DictionaryEntry(((DictionaryEntry)_arrayEnumerator.Current).Key, ((DictionaryEntry)_arrayEnumerator.Current).Value);
}
}
/// <devdoc>
/// Retrieves the key of the current DictionaryEntry
/// </devdoc>
public object Key
{
get
{
return ((DictionaryEntry)_arrayEnumerator.Current).Key;
}
}
/// <devdoc>
/// Retrieves the value of the current DictionaryEntry
/// </devdoc>
public object Value
{
get
{
return ((DictionaryEntry)_arrayEnumerator.Current).Value;
}
}
/// <devdoc>
/// Moves the enumerator pointer to the next member
/// </devdoc>
public bool MoveNext()
{
return _arrayEnumerator.MoveNext();
}
/// <devdoc>
/// Resets the enumerator pointer to the beginning.
/// </devdoc>
public void Reset()
{
_arrayEnumerator.Reset();
}
}
/// <devdoc>
/// OrderedDictionaryKeyValueCollection implements a collection for the Values and Keys properties
/// that is "live"- it will reflect changes to the OrderedDictionary on the collection made after the getter
/// was called.
/// </devdoc>
private class OrderedDictionaryKeyValueCollection : ICollection
{
private ArrayList _objects;
private bool _isKeys;
public OrderedDictionaryKeyValueCollection(ArrayList array, bool isKeys)
{
_objects = array;
_isKeys = isKeys;
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
foreach (object o in _objects)
{
array.SetValue(_isKeys ? ((DictionaryEntry)o).Key : ((DictionaryEntry)o).Value, index);
index++;
}
}
int ICollection.Count
{
get
{
return _objects.Count;
}
}
bool ICollection.IsSynchronized
{
get
{
return false;
}
}
object ICollection.SyncRoot
{
get
{
return _objects.SyncRoot;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return new OrderedDictionaryEnumerator(_objects, _isKeys == true ? OrderedDictionaryEnumerator.Keys : OrderedDictionaryEnumerator.Values);
}
}
}
}
| |
using System;
using Server;
using Server.Engines.Craft;
using Server.Mobiles;
using System.Collections.Generic;
namespace Server.Items
{
public enum PotionEffect
{
Nightsight, // 0
CureLesser, // 1
Cure, // 2
CureGreater, // 3
Agility, // 4
AgilityGreater, // 5
Strength, // 6
StrengthGreater, // 7
PoisonLesser, // 8
Poison, // 9
PoisonGreater, // 10
PoisonDeadly, // 11
Refresh, // 12
RefreshTotal, // 13
HealLesser, // 14
Heal, // 15
HealGreater, // 16
ExplosionLesser, // 17
Explosion, // 18
ExplosionGreater, // 19
Conflagration, // 20
ConflagrationGreater, // 21
MaskOfDeath, // 22 // Mask of Death is not available in OSI but does exist in cliloc files
MaskOfDeathGreater, // 23 // included in enumeration for compatability if later enabled by OSI
ConfusionBlast, // 24
ConfusionBlastGreater, // 25
//Ajout Myron Gender Potion
GenderSwap, // 26
FrogMorph, // 27
Invisibility, // 28
Parasitic, // 29
Darkglow, // 30
Hallucinogen, //31
Clumsy,
ClumsyGreater
}
public abstract class BasePotion : Item, ICraftable, ICommodity
{
public virtual bool CIT { get { return false; } }
public virtual bool CIS { get { return false; } }
private bool m_IntensifiedTime;
[CommandProperty(AccessLevel.GameMaster)]
public bool IntensifiedTime
{
get
{
return m_IntensifiedTime;
}
set
{
m_IntensifiedTime = value;
}
}
private bool m_IntensifiedStrength;
[CommandProperty(AccessLevel.GameMaster)]
public bool IntensifiedStrength
{
get
{
return m_IntensifiedStrength;
}
set
{
m_IntensifiedStrength = value;
}
}
private PotionEffect m_PotionEffect;
public PotionEffect PotionEffect
{
get
{
return m_PotionEffect;
}
set
{
m_PotionEffect = value;
InvalidateProperties();
}
}
int ICommodity.DescriptionNumber { get { return LabelNumber; } }
bool ICommodity.IsDeedable { get { return (Core.ML); } }
public override int LabelNumber{ get{ return 1041314 + (int)m_PotionEffect; } }
public BasePotion( int itemID, PotionEffect effect ) : base( itemID )
{
m_PotionEffect = effect;
Stackable = Core.ML;
Weight = 1.0;
}
public BasePotion( Serial serial ) : base( serial )
{
}
public virtual bool RequireFreeHand{ get{ return true; } }
public static bool HasFreeHand( Mobile m )
{
Item handOne = m.FindItemOnLayer( Layer.OneHanded );
Item handTwo = m.FindItemOnLayer( Layer.TwoHanded );
if ( handTwo is BaseWeapon )
handOne = handTwo;
if (handTwo is BaseRanged)
{
BaseRanged ranged = (BaseRanged)handTwo;
if ( ranged.Balanced )
return true;
}
return ( handOne == null || handTwo == null );
}
public override void OnDoubleClick( Mobile from )
{
if ( !Movable )
return;
if ( from.InRange( this.GetWorldLocation(), 1 ) )
{
if (!RequireFreeHand || HasFreeHand(from))
{
if (this is BaseExplosionPotion && Amount > 1)
{
BasePotion pot = (BasePotion)Activator.CreateInstance(this.GetType());
if (pot != null)
{
Amount--;
if (from.Backpack != null && !from.Backpack.Deleted)
{
from.Backpack.DropItem(pot);
}
else
{
pot.MoveToWorld(from.Location, from.Map);
}
pot.Drink( from );
}
}
else
{
this.Drink( from );
}
}
else
{
from.SendLocalizedMessage(502172); // You must have a free hand to drink a potion.
}
}
else
{
from.SendLocalizedMessage( 502138 ); // That is too far away for you to use
}
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 2 ); // version
writer.Write((bool)m_IntensifiedTime);
writer.Write((bool)m_IntensifiedStrength);
writer.Write( (int) m_PotionEffect );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 2:
{
m_IntensifiedTime = reader.ReadBool();
m_IntensifiedStrength = reader.ReadBool();
goto case 1;
}
case 1:
case 0:
{
m_PotionEffect = (PotionEffect)reader.ReadInt();
break;
}
}
if( version == 0 )
Stackable = Core.ML;
}
public abstract void Drink(Mobile from);
public static void PlayDrinkEffect( Mobile m )
{
m.RevealingAction();
m.PlaySound( 0x2D6 );
#region Dueling
if (!Engines.ConPVP.DuelContext.IsFreeConsume(m))
m.AddToBackpack(new Bottle());
#endregion
//m.AddToBackpack( new Bottle() );
if ( m.Body.IsHuman && !m.Mounted )
m.Animate( 34, 5, 1, true, false, 0 );
}
public static int EnhancePotions( Mobile m )
{
int EP = AosAttributes.GetValue( m, AosAttribute.EnhancePotions );
int skillBonus = m.Skills.Alchemy.Fixed / 330 * 10;
if ( Core.ML && EP > 50 && m.AccessLevel <= AccessLevel.Player )
EP = 50;
return ( EP + skillBonus );
}
public static TimeSpan Scale( Mobile m, TimeSpan v )
{
if ( !Core.AOS )
return v;
double scalar = 1.0 + ( 0.01 * EnhancePotions( m ) );
return TimeSpan.FromSeconds( v.TotalSeconds * scalar );
}
public static double Scale( Mobile m, double v )
{
if ( !Core.AOS )
return v;
double scalar = 1.0 + ( 0.01 * EnhancePotions( m ) );
return v * scalar;
}
public static int Scale( Mobile m, int v )
{
if ( !Core.AOS )
return v;
return AOS.Scale( v, 100 + EnhancePotions( m ) );
}
public override bool StackWith( Mobile from, Item dropped, bool playSound )
{
if( dropped is BasePotion && ((BasePotion)dropped).m_PotionEffect == m_PotionEffect )
return base.StackWith( from, dropped, playSound );
return false;
}
#region ICraftable Members
public int OnCraft( int quality, bool makersMark, Mobile from, CraftSystem craftSystem, Type typeRes, BaseTool tool, CraftItem craftItem, int resHue )
{
if ( craftSystem is DefAlchemy )
{
Container pack = from.Backpack;
if ( pack != null )
{
if ((int)PotionEffect >= (int)PotionEffect.Invisibility)
return 1;
List<PotionKeg> kegs = pack.FindItemsByType<PotionKeg>();
for ( int i = 0; i < kegs.Count; ++i )
{
PotionKeg keg = kegs[i];
if ( keg == null )
continue;
if ( keg.Held <= 0 || keg.Held >= 100 )
continue;
if ( keg.Type != PotionEffect )
continue;
++keg.Held;
Consume();
from.AddToBackpack( new Bottle() );
return -1; // signal placed in keg
}
}
}
return 1;
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using FluentAssertions;
using Microsoft.Build.Construction;
using Microsoft.DotNet.Tools;
using Microsoft.DotNet.Tools.Test.Utilities;
using Msbuild.Tests.Utilities;
using System;
using System.IO;
using Xunit;
namespace Microsoft.DotNet.Cli.Remove.Reference.Tests
{
public class GivenDotnetRemoveReference : TestBase
{
private const string HelpText = @"Usage: dotnet remove <PROJECT> reference [options] <PROJECT_PATH>
Arguments:
<PROJECT> The project file to operate on. If a file is not specified, the command will search the current directory for one.
<PROJECT_PATH> The paths to the referenced projects to remove.
Options:
-h, --help Show command line help.
-f, --framework <FRAMEWORK> Remove the reference only when targeting a specific framework.";
private const string RemoveCommandHelpText = @"Usage: dotnet remove [options] <PROJECT> [command]
Arguments:
<PROJECT> The project file to operate on. If a file is not specified, the command will search the current directory for one.
Options:
-h, --help Show command line help.
Commands:
package <PACKAGE_NAME> Remove a NuGet package reference from the project.
reference <PROJECT_PATH> Remove a project-to-project reference from the project.";
const string FrameworkNet451Arg = "-f net451";
const string ConditionFrameworkNet451 = "== 'net451'";
const string FrameworkNetCoreApp10Arg = "-f netcoreapp1.0";
const string ConditionFrameworkNetCoreApp10 = "== 'netcoreapp1.0'";
static readonly string[] DefaultFrameworks = new string[] { "netcoreapp1.0", "net451" };
private TestSetup Setup([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(Setup), string identifier = "")
{
return new TestSetup(
TestAssets.Get(TestSetup.TestGroup, TestSetup.ProjectName)
.CreateInstance(callingMethod: callingMethod, identifier: identifier)
.WithSourceFiles()
.Root
.FullName);
}
private ProjDir NewDir([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
return new ProjDir(TestAssets.CreateTestDirectory(callingMethod: callingMethod, identifier: identifier).FullName);
}
private ProjDir NewLib(string dir = null, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
var projDir = dir == null ? NewDir(callingMethod: callingMethod, identifier: identifier) : new ProjDir(dir);
try
{
string newArgs = $"classlib -o \"{projDir.Path}\" --no-restore";
new NewCommandShim()
.WithWorkingDirectory(projDir.Path)
.ExecuteWithCapturedOutput(newArgs)
.Should().Pass();
}
catch (System.ComponentModel.Win32Exception e)
{
throw new Exception($"Intermittent error in `dotnet new` occurred when running it in dir `{projDir.Path}`\nException:\n{e}");
}
return projDir;
}
private static void SetTargetFrameworks(ProjDir proj, string[] frameworks)
{
var csproj = proj.CsProj();
csproj.AddProperty("TargetFrameworks", string.Join(";", frameworks));
csproj.Save();
}
private ProjDir NewLibWithFrameworks(string dir = null, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
var ret = NewLib(dir, callingMethod: callingMethod, identifier: identifier);
SetTargetFrameworks(ret, DefaultFrameworks);
return ret;
}
private ProjDir GetLibRef(TestSetup setup)
{
return new ProjDir(setup.LibDir);
}
private ProjDir AddLibRef(TestSetup setup, ProjDir proj, string additionalArgs = "")
{
var ret = GetLibRef(setup);
new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"{additionalArgs} \"{ret.CsProjPath}\"")
.Should().Pass();
return ret;
}
private ProjDir AddValidRef(TestSetup setup, ProjDir proj, string frameworkArg = "")
{
var ret = new ProjDir(setup.ValidRefDir);
new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"{frameworkArg} \"{ret.CsProjPath}\"")
.Should().Pass();
return ret;
}
[Theory]
[InlineData("--help")]
[InlineData("-h")]
public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg)
{
var cmd = new RemoveReferenceCommand().Execute(helpArg);
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Theory]
[InlineData("")]
[InlineData("unknownCommandName")]
public void WhenNoCommandIsPassedItPrintsError(string commandName)
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput($"remove {commandName}");
cmd.Should().Fail();
cmd.StdErr.Should().Be(CommonLocalizableStrings.RequiredCommandNotPassed);
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(RemoveCommandHelpText);
}
[Fact]
public void WhenTooManyArgumentsArePassedItPrintsError()
{
var cmd = new AddReferenceCommand()
.WithProject("one two three")
.Execute("proj.csproj");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().BeVisuallyEquivalentTo($@"{string.Format(CommandLine.LocalizableStrings.UnrecognizedCommandOrArgument, "two")}
{string.Format(CommandLine.LocalizableStrings.UnrecognizedCommandOrArgument, "three")}");
}
[Theory]
[InlineData("idontexist.csproj")]
[InlineData("ihave?inv@lid/char\\acters")]
public void WhenNonExistingProjectIsPassedItPrintsErrorAndUsage(string projName)
{
var setup = Setup();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(projName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindProjectOrDirectory, projName));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenBrokenProjectIsPassedItPrintsErrorAndUsage()
{
string projName = "Broken/Broken.csproj";
var setup = Setup();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(projName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.ProjectIsInvalid, "Broken/Broken.csproj"));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenMoreThanOneProjectExistsInTheDirectoryItPrintsErrorAndUsage()
{
var setup = Setup();
var workingDir = Path.Combine(setup.TestRoot, "MoreThanOne");
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(workingDir)
.Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.MoreThanOneProjectInDirectory, workingDir + Path.DirectorySeparatorChar));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void WhenNoProjectsExistsInTheDirectoryItPrintsErrorAndUsage()
{
var setup = Setup();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindAnyProjectInDirectory, setup.TestRoot + Path.DirectorySeparatorChar));
cmd.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
}
[Fact]
public void ItRemovesRefWithoutCondAndPrintsStatus()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = AddLibRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void ItRemovesRefWithCondAndPrintsStatus()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = AddLibRef(setup, lib, FrameworkNet451Arg);
int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(libref.Name, ConditionFrameworkNet451).Should().Be(0);
}
[Fact]
public void WhenTwoDifferentRefsArePresentItDoesNotRemoveBoth()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = AddLibRef(setup, lib);
var validref = AddValidRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenRefWithoutCondIsNotThereItPrintsMessage()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = GetLibRef(setup);
string csprojContentBefore = lib.CsProjContent();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceCouldNotBeFound, libref.CsProjPath));
lib.CsProjContent().Should().BeEquivalentTo(csprojContentBefore);
}
[Fact]
public void WhenRefWithCondIsNotThereItPrintsMessage()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = GetLibRef(setup);
string csprojContentBefore = lib.CsProjContent();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceCouldNotBeFound, libref.CsProjPath));
lib.CsProjContent().Should().BeEquivalentTo(csprojContentBefore);
}
[Fact]
public void WhenRefWithAndWithoutCondArePresentAndRemovingNoCondItDoesNotRemoveOther()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var librefCond = AddLibRef(setup, lib, FrameworkNet451Arg);
var librefNoCond = AddLibRef(setup, lib);
var csprojBefore = lib.CsProj();
int noCondBefore = csprojBefore.NumberOfItemGroupsWithoutCondition();
int condBefore = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{librefNoCond.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(librefNoCond.Name).Should().Be(0);
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCond.Name, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenRefWithAndWithoutCondArePresentAndRemovingCondItDoesNotRemoveOther()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var librefCond = AddLibRef(setup, lib, FrameworkNet451Arg);
var librefNoCond = AddLibRef(setup, lib);
var csprojBefore = lib.CsProj();
int noCondBefore = csprojBefore.NumberOfItemGroupsWithoutCondition();
int condBefore = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{librefCond.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
csproj.NumberOfProjectReferencesWithIncludeContaining(librefNoCond.Name).Should().Be(1);
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCond.Name, ConditionFrameworkNet451).Should().Be(0);
}
[Fact]
public void WhenRefWithDifferentCondIsPresentItDoesNotRemoveIt()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var librefCondNet451 = AddLibRef(setup, lib, FrameworkNet451Arg);
var librefCondNetCoreApp10 = AddLibRef(setup, lib, FrameworkNetCoreApp10Arg);
var csprojBefore = lib.CsProj();
int condNet451Before = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
int condNetCoreApp10Before = csprojBefore.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNetCoreApp10);
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{librefCondNet451.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condNet451Before - 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCondNet451.Name, ConditionFrameworkNet451).Should().Be(0);
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNetCoreApp10).Should().Be(condNetCoreApp10Before);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(librefCondNetCoreApp10.Name, ConditionFrameworkNetCoreApp10).Should().Be(1);
}
[Fact]
public void WhenDuplicateReferencesArePresentItRemovesThemAll()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithDoubledRef"));
var libref = GetLibRef(setup);
string removedText = $@"{string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, setup.LibCsprojRelPath)}
{string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, setup.LibCsprojRelPath)}";
int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(removedText);
var csproj = proj.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingRefWithRelPathItRemovesRefWithAbsolutePath()
{
var setup = Setup();
var lib = GetLibRef(setup);
var libref = AddValidRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, setup.ValidRefCsprojRelToOtherProjPath));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingRefWithRelPathToProjectItRemovesRefWithPathRelToProject()
{
var setup = Setup();
var lib = GetLibRef(setup);
var libref = AddValidRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, setup.ValidRefCsprojRelToOtherProjPath));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingRefWithAbsolutePathItRemovesRefWithRelPath()
{
var setup = Setup();
var lib = GetLibRef(setup);
var libref = AddValidRef(setup, lib);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, setup.ValidRefCsprojRelToOtherProjPath));
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingMultipleReferencesItRemovesThemAll()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = AddLibRef(setup, lib);
var validref = AddValidRef(setup, lib);
string outputText = $@"{string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName))}
{string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine(setup.ValidRefCsprojRelPath))}";
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\" \"{validref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(outputText);
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(libref.Name).Should().Be(0);
csproj.NumberOfProjectReferencesWithIncludeContaining(validref.Name).Should().Be(0);
}
[Fact]
public void WhenPassingMultipleReferencesAndOneOfThemDoesNotExistItRemovesOne()
{
var setup = Setup();
var lib = NewLibWithFrameworks(setup.TestRoot);
var libref = GetLibRef(setup);
var validref = AddValidRef(setup, lib);
string outputText = $@"{string.Format(CommonLocalizableStrings.ProjectReferenceCouldNotBeFound, setup.LibCsprojPath)}
{string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine(setup.ValidRefCsprojRelPath))}";
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\" \"{validref.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(outputText);
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore - 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(validref.Name).Should().Be(0);
}
[Fact]
public void WhenDirectoryContainingProjectIsGivenReferenceIsRemoved()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
var libref = AddLibRef(setup, lib);
var result = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{libref.CsProjPath}\"");
result.Should().Pass();
result.StdOut.Should().Be(string.Format(CommonLocalizableStrings.ProjectReferenceRemoved, Path.Combine("Lib", setup.LibCsprojName)));
result.StdErr.Should().BeEmpty();
}
[Fact]
public void WhenDirectoryContainsNoProjectsItCancelsWholeOperation()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
var reference = "Empty";
var result = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute(reference);
result.Should().Fail();
result.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
result.StdErr.Should().Be(string.Format(CommonLocalizableStrings.CouldNotFindAnyProjectInDirectory, Path.Combine(setup.TestRoot, reference)));
}
[Fact]
public void WhenDirectoryContainsMultipleProjectsItCancelsWholeOperation()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
var reference = "MoreThanOne";
var result = new RemoveReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute(reference);
result.Should().Fail();
result.StdOut.Should().BeVisuallyEquivalentToIfNotLocalized(HelpText);
result.StdErr.Should().Be(string.Format(CommonLocalizableStrings.MoreThanOneProjectInDirectory, Path.Combine(setup.TestRoot, reference)));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServiceBus
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SubscriptionsOperations.
/// </summary>
public static partial class SubscriptionsOperationsExtensions
{
/// <summary>
/// List all the subscriptions under a specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639400.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
public static IPage<SubscriptionResource> ListAll(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName)
{
return operations.ListAllAsync(resourceGroupName, namespaceName, topicName).GetAwaiter().GetResult();
}
/// <summary>
/// List all the subscriptions under a specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639400.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SubscriptionResource>> ListAllAsync(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a topic subscription.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639385.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='subscriptionName'>
/// The subscription name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a subscription resource.
/// </param>
public static SubscriptionResource CreateOrUpdate(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName, SubscriptionCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, namespaceName, topicName, subscriptionName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a topic subscription.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639385.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='subscriptionName'>
/// The subscription name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a subscription resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SubscriptionResource> CreateOrUpdateAsync(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName, SubscriptionCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, subscriptionName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a subscription from the specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639381.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='subscriptionName'>
/// The subscription name.
/// </param>
public static void Delete(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName)
{
operations.DeleteAsync(resourceGroupName, namespaceName, topicName, subscriptionName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a subscription from the specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639381.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='subscriptionName'>
/// The subscription name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, subscriptionName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns a subscription description for the specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639402.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='subscriptionName'>
/// The subscription name.
/// </param>
public static SubscriptionResource Get(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName)
{
return operations.GetAsync(resourceGroupName, namespaceName, topicName, subscriptionName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a subscription description for the specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639402.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='topicName'>
/// The topic name.
/// </param>
/// <param name='subscriptionName'>
/// The subscription name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SubscriptionResource> GetAsync(this ISubscriptionsOperations operations, string resourceGroupName, string namespaceName, string topicName, string subscriptionName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, topicName, subscriptionName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// List all the subscriptions under a specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639400.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<SubscriptionResource> ListAllNext(this ISubscriptionsOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// List all the subscriptions under a specified topic.
/// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639400.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SubscriptionResource>> ListAllNextAsync(this ISubscriptionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Compute.Tests
{
public class VMScaleSetRollingUpgradeTests : VMScaleSetTestsBase
{
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create Network Resources with an SLB probe to use as a health probe
/// Create VMScaleSet in rolling upgrade mode
/// Get VMScaleSet Model View
/// Get VMScaleSet Instance View
/// Upgrade scale set with an extension
/// Delete VMScaleSet
/// Delete RG
/// </summary>
[Fact]
[Trait("Name", "TestVMScaleSetRollingUpgrade")]
public void TestVMScaleSetRollingUpgrade()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
// Create resource group
var rgName = TestUtilities.GenerateName(TestPrefix);
var vmssName = TestUtilities.GenerateName("vmss");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "southcentralus");
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile()
{
Extensions = new List<VirtualMachineScaleSetExtension>()
{
GetTestVMSSVMExtension(),
}
};
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist");
var getResponse = CreateVMScaleSet_NoAsyncTracking(
rgName,
vmssName,
storageAccountOutput,
imageRef,
out inputVMScaleSet,
null,
(vmScaleSet) =>
{
vmScaleSet.Overprovision = false;
vmScaleSet.UpgradePolicy.Mode = UpgradeMode.Rolling;
},
createWithManagedDisks: true,
createWithPublicIpAddress: false,
createWithHealthProbe: true);
ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);
var getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName);
Assert.NotNull(getInstanceViewResponse);
ValidateVMScaleSetInstanceView(inputVMScaleSet, getInstanceViewResponse);
var getVMInstanceViewResponse = m_CrpClient.VirtualMachineScaleSetVMs.GetInstanceView(rgName, vmssName, "0");
Assert.NotNull(getVMInstanceViewResponse);
Assert.NotNull(getVMInstanceViewResponse.VmHealth);
Assert.Equal("HealthState/healthy", getVMInstanceViewResponse.VmHealth.Status.Code);
// Update the VMSS by adding an extension
ComputeManagementTestUtilities.WaitSeconds(600);
var vmssStatus = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName);
inputVMScaleSet.VirtualMachineProfile.ExtensionProfile = extensionProfile;
UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet);
getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);
getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName);
Assert.NotNull(getInstanceViewResponse);
ValidateVMScaleSetInstanceView(inputVMScaleSet, getInstanceViewResponse);
m_CrpClient.VirtualMachineScaleSets.Delete(rgName, vmssName);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
//Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
//of the test to cover deletion. CSM does persistent retrying over all RG resources.
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
}
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create Network Resources with an SLB probe to use as a health probe
/// Create VMScaleSet in rolling upgrade mode
/// Perform a rolling OS upgrade
/// Validate the rolling upgrade completed
/// Perform another rolling OS upgrade
/// Cancel the rolling upgrade
/// Delete RG
/// </summary>
[Fact]
[Trait("Name", "TestVMScaleSetRollingUpgradeAPIs")]
public void TestVMScaleSetRollingUpgradeAPIs()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
// Create resource group
var rgName = TestUtilities.GenerateName(TestPrefix);
var vmssName = TestUtilities.GenerateName("vmss");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "southcentralus");
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
imageRef.Version = "latest";
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist");
var getResponse = CreateVMScaleSet_NoAsyncTracking(
rgName,
vmssName,
storageAccountOutput,
imageRef,
out inputVMScaleSet,
null,
(vmScaleSet) =>
{
vmScaleSet.Overprovision = false;
vmScaleSet.UpgradePolicy.Mode = UpgradeMode.Rolling;
vmScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy = new AutomaticOSUpgradePolicy()
{
EnableAutomaticOSUpgrade = false
};
},
createWithManagedDisks: true,
createWithPublicIpAddress: false,
createWithHealthProbe: true);
ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);
ComputeManagementTestUtilities.WaitSeconds(600);
var vmssStatus = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName);
m_CrpClient.VirtualMachineScaleSetRollingUpgrades.StartOSUpgrade(rgName, vmssName);
var rollingUpgradeStatus = m_CrpClient.VirtualMachineScaleSetRollingUpgrades.GetLatest(rgName, vmssName);
Assert.Equal(inputVMScaleSet.Sku.Capacity, rollingUpgradeStatus.Progress.SuccessfulInstanceCount);
var upgradeTask = m_CrpClient.VirtualMachineScaleSetRollingUpgrades.BeginStartOSUpgradeWithHttpMessagesAsync(rgName, vmssName);
vmssStatus = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName);
m_CrpClient.VirtualMachineScaleSetRollingUpgrades.Cancel(rgName, vmssName);
rollingUpgradeStatus = m_CrpClient.VirtualMachineScaleSetRollingUpgrades.GetLatest(rgName, vmssName);
Assert.True(rollingUpgradeStatus.RunningStatus.Code == RollingUpgradeStatusCode.Cancelled);
Assert.True(rollingUpgradeStatus.Progress.PendingInstanceCount >= 0);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
//Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
//of the test to cover deletion. CSM does persistent retrying over all RG resources.
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
}
/// <summary>
/// Covers following Operations:
/// Create RG
/// Create Storage Account
/// Create Network Resources with an SLB probe to use as a health probe
/// Create VMScaleSet in rolling upgrade mode
/// Perform a rolling OS upgrade
/// Validate Upgrade History
/// Delete RG
/// </summary>
[Fact]
[Trait("Name", "TestVMScaleSetRollingUpgradeHistory")]
public void TestVMScaleSetRollingUpgradeHistory()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
// Create resource group
var rgName = TestUtilities.GenerateName(TestPrefix);
var vmssName = TestUtilities.GenerateName("vmss");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "southcentralus");
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
imageRef.Version = "latest";
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist");
var getResponse = CreateVMScaleSet_NoAsyncTracking(
rgName,
vmssName,
storageAccountOutput,
imageRef,
out inputVMScaleSet,
null,
(vmScaleSet) =>
{
vmScaleSet.Overprovision = false;
vmScaleSet.UpgradePolicy.Mode = UpgradeMode.Rolling;
},
createWithManagedDisks: true,
createWithPublicIpAddress: false,
createWithHealthProbe: true);
ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);
ComputeManagementTestUtilities.WaitSeconds(600);
var vmssStatus = m_CrpClient.VirtualMachineScaleSets.GetInstanceView(rgName, vmssName);
m_CrpClient.VirtualMachineScaleSetRollingUpgrades.StartOSUpgrade(rgName, vmssName);
var rollingUpgradeHistory = m_CrpClient.VirtualMachineScaleSets.GetOSUpgradeHistory(rgName, vmssName);
Assert.NotNull(rollingUpgradeHistory);
Assert.True(rollingUpgradeHistory.Count() == 1);
Assert.Equal(inputVMScaleSet.Sku.Capacity, rollingUpgradeHistory.First().Properties.Progress.SuccessfulInstanceCount);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
//Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
//of the test to cover deletion. CSM does persistent retrying over all RG resources.
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
}
/// <summary>
/// Testing Automatic OS Upgrade Policy
/// </summary>
[Fact]
[Trait("Name", "TestVMScaleSetAutomaticOSUpgradePolicies")]
public void TestVMScaleSetAutomaticOSUpgradePolicies()
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
using (MockContext context = MockContext.Start(this.GetType()))
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "westcentralus");
EnsureClientsInitialized(context);
ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true);
imageRef.Version = "latest";
// Create resource group
var rgName = TestUtilities.GenerateName(TestPrefix);
var vmssName = TestUtilities.GenerateName("vmss");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
try
{
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist");
var getResponse = CreateVMScaleSet_NoAsyncTracking(
rgName,
vmssName,
storageAccountOutput,
imageRef,
out inputVMScaleSet,
null,
(vmScaleSet) =>
{
vmScaleSet.Overprovision = false;
vmScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy = new AutomaticOSUpgradePolicy()
{
DisableAutomaticRollback = false
};
},
createWithManagedDisks: true,
createWithPublicIpAddress: false,
createWithHealthProbe: true);
ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);
// Set Automatic OS Upgrade
inputVMScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy.EnableAutomaticOSUpgrade = true;
UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet);
getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);
// with automatic OS upgrade policy as null
inputVMScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy = null;
UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet);
getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);
Assert.NotNull(getResponse.UpgradePolicy.AutomaticOSUpgradePolicy);
Assert.True(getResponse.UpgradePolicy.AutomaticOSUpgradePolicy.DisableAutomaticRollback == false);
Assert.True(getResponse.UpgradePolicy.AutomaticOSUpgradePolicy.EnableAutomaticOSUpgrade == true);
// Toggle Disable Auto Rollback
inputVMScaleSet.UpgradePolicy.AutomaticOSUpgradePolicy = new AutomaticOSUpgradePolicy()
{
DisableAutomaticRollback = true,
EnableAutomaticOSUpgrade = false
};
UpdateVMScaleSet(rgName, vmssName, inputVMScaleSet);
getResponse = m_CrpClient.VirtualMachineScaleSets.Get(rgName, vmssName);
ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
//Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose
//of the test to cover deletion. CSM does persistent retrying over all RG resources.
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
}
// Does the following operations:
// Create ResourceGroup
// Create StorageAccount
// Create VMSS in Automatic Mode
// Perform an extension rolling upgrade
// Delete ResourceGroup
[Fact]
[Trait("Name", "TestVMScaleSetExtensionUpgradeAPIs")]
public void TestVMScaleSetExtensionUpgradeAPIs()
{
using (MockContext context = MockContext.Start(this.GetType()))
{
string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION");
string rgName = TestUtilities.GenerateName(TestPrefix);
string vmssName = TestUtilities.GenerateName("vmss");
string storageAccountName = TestUtilities.GenerateName(TestPrefix);
VirtualMachineScaleSet inputVMScaleSet;
try
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2");
EnsureClientsInitialized(context);
// Windows VM image
ImageReference imageRef = GetPlatformVMImage(true);
imageRef.Version = "latest";
var extension = GetTestVMSSVMExtension();
VirtualMachineScaleSetExtensionProfile extensionProfile = new VirtualMachineScaleSetExtensionProfile()
{
Extensions = new List<VirtualMachineScaleSetExtension>()
{
extension,
}
};
var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName);
m_CrpClient.VirtualMachineScaleSets.Delete(rgName, "VMScaleSetDoesNotExist");
var getResponse = CreateVMScaleSet_NoAsyncTracking(
rgName,
vmssName,
storageAccountOutput,
imageRef,
out inputVMScaleSet,
extensionProfile,
(vmScaleSet) =>
{
vmScaleSet.Overprovision = false;
vmScaleSet.UpgradePolicy.Mode = UpgradeMode.Automatic;
},
createWithManagedDisks: true,
createWithPublicIpAddress: false,
createWithHealthProbe: true);
ValidateVMScaleSet(inputVMScaleSet, getResponse, hasManagedDisks: true);
m_CrpClient.VirtualMachineScaleSetRollingUpgrades.StartExtensionUpgrade(rgName, vmssName);
var rollingUpgradeStatus = m_CrpClient.VirtualMachineScaleSetRollingUpgrades.GetLatest(rgName, vmssName);
Assert.Equal(inputVMScaleSet.Sku.Capacity, rollingUpgradeStatus.Progress.SuccessfulInstanceCount);
}
finally
{
Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation);
// Cleanup resource group and revert default location to the original location
m_ResourcesClient.ResourceGroups.Delete(rgName);
}
}
}
}
}
| |
/*===============================================================================
Copyright (c) 2015-2016 PTC Inc. All Rights Reserved.
Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
Vuforia is a trademark of PTC Inc., registered in the United States and other
countries.
==============================================================================*/
using UnityEngine;
using Vuforia;
using System.Collections;
/// <summary>
/// The VideoPlaybackBehaviour manages the appearance of a video that can be superimposed on a target.
/// Playback controls are shown on top of it to control the video.
/// </summary>
public class VideoPlaybackBehaviour : MonoBehaviour
{
#region PUBLIC_MEMBER_VARIABLES
/// <summary>
/// URL of the video, either a path to a local file or a remote address
/// </summary>
public string m_path = null;
/// <summary>
/// Texture for the play icon
/// </summary>
public Texture m_playTexture = null;
/// <summary>
/// Texture for the busy icon
/// </summary>
public Texture m_busyTexture = null;
/// <summary>
/// Texture for the error icon
/// </summary>
public Texture m_errorTexture = null;
/// <summary>
/// Define whether video should automatically start
/// </summary>
public bool m_autoPlay = false;
#endregion // PUBLIC_MEMBER_VARIABLES
#region PRIVATE_MEMBER_VARIABLES
private static bool sLoadingLocked = false;
private VideoPlayerHelper mVideoPlayer = null;
private bool mIsInited = false;
private bool mInitInProgess = false;
private bool mAppPaused = false;
private Texture2D mVideoTexture = null;
[SerializeField]
[HideInInspector]
private Texture mKeyframeTexture = null;
private VideoPlayerHelper.MediaType mMediaType =
VideoPlayerHelper.MediaType.ON_TEXTURE_FULLSCREEN;
private VideoPlayerHelper.MediaState mCurrentState =
VideoPlayerHelper.MediaState.NOT_READY;
private float mSeekPosition = 0.0f;
private bool isPlayableOnTexture;
private GameObject mIconPlane = null;
private bool mIconPlaneActive = false;
#endregion // PRIVATE_MEMBER_VARIABLES
#region PROPERTIES
/// <summary>
/// Returns the video player
/// </summary>
public VideoPlayerHelper VideoPlayer
{
get { return mVideoPlayer; }
}
/// <summary>
/// Returns the current playback state
/// </summary>
public VideoPlayerHelper.MediaState CurrentState
{
get { return mCurrentState; }
}
/// <summary>
/// Type of playback (on-texture only, fullscreen only, or both)
/// </summary>
public VideoPlayerHelper.MediaType MediaType
{
get { return mMediaType; }
set { mMediaType = value; }
}
/// <summary>
/// Texture displayed before video playback begins
/// </summary>
public Texture KeyframeTexture
{
get { return mKeyframeTexture; }
set { mKeyframeTexture = value; }
}
/// <summary>
/// Returns whether the video should automatically start
/// </summary>
public bool AutoPlay
{
get { return m_autoPlay; }
}
#endregion // PROPERTIES
#region UNITY_MONOBEHAVIOUR_METHODS
void Start()
{
// Find the icon plane (child of this object)
mIconPlane = transform.Find("Icon").gameObject;
// A filename or url must be set in the inspector
if (m_path == null || m_path.Length == 0)
{
Debug.Log("Please set a video url in the Inspector");
HandleStateChange(VideoPlayerHelper.MediaState.ERROR);
mCurrentState = VideoPlayerHelper.MediaState.ERROR;
this.enabled = false;
}
else
{
// Set the current state to Not Ready
HandleStateChange(VideoPlayerHelper.MediaState.NOT_READY);
mCurrentState = VideoPlayerHelper.MediaState.NOT_READY;
}
// Create the video player and set the filename
mVideoPlayer = new VideoPlayerHelper();
mVideoPlayer.SetFilename(m_path);
// Flip the plane as the video texture is mirrored on the horizontal
transform.localScale = new Vector3(-1 * Mathf.Abs(transform.localScale.x),
transform.localScale.y, transform.localScale.z);
// Scale the icon
ScaleIcon();
}
void OnRenderObject()
{
if (mAppPaused) return;
CheckIconPlaneVisibility();
if (!mIsInited)
{
if (!mInitInProgess)
{
mInitInProgess = true;
StartCoroutine(InitVideoPlayer());
}
return;
}
if (isPlayableOnTexture)
{
// Update the video texture with the latest video frame
VideoPlayerHelper.MediaState state = mVideoPlayer.UpdateVideoData();
if ((state == VideoPlayerHelper.MediaState.PLAYING)
|| (state == VideoPlayerHelper.MediaState.PLAYING_FULLSCREEN))
{
#if UNITY_WSA_10_0 && !UNITY_EDITOR
// For Direct3D video texture update, we need to be on the rendering thread
GL.IssuePluginEvent(VideoPlayerHelper.GetNativeRenderEventFunc(), 0);
#else
GL.InvalidateState();
#endif
}
// Check for playback state change
if (state != mCurrentState)
{
HandleStateChange(state);
mCurrentState = state;
}
}
else
{
// Get the current status
VideoPlayerHelper.MediaState state = mVideoPlayer.GetStatus();
if ((state == VideoPlayerHelper.MediaState.PLAYING)
|| (state == VideoPlayerHelper.MediaState.PLAYING_FULLSCREEN))
{
GL.InvalidateState();
}
// Check for playback state change
if (state != mCurrentState)
{
HandleStateChange(state);
mCurrentState = state;
}
}
}
private IEnumerator InitVideoPlayer()
{
// Initialize the video player
VuforiaRenderer.RendererAPI rendererAPI = VuforiaRenderer.Instance.GetRendererAPI();
if (mVideoPlayer.Init(rendererAPI))
{
yield return new WaitForEndOfFrame();
// Wait in case other videos are loading at the same time
while (sLoadingLocked)
{
yield return new WaitForSeconds(0.5f);
}
// Now we can proceed to load the video
StartCoroutine(LoadVideo());
}
else
{
Debug.Log("Could not initialize video player");
HandleStateChange(VideoPlayerHelper.MediaState.ERROR);
this.enabled = false;
}
}
private IEnumerator LoadVideo()
{
// Lock file loading
sLoadingLocked = true;
// Load the video
if (mVideoPlayer.Load(m_path, mMediaType, false, 0))
{
yield return new WaitForEndOfFrame();
#if UNITY_WSA_10_0 && !UNITY_EDITOR
// On Windows 10 (WSA), we need to wait a little bit after loading a video,
// to avoid potential conflicts when loading multiple videos
yield return new WaitForSeconds(1.5f);
#endif
// Unlock file loading
sLoadingLocked = false;
// Proceed to video preparation
StartCoroutine( PrepareVideo() );
}
else
{
// Unlock file loading
sLoadingLocked = false;
Debug.Log("Could not load video '" + m_path + "' for media type " + mMediaType);
HandleStateChange(VideoPlayerHelper.MediaState.ERROR);
this.enabled = false;
}
}
private IEnumerator PrepareVideo()
{
// Get the video player status
VideoPlayerHelper.MediaState state = mVideoPlayer.GetStatus();
if (state == VideoPlayerHelper.MediaState.ERROR)
{
Debug.Log("Cannot prepare video, as the player is in error state.");
HandleStateChange(VideoPlayerHelper.MediaState.ERROR);
this.enabled = false;
}
else
{
// Not in error state, we can move on...
while (mVideoPlayer.GetStatus() == VideoPlayerHelper.MediaState.NOT_READY)
{
// Wait one or few frames for video state to become ready
yield return new WaitForEndOfFrame();
}
// Video player is ready
Debug.Log("VideoPlayer ready.");
// Initialize the video texture
bool isOpenGLRendering = (
VuforiaRenderer.Instance.GetRendererAPI() == VuforiaRenderer.RendererAPI.GL_20
|| VuforiaRenderer.Instance.GetRendererAPI() == VuforiaRenderer.RendererAPI.GL_30);
InitVideoTexture(isOpenGLRendering);
// Can we play this video on a texture?
isPlayableOnTexture = mVideoPlayer.IsPlayableOnTexture();
if (isPlayableOnTexture)
{
// Pass the video texture id to the video player
mVideoPlayer.SetVideoTexturePtr(mVideoTexture.GetNativeTexturePtr());
// Get the video width and height
int videoWidth = mVideoPlayer.GetVideoWidth();
int videoHeight = mVideoPlayer.GetVideoHeight();
if (videoWidth > 0 && videoHeight > 0)
{
// Scale the video plane to match the video aspect ratio
float aspect = videoHeight / (float)videoWidth;
// Flip the plane as the video texture is mirrored on the horizontal
transform.localScale = new Vector3(-0.1f, 0.1f, 0.1f * aspect);
}
// Seek ahead if necessary
if (mSeekPosition > 0)
{
mVideoPlayer.SeekTo(mSeekPosition);
}
}
else
{
// Handle the state change
state = mVideoPlayer.GetStatus();
HandleStateChange(state);
mCurrentState = state;
}
// Scale the icon
ScaleIcon();
mIsInited = true;
}
mInitInProgess = false;
yield return new WaitForEndOfFrame();
}
void OnApplicationPause(bool pause)
{
mAppPaused = pause;
if (!mIsInited)
return;
if (pause)
{
// Handle pause event natively
mVideoPlayer.OnPause();
// Store the playback position for later
mSeekPosition = mVideoPlayer.GetCurrentPosition();
// Deinit the video
mVideoPlayer.Deinit();
// Reset initialization parameters
mIsInited = false;
mInitInProgess = false;
// Set the current state to Not Ready
HandleStateChange(VideoPlayerHelper.MediaState.NOT_READY);
mCurrentState = VideoPlayerHelper.MediaState.NOT_READY;
}
}
void OnDestroy()
{
// Deinit the video
mVideoPlayer.Deinit();
}
#endregion // UNITY_MONOBEHAVIOUR_METHODS
#region PUBLIC_METHODS
/// <summary>
/// Displays the busy icon on top of the video
/// </summary>
public void ShowBusyIcon()
{
mIconPlane.GetComponent<Renderer>().material.mainTexture = m_busyTexture;
}
/// <summary>
/// Displays the play icon on top of the video
/// </summary>
public void ShowPlayIcon()
{
mIconPlane.GetComponent<Renderer>().material.mainTexture = m_playTexture;
}
#endregion // PUBLIC_METHODS
#region PRIVATE_METHODS
// Initialize the video texture
private void InitVideoTexture(bool isOpenGLRendering)
{
// Create texture whose content will be updated in native plugin code.
// Note: width and height don't matter and may be zero for OpenGL textures,
// as we update the texture content via glTexImage;
// however they MUST be correctly initialized for iOS METAL and D3D textures;
// similarly, the format must be correctly initialized to 4 bytes (BGRA32) per pixel
int w = mVideoPlayer.GetVideoWidth();
int h = mVideoPlayer.GetVideoHeight();
Debug.Log("InitVideoTexture with size: " + w + " x " + h);
mVideoTexture = isOpenGLRendering ?
new Texture2D(0, 0, TextureFormat.RGB565, false) :
new Texture2D(w, h, TextureFormat.BGRA32, false);
mVideoTexture.filterMode = FilterMode.Bilinear;
mVideoTexture.wrapMode = TextureWrapMode.Clamp;
}
// Handle video playback state changes
private void HandleStateChange(VideoPlayerHelper.MediaState newState)
{
// If the movie is playing or paused render the video texture
// Otherwise render the keyframe
if (newState == VideoPlayerHelper.MediaState.PLAYING ||
newState == VideoPlayerHelper.MediaState.PAUSED)
{
Material mat = GetComponent<Renderer>().material;
mat.mainTexture = mVideoTexture;
mat.mainTextureScale = new Vector2(1, 1);
}
else
{
if (mKeyframeTexture != null)
{
Material mat = GetComponent<Renderer>().material;
mat.mainTexture = mKeyframeTexture;
mat.mainTextureScale = new Vector2(1, -1);
}
}
// Display the appropriate icon, or disable if not needed
switch (newState)
{
case VideoPlayerHelper.MediaState.READY:
case VideoPlayerHelper.MediaState.REACHED_END:
case VideoPlayerHelper.MediaState.PAUSED:
case VideoPlayerHelper.MediaState.STOPPED:
mIconPlane.GetComponent<Renderer>().material.mainTexture = m_playTexture;
mIconPlaneActive = true;
break;
case VideoPlayerHelper.MediaState.NOT_READY:
case VideoPlayerHelper.MediaState.PLAYING_FULLSCREEN:
mIconPlane.GetComponent<Renderer>().material.mainTexture = m_busyTexture;
mIconPlaneActive = true;
break;
case VideoPlayerHelper.MediaState.ERROR:
mIconPlane.GetComponent<Renderer>().material.mainTexture = m_errorTexture;
mIconPlaneActive = true;
break;
default:
mIconPlaneActive = false;
break;
}
if (newState == VideoPlayerHelper.MediaState.PLAYING_FULLSCREEN)
{
// Switching to full screen, disable VuforiaBehaviour (only applicable for iOS)
VuforiaBehaviour.Instance.enabled = false;
}
else if (mCurrentState == VideoPlayerHelper.MediaState.PLAYING_FULLSCREEN)
{
// Switching away from full screen, enable VuforiaBehaviour (only applicable for iOS)
VuforiaBehaviour.Instance.enabled = true;
}
}
private void ScaleIcon()
{
// Icon should fill 50% of the narrowest side of the video
float videoWidth = Mathf.Abs(transform.localScale.x);
float videoHeight = Mathf.Abs(transform.localScale.z);
float iconWidth, iconHeight;
if (videoWidth > videoHeight)
{
iconWidth = 0.5f * videoHeight / videoWidth;
iconHeight = 0.5f;
}
else
{
iconWidth = 0.5f;
iconHeight = 0.5f * videoWidth / videoHeight;
}
mIconPlane.transform.localScale = new Vector3(-iconWidth, 1.0f, iconHeight);
}
private void CheckIconPlaneVisibility()
{
// If the video object renderer is currently enabled, we might need to toggle the icon plane visibility
if (GetComponent<Renderer>().enabled)
{
// Check if the icon plane renderer has to be disabled explicitly in case it was enabled by another script (e.g. TrackableEventHandler)
Renderer rendererComp = mIconPlane.GetComponent<Renderer>();
if (rendererComp.enabled != mIconPlaneActive)
rendererComp.enabled = mIconPlaneActive;
}
}
#endregion // PRIVATE_METHODS
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Tests
{
public class ImmutableSortedSetBuilderTest : ImmutablesTestBase
{
[Fact]
public void CreateBuilder()
{
ImmutableSortedSet<string>.Builder builder = ImmutableSortedSet.CreateBuilder<string>();
Assert.NotNull(builder);
builder = ImmutableSortedSet.CreateBuilder<string>(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableSortedSet<int>.Empty.ToBuilder();
Assert.True(builder.Add(3));
Assert.True(builder.Add(5));
Assert.False(builder.Add(5));
Assert.Equal(2, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var set = builder.ToImmutable();
Assert.Equal(builder.Count, set.Count);
Assert.True(builder.Add(8));
Assert.Equal(3, builder.Count);
Assert.Equal(2, set.Count);
Assert.True(builder.Contains(8));
Assert.False(set.Contains(8));
}
[Fact]
public void BuilderFromSet()
{
var set = ImmutableSortedSet<int>.Empty.Add(1);
var builder = set.ToBuilder();
Assert.True(builder.Contains(1));
Assert.True(builder.Add(3));
Assert.True(builder.Add(5));
Assert.False(builder.Add(5));
Assert.Equal(3, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var set2 = builder.ToImmutable();
Assert.Equal(builder.Count, set2.Count);
Assert.True(set2.Contains(1));
Assert.True(builder.Add(8));
Assert.Equal(4, builder.Count);
Assert.Equal(3, set2.Count);
Assert.True(builder.Contains(8));
Assert.False(set.Contains(8));
Assert.False(set2.Contains(8));
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10)).ToBuilder();
Assert.Equal(Enumerable.Range(1, 10), builder);
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11);
// Verify that a new enumerator will succeed.
Assert.Equal(Enumerable.Range(1, 11), builder);
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
Assert.Equal(Enumerable.Range(1, 11), builder);
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableSortedSet<int>.Empty.Add(1);
var builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // no changes at all.
builder.Add(2);
var newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void GetEnumeratorTest()
{
var builder = ImmutableSortedSet.Create("a", "B").WithComparer(StringComparer.Ordinal).ToBuilder();
IEnumerable<string> enumerable = builder;
using (var enumerator = enumerable.GetEnumerator())
{
Assert.True(enumerator.MoveNext());
Assert.Equal("B", enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal("a", enumerator.Current);
Assert.False(enumerator.MoveNext());
}
}
[Fact]
public void MaxMin()
{
var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder();
Assert.Equal(1, builder.Min);
Assert.Equal(3, builder.Max);
}
[Fact]
public void Clear()
{
var set = ImmutableSortedSet<int>.Empty.Add(1);
var builder = set.ToBuilder();
builder.Clear();
Assert.Equal(0, builder.Count);
}
[Fact]
public void KeyComparer()
{
var builder = ImmutableSortedSet.Create("a", "B").ToBuilder();
Assert.Same(Comparer<string>.Default, builder.KeyComparer);
Assert.True(builder.Contains("a"));
Assert.False(builder.Contains("A"));
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
Assert.Equal(2, builder.Count);
Assert.True(builder.Contains("a"));
Assert.True(builder.Contains("A"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void KeyComparerCollisions()
{
var builder = ImmutableSortedSet.Create("a", "A").ToBuilder();
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Equal(1, builder.Count);
Assert.True(builder.Contains("a"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
Assert.Equal(1, set.Count);
Assert.True(set.Contains("a"));
}
[Fact]
public void KeyComparerEmptyCollection()
{
var builder = ImmutableSortedSet.Create<string>().ToBuilder();
Assert.Same(Comparer<string>.Default, builder.KeyComparer);
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void UnionWith()
{
var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.UnionWith(null));
builder.UnionWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1, 2, 3, 4 }, builder);
}
[Fact]
public void ExceptWith()
{
var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.ExceptWith(null));
builder.ExceptWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1 }, builder);
}
[Fact]
public void SymmetricExceptWith()
{
var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.SymmetricExceptWith(null));
builder.SymmetricExceptWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1, 4 }, builder);
}
[Fact]
public void IntersectWith()
{
var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IntersectWith(null));
builder.IntersectWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 2, 3 }, builder);
}
[Fact]
public void IsProperSubsetOf()
{
var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsProperSubsetOf(null));
Assert.False(builder.IsProperSubsetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsProperSubsetOf(Enumerable.Range(1, 5)));
}
[Fact]
public void IsProperSupersetOf()
{
var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsProperSupersetOf(null));
Assert.False(builder.IsProperSupersetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsProperSupersetOf(Enumerable.Range(1, 2)));
}
[Fact]
public void IsSubsetOf()
{
var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsSubsetOf(null));
Assert.False(builder.IsSubsetOf(Enumerable.Range(1, 2)));
Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 5)));
}
[Fact]
public void IsSupersetOf()
{
var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsSupersetOf(null));
Assert.False(builder.IsSupersetOf(Enumerable.Range(1, 4)));
Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 2)));
}
[Fact]
public void Overlaps()
{
var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.Overlaps(null));
Assert.True(builder.Overlaps(Enumerable.Range(3, 2)));
Assert.False(builder.Overlaps(Enumerable.Range(4, 3)));
}
[Fact]
public void Remove()
{
var builder = ImmutableSortedSet.Create("a").ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.Remove(null));
Assert.False(builder.Remove("b"));
Assert.True(builder.Remove("a"));
}
[Fact]
public void Reverse()
{
var builder = ImmutableSortedSet.Create("a", "b").ToBuilder();
Assert.Equal(new[] { "b", "a" }, builder.Reverse());
}
[Fact]
public void SetEquals()
{
var builder = ImmutableSortedSet.Create("a").ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.SetEquals(null));
Assert.False(builder.SetEquals(new[] { "b" }));
Assert.True(builder.SetEquals(new[] { "a" }));
Assert.True(builder.SetEquals(builder));
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> builder = ImmutableSortedSet.Create("a").ToBuilder();
builder.Add("b");
Assert.True(builder.Contains("b"));
var array = new string[3];
builder.CopyTo(array, 1);
Assert.Equal(new[] { null, "a", "b" }, array);
Assert.False(builder.IsReadOnly);
Assert.Equal(new[] { "a", "b" }, builder.ToArray()); // tests enumerator
}
[Fact]
public void ICollectionMethods()
{
ICollection builder = ImmutableSortedSet.Create("a").ToBuilder();
var array = new string[builder.Count + 1];
builder.CopyTo(array, 1);
Assert.Equal(new[] { null, "a" }, array);
Assert.False(builder.IsSynchronized);
Assert.NotNull(builder.SyncRoot);
Assert.Same(builder.SyncRoot, builder.SyncRoot);
}
[Fact]
public void Indexer()
{
var builder = ImmutableSortedSet.Create(1, 3, 2).ToBuilder();
Assert.Equal(1, builder[0]);
Assert.Equal(2, builder[1]);
Assert.Equal(3, builder[2]);
Assert.Throws<ArgumentOutOfRangeException>(() => builder[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => builder[3]);
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedSet.CreateBuilder<string>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableSortedSet.CreateBuilder<int>());
}
}
}
| |
using System;
using System.IO;
using System.Data;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using LumiSoft.Net;
namespace LumiSoft.Net.FTP.Server
{
/// <summary>
/// FTP Session.
/// </summary>
public class FTP_Session : ISocketServerSession
{
private BufferedSocket m_pSocket = null; // Reference to client Socket.
private FTP_Server m_pServer = null; // Referance to POP3 server.
private string m_SessionID = ""; // Holds session ID.
private string m_UserName = ""; // Holds loggedIn UserName.
private string m_CurrentDir = "/";
private string m_RenameFrom = "";
private bool m_PassiveMode = false;
private TcpListener m_pPassiveListener = null;
private IPEndPoint m_pDataConEndPoint = null;
private bool m_Authenticated = false; // Holds authentication flag.
private int m_BadCmdCount = 0; // Holds number of bad commands.
private DateTime m_SessionStartTime;
private DateTime m_LastDataTime;
private object m_Tag = null;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="clientSocket">Referance to socket.</param>
/// <param name="server">Referance to FTP server.</param>
/// <param name="sessionID">Session ID which is assigned to this session.</param>
/// <param name="logWriter">Log writer.</param>
public FTP_Session(Socket clientSocket,FTP_Server server,string sessionID,SocketLogger logWriter)
{
m_pSocket = new BufferedSocket(clientSocket);
m_pServer = server;
m_SessionID = sessionID;
// m_pLogWriter = logWriter;
m_SessionStartTime = DateTime.Now;
m_LastDataTime = DateTime.Now;
m_pSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.NoDelay,1);
m_pSocket.Activity += new EventHandler(OnSocketActivity);
// Start session proccessing
StartSession();
}
#region method StartSession
/// <summary>
/// Starts session.
/// </summary>
private void StartSession()
{
// Add session to session list
m_pServer.AddSession(this);
// if(m_pServer.LogCommands){
// m_pLogWriter.AddEntry("//----- Sys: 'Session:'" + this.SessionID + " added " + DateTime.Now);
// }
// Check if ip is allowed to connect this computer
if(m_pServer.OnValidate_IpAddress(this.LocalEndPoint,this.RemoteEndPoint)){
// Notify that server is ready
m_pSocket.SendLine("220 " + m_pServer.HostName + " FTP server ready");
BeginRecieveCmd();
}
else{
EndSession();
}
}
#endregion
#region method EndSession
/// <summary>
/// Ends session, closes socket.
/// </summary>
private void EndSession()
{
m_pServer.RemoveSession(this);
// Write logs to log file, if needed
if(m_pServer.LogCommands){
// m_pLogWriter.AddEntry("//----- Sys: 'Session:'" + this.SessionID + " removed " + DateTime.Now);
// m_pLogWriter.Flush();
m_pSocket.Logger.Flush();
}
if(m_pSocket != null){
m_pSocket.Shutdown(SocketShutdown.Both);
m_pSocket.Close();
m_pSocket = null;
}
}
#endregion
#region method OnSessionTimeout
/// <summary>
/// Is called by server when session has timed out.
/// </summary>
public void OnSessionTimeout()
{
try{
m_pSocket.SendLine("500 Session timeout, closing transmission channel");
}
catch{
}
EndSession();
}
#endregion
#region method OnSocketActivity
/// <summary>
/// Is called if there was some activity on socket, some data sended or received.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnSocketActivity(object sender,EventArgs e)
{
m_LastDataTime = DateTime.Now;
}
#endregion
#region method OnError
/// <summary>
/// Is called when error occures.
/// </summary>
/// <param name="x"></param>
private void OnError(Exception x)
{
try{
if(x is SocketException){
SocketException xs = (SocketException)x;
// Client disconnected without shutting down
if(xs.ErrorCode == 10054 || xs.ErrorCode == 10053){
if(m_pServer.LogCommands){
// m_pLogWriter.AddEntry("Client aborted/disconnected",this.SessionID,this.RemoteEndPoint.Address.ToString(),"C");
m_pSocket.Logger.AddTextEntry("Client aborted/disconnected");
}
EndSession();
// Exception handled, return
return;
}
}
m_pServer.OnSysError("",x);
}
catch(Exception ex){
m_pServer.OnSysError("",ex);
}
}
#endregion
#region method BeginRecieveCmd
/// <summary>
/// Starts recieveing command.
/// </summary>
private void BeginRecieveCmd()
{
MemoryStream strm = new MemoryStream();
m_pSocket.BeginReadLine(strm,1024,strm,new SocketCallBack(this.EndRecieveCmd));
}
#endregion
#region method EndRecieveCmd
/// <summary>
/// Is called if command is recieved.
/// </summary>
/// <param name="result"></param>
/// <param name="exception"></param>
/// <param name="count"></param>
/// <param name="tag"></param>
private void EndRecieveCmd(SocketCallBackResult result,long count,Exception exception,object tag)
{
try{
switch(result)
{
case SocketCallBackResult.Ok:
MemoryStream strm = (MemoryStream)tag;
string cmdLine = System.Text.Encoding.Default.GetString(strm.ToArray());
// if(m_pServer.LogCommands){
// m_pLogWriter.AddEntry(cmdLine + "<CRLF>",this.SessionID,this.RemoteEndPoint.Address.ToString(),"C");
// }
// Exceute command
if(SwitchCommand(cmdLine)){
// Session end, close session
EndSession();
}
break;
case SocketCallBackResult.LengthExceeded:
m_pSocket.SendLine("500 Line too long.");
BeginRecieveCmd();
break;
case SocketCallBackResult.SocketClosed:
EndSession();
break;
case SocketCallBackResult.Exception:
OnError(exception);
break;
}
}
catch(Exception x){
OnError(x);
}
}
#endregion
#region function SwitchCommand
/// <summary>
/// Parses and executes POP3 commmand.
/// </summary>
/// <param name="commandTxt">FTP command text.</param>
/// <returns>Returns true,if session must be terminated.</returns>
private bool SwitchCommand(string commandTxt)
{
//---- Parse command --------------------------------------------------//
string[] cmdParts = commandTxt.TrimStart().Split(new char[]{' '});
string command = cmdParts[0].ToUpper().Trim();
string argsText = Core.GetArgsText(commandTxt,command);
//---------------------------------------------------------------------//
/*
USER <SP> <username> <CRLF>
PASS <SP> <password> <CRLF>
ACCT <SP> <account-information> <CRLF>
CWD <SP> <pathname> <CRLF>
CDUP <CRLF>
SMNT <SP> <pathname> <CRLF>
QUIT <CRLF>
REIN <CRLF>
PORT <SP> <host-port> <CRLF>
PASV <CRLF>
TYPE <SP> <type-code> <CRLF>
STRU <SP> <structure-code> <CRLF>
MODE <SP> <mode-code> <CRLF>
RETR <SP> <pathname> <CRLF>
STOR <SP> <pathname> <CRLF>
STOU <CRLF>
APPE <SP> <pathname> <CRLF>
ALLO <SP> <decimal-integer>
[<SP> R <SP> <decimal-integer>] <CRLF>
REST <SP> <marker> <CRLF>
RNFR <SP> <pathname> <CRLF>
RNTO <SP> <pathname> <CRLF>
ABOR <CRLF>
DELE <SP> <pathname> <CRLF>
RMD <SP> <pathname> <CRLF>
MKD <SP> <pathname> <CRLF>
PWD <CRLF>
LIST [<SP> <pathname>] <CRLF>
NLST [<SP> <pathname>] <CRLF>
SITE <SP> <string> <CRLF>
SYST <CRLF>
STAT [<SP> <pathname>] <CRLF>
HELP [<SP> <string>] <CRLF>
NOOP <CRLF>
*/
switch(command)
{
case "USER":
USER(argsText);
break;
case "PASS":
PASS(argsText);
break;
case "CWD":
CWD(argsText);
break;
case "CDUP":
CDUP(argsText);
break;
// case "REIN":
// break;
case "QUIT":
QUIT();
return true;
case "PORT":
PORT(argsText);
break;
case "PASV":
PASV(argsText);
break;
case "TYPE":
TYPE(argsText);
break;
case "RETR":
RETR(argsText);
break;
case "STOR":
STOR(argsText);
break;
// case "STOU":
// break;
case "APPE":
APPE(argsText);
break;
// case "REST":
// break;
case "RNFR":
RNFR(argsText);
break;
case "RNTO":
RNTO(argsText);
break;
// case "ABOR":
// break;
case "DELE":
DELE(argsText);
break;
case "RMD":
RMD(argsText);
break;
case "MKD":
MKD(argsText);
break;
case "PWD":
PWD();
break;
case "LIST":
LIST(argsText);
break;
case "NLST":
NLST(argsText);
break;
case "SYST":
SYST();
break;
// case "STAT":
// break;
// case "HELP":
// break;
case "NOOP":
NOOP();
break;
case "":
break;
default:
m_pSocket.SendLine("500 Invalid command " + command);
//---- Check that maximum bad commands count isn't exceeded ---------------//
if(m_BadCmdCount > m_pServer.MaxBadCommands-1){
m_pSocket.SendLine("421 Too many bad commands, closing transmission channel");
return true;
}
m_BadCmdCount++;
//-------------------------------------------------------------------------//
break;
}
BeginRecieveCmd();
return false;
}
#endregion
#region method USER
private void USER(string argsText)
{
if(m_Authenticated){
m_pSocket.SendLine("500 You are already authenticated");
return;
}
if(m_UserName.Length > 0){
m_pSocket.SendLine("500 username is already specified, please specify password");
return;
}
string[] param = argsText.Split(new char[]{' '});
// There must be only one parameter - userName
if(argsText.Length > 0 && param.Length == 1){
string userName = param[0];
m_pSocket.SendLine("331 Password required or user:'" + userName + "'");
m_UserName = userName;
}
else{
m_pSocket.SendLine("500 Syntax error. Syntax:{USER username}");
}
}
#endregion
#region method PASS
private void PASS(string argsText)
{
if(m_Authenticated){
m_pSocket.SendLine("500 You are already authenticated");
return;
}
if(m_UserName.Length == 0){
m_pSocket.SendLine("503 please specify username first");
return;
}
string[] param = argsText.Split(new char[]{' '});
// There may be only one parameter - password
if(param.Length == 1){
string password = param[0];
// Authenticate user
if(m_pServer.OnAuthUser(this,m_UserName,password,"",AuthType.Plain)){
m_Authenticated = true;
m_pSocket.SendLine("230 Password ok");
}
else{
m_pSocket.SendLine("530 UserName or Password is incorrect");
m_UserName = ""; // Reset userName !!!
}
}
else{
m_pSocket.SendLine("500 Syntax error. Syntax:{PASS userName}");
}
}
#endregion
#region method CWD
private void CWD(string argsText)
{
/*
This command allows the user to work with a different
directory or dataset for file storage or retrieval without
altering his login or accounting information. Transfer
parameters are similarly unchanged. The argument is a
pathname specifying a directory or other system dependent
file group designator.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
string dir = GetAndNormailizePath(argsText);
//Check if dir exists and is accesssible for this user
if(m_pServer.OnDirExists(this,dir)){
m_CurrentDir = dir;
m_pSocket.SendLine("250 CDW command successful.");
}
else{
m_pSocket.SendLine("550 System can't find directory '" + dir + "'.");
}
}
#endregion
#region method CDUP
private void CDUP(string argsText)
{
/*
This command is a special case of CWD, and is included to
simplify the implementation of programs for transferring
directory trees between operating systems having different
syntaxes for naming the parent directory. The reply codes
shall be identical to the reply codes of CWD.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
// Move dir up if possible
string[] pathParts = m_CurrentDir.Split('/');
if(pathParts.Length > 1){
m_CurrentDir = "";
for(int i=0;i<(pathParts.Length - 2);i++){
m_CurrentDir += pathParts[i] + "/";
}
if(m_CurrentDir.Length == 0){
m_CurrentDir = "/";
}
}
m_pSocket.SendLine("250 CDUP command successful.");
}
#endregion
#region method PWD
private void PWD()
{
/*
This command causes the name of the current working
directory to be returned in the reply.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
m_pSocket.SendLine("257 \"" + m_CurrentDir + "\" is current directory.");
}
#endregion
#region method RETR
private void RETR(string argsText)
{
/*
This command causes the server-DTP to transfer a copy of the
file, specified in the pathname, to the server- or user-DTP
at the other end of the data connection. The status and
contents of the file at the server site shall be unaffected.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
// ToDo: custom errors
//---- See if path accessible
Stream fileStream = null;
try{
string file = GetAndNormailizePath(argsText);
file = file.Substring(0,file.Length - 1);
fileStream = m_pServer.OnGetFile(this,file);
}
catch{
m_pSocket.SendLine("550 Access denied or directory dosen't exist !");
return;
}
Socket socket = GetDataConnection();
if(socket == null){
return;
}
try{
// string file = GetAndNormailizePath(argsText);
// file = file.Substring(0,file.Length - 1);
// using(Stream fileStream = m_pServer.OnGetFile(file)){
if(fileStream != null){
// ToDo: bandwidth limiting here
int readed = 1;
while(readed > 0){
byte[] data = new byte[10000];
readed = fileStream.Read(data,0,data.Length);
socket.Send(data);
}
}
// }
socket.Shutdown(SocketShutdown.Both);
socket.Close();
m_pSocket.SendLine("226 Transfer Complete.");
}
catch{
m_pSocket.SendLine("426 Connection closed; transfer aborted.");
}
fileStream.Close();
}
#endregion
#region method STOR
private void STOR(string argsText)
{
/*
This command causes the server-DTP to transfer a copy of the
file, specified in the pathname, to the server- or user-DTP
at the other end of the data connection. The status and
contents of the file at the server site shall be unaffected.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
// ToDo: custom errors
//---- See if path accessible
Stream fileStream = null;
try{
string file = GetAndNormailizePath(argsText);
file = file.Substring(0,file.Length - 1);
fileStream = m_pServer.OnStoreFile(this,file);
}
catch{
m_pSocket.SendLine("550 Access denied or directory dosen't exist !");
return;
}
Socket socket = GetDataConnection();
if(socket == null){
return;
}
try{
string file = GetAndNormailizePath(argsText);
file = file.Substring(0,file.Length - 1);
// using(Stream fileStream = m_pServer.OnStoreFile(file)){
if(fileStream != null){
// ToDo: bandwidth limiting here
int readed = 1;
while(readed > 0){
byte[] data = new byte[10000];
readed = socket.Receive(data);
fileStream.Write(data,0,readed);
}
}
// }
socket.Shutdown(SocketShutdown.Both);
socket.Close();
m_pSocket.SendLine("226 Transfer Complete.");
}
catch{ // ToDo: report right errors here. eg. DataConnection read time out, ... .
m_pSocket.SendLine("426 Connection closed; transfer aborted.");
}
fileStream.Close();
}
#endregion
#region method DELE
private void DELE(string argsText)
{
/*
This command causes the file specified in the pathname to be
deleted at the server site. If an extra level of protection
is desired (such as the query, "Do you really wish to
delete?"), it should be provided by the user-FTP process.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
string file = GetAndNormailizePath(argsText);
file = file.Substring(0,file.Length - 1);
m_pServer.OnDeleteFile(this,file);
m_pSocket.SendLine("250 file deleted.");
}
#endregion
#region method APPE
private void APPE(string argsText)
{
/*
This command causes the server-DTP to accept the data
transferred via the data connection and to store the data in
a file at the server site. If the file specified in the
pathname exists at the server site, then the data shall be
appended to that file; otherwise the file specified in the
pathname shall be created at the server site.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
//m_pServer.OnDeleteFile();
m_pSocket.SendLine("500 unimplemented");
}
#endregion
#region method RNFR
private void RNFR(string argsText)
{
/*
This command specifies the old pathname of the file which is
to be renamed. This command must be immediately followed by
a "rename to" command specifying the new file pathname.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
string dir = GetAndNormailizePath(argsText);
if(m_pServer.OnDirExists(this,dir) || m_pServer.OnFileExists(this,dir)){
m_pSocket.SendLine("350 Please specify destination name.");
m_RenameFrom = dir;
}
else{
m_pSocket.SendLine("550 File or directory doesn't exist.");
}
}
#endregion
#region method RNTO
private void RNTO(string argsText)
{
/*
This command specifies the new pathname of the file
specified in the immediately preceding "rename from"
command. Together the two commands cause a file to be
renamed.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
if(m_RenameFrom.Length == 0){
m_pSocket.SendLine("503 Bad sequence of commands.");
return;
}
string dir = GetAndNormailizePath(argsText);
if(m_pServer.OnRenameDirFile(this,m_RenameFrom,dir)){
m_pSocket.SendLine("250 Directory renamed.");
m_RenameFrom = "";
}
else{
m_pSocket.SendLine("550 Error renameing directory or file .");
}
}
#endregion
#region method RMD
private void RMD(string argsText)
{
/*
This command causes the directory specified in the pathname
to be removed as a directory (if the pathname is absolute)
or as a subdirectory of the current working directory (if
the pathname is relative).
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
string dir = GetAndNormailizePath(argsText);
if(m_pServer.OnDeleteDir(this,dir)){
m_pSocket.SendLine("250 \"" + dir + "\" directory deleted.");
}
else{
m_pSocket.SendLine("550 Directory deletion failed.");
}
}
#endregion
#region method MKD
private void MKD(string argsText)
{
/*
This command causes the directory specified in the pathname
to be created as a directory (if the pathname is absolute)
or as a subdirectory of the current working directory (if
the pathname is relative).
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
string dir = GetAndNormailizePath(argsText);
if(m_pServer.OnCreateDir(this,dir)){
m_pSocket.SendLine("257 \"" + dir + "\" directory created.");
}
else{
m_pSocket.SendLine("550 Directory creation failed.");
}
}
#endregion
#region method LIST
private void LIST(string argsText)
{
/*
This command causes a list to be sent from the server to the
passive DTP. If the pathname specifies a directory or other
group of files, the server should transfer a list of files
in the specified directory. If the pathname specifies a
file then the server should send current information on the
file. A null argument implies the user's current working or
default directory. The data transfer is over the data
connection in type ASCII or type EBCDIC. (The user must
ensure that the TYPE is appropriately ASCII or EBCDIC).
Since the information on a file may vary widely from system
to system, this information may be hard to use automatically
in a program, but may be quite useful to a human user.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
// ToDo: custom errors
//---- See if path accessible
FileSysEntry_EventArgs eArgs = m_pServer.OnGetDirInfo(this,GetAndNormailizePath(argsText));
if(!eArgs.Validated){
m_pSocket.SendLine("550 Access denied or directory dosen't exist !");
return;
}
DataSet ds = eArgs.DirInfo;
Socket socket = GetDataConnection();
if(socket == null){
return;
}
try{
// string dir = GetAndNormailizePath(argsText);
// DataSet ds = m_pServer.OnGetDirInfo(dir);
foreach(DataRow dr in ds.Tables["DirInfo"].Rows){
string name = dr["Name"].ToString();
string date = Convert.ToDateTime(dr["Date"]).ToString("MM-dd-yy hh:mmtt");
bool isDir = Convert.ToBoolean(dr["IsDirectory"]);
if(isDir){
socket.Send(System.Text.Encoding.Default.GetBytes(date + " <DIR> " + name + "\r\n"));
}
else{
socket.Send(System.Text.Encoding.Default.GetBytes(date + " " + dr["Size"].ToString() + " " + name + "\r\n"));
}
}
socket.Shutdown(SocketShutdown.Both);
socket.Close();
m_pSocket.SendLine("226 Transfer Complete.");
}
catch{
m_pSocket.SendLine("426 Connection closed; transfer aborted.");
}
}
#endregion
#region method NLST
private void NLST(string argsText)
{
/*
This command causes a directory listing to be sent from
server to user site. The pathname should specify a
directory or other system-specific file group descriptor; a
null argument implies the current directory. The server
will return a stream of names of files and no other
information. The data will be transferred in ASCII or
EBCDIC type over the data connection as valid pathname
strings separated by <CRLF> or <NL>. (Again the user must
ensure that the TYPE is correct.) This command is intended
to return information that can be used by a program to
further process the files automatically. For example, in
the implementation of a "multiple get" function.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
//---- See if path accessible
FileSysEntry_EventArgs eArgs = m_pServer.OnGetDirInfo(this,GetAndNormailizePath(argsText));
if(!eArgs.Validated){
m_pSocket.SendLine("550 Access denied or directory dosen't exist !");
return;
}
DataSet ds = eArgs.DirInfo;
Socket socket = GetDataConnection();
if(socket == null){
return;
}
try{
// string dir = GetAndNormailizePath(argsText);
// DataSet ds = m_pServer.OnGetDirInfo(dir);
foreach(DataRow dr in ds.Tables["DirInfo"].Rows){
socket.Send(System.Text.Encoding.Default.GetBytes(dr["Name"].ToString() + "\r\n"));
}
socket.Send(System.Text.Encoding.Default.GetBytes("aaa\r\n"));
socket.Shutdown(SocketShutdown.Both);
socket.Close();
m_pSocket.SendLine("226 Transfer Complete.");
}
catch{
m_pSocket.SendLine("426 Connection closed; transfer aborted.");
}
}
#endregion
#region method TYPE
private void TYPE(string argsText)
{
/*
The argument specifies the representation type as described
in the Section on Data Representation and Storage. Several
types take a second parameter. The first parameter is
denoted by a single Telnet character, as is the second
Format parameter for ASCII and EBCDIC; the second parameter
for local byte is a decimal integer to indicate Bytesize.
The parameters are separated by a <SP> (Space, ASCII code
32).
The following codes are assigned for type:
\ /
A - ASCII | | N - Non-print
|-><-| T - Telnet format effectors
E - EBCDIC| | C - Carriage Control (ASA)
/ \
I - Image
L <byte size> - Local byte Byte size
The default representation type is ASCII Non-print. If the
Format parameter is changed, and later just the first
argument is changed, Format then returns to the Non-print
default.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
if(argsText.Trim().ToUpper() == "A" || argsText.Trim().ToUpper() == "I"){
m_pSocket.SendLine("200 Type is set to " + argsText + ".");
}
else{
m_pSocket.SendLine("500 Invalid type " + argsText + ".");
}
}
#endregion
#region method PORT
private void PORT(string argsText)
{
/*
The argument is a HOST-PORT specification for the data port
to be used in data connection. There are defaults for both
the user and server data ports, and under normal
circumstances this command and its reply are not needed. If
this command is used, the argument is the concatenation of a
32-bit internet host address and a 16-bit TCP port address.
This address information is broken into 8-bit fields and the
value of each field is transmitted as a decimal number (in
character string representation). The fields are separated
by commas. A port command would be:
PORT h1,h2,h3,h4,p1,p2
where h1 is the high order 8 bits of the internet host
address.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
string[] parts = argsText.Split(',');
if(parts.Length != 6){
m_pSocket.SendLine("550 Invalid arguments.");
return;
}
string ip = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3];
int port = (Convert.ToInt32(parts[4]) << 8) | Convert.ToInt32(parts[5]);
m_pDataConEndPoint = new IPEndPoint(System.Net.Dns.GetHostByAddress(ip).AddressList[0],port);
m_pSocket.SendLine("200 PORT Command successful.");
}
#endregion
#region method PASV
private void PASV(string argsText)
{
/*
This command requests the server-DTP to "listen" on a data
port (which is not its default data port) and to wait for a
connection rather than initiate one upon receipt of a
transfer command. The response to this command includes the
host and port address this server is listening on.
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
//--- Find free port -------------------------------//
int port = 6000;
while(true){
try{
m_pPassiveListener = new TcpListener(IPAddress.Any,port);
m_pPassiveListener.Start();
// If we reach here then port is free
break;
}
catch{
}
port++;
}
//--------------------------------------------------//
// Notify client on what IP and port server is listening client to connect.
// PORT h1,h2,h3,h4,p1,p2
string ip = m_pSocket.LocalEndPoint.ToString();
ip = ip.Substring(0,ip.IndexOf(":"));
ip = ip.Replace(".",",");
ip += "," + (port >> 8) + "," + (port & 255);
m_pSocket.SendLine("227 Entering Passive Mode (" + ip + ").");
m_PassiveMode = true;
}
#endregion
#region method SYST
private void SYST()
{
/*
This command is used to find out the type of operating
system at the server. The reply shall have as its first
word one of the system names listed in the current version
of the Assigned Numbers document [4].
*/
if(!m_Authenticated){
m_pSocket.SendLine("530 Please authenticate firtst !");
return;
}
m_pSocket.SendLine("215 Windows_NT");
}
#endregion
#region method NOOP
private void NOOP()
{
/*
This command does not affect any parameters or previously
entered commands. It specifies no action other than that the
server send an OK reply.
*/
m_pSocket.SendLine("200 OK");
}
#endregion
#region method QUIT
private void QUIT()
{
/*
This command terminates a USER and if file transfer is not
in progress, the server closes the control connection. If
file transfer is in progress, the connection will remain
open for result response and the server will then close it.
If the user-process is transferring files for several USERs
but does not wish to close and then reopen connections for
each, then the REIN command should be used instead of QUIT.
An unexpected close on the control connection will cause the
server to take the effective action of an abort (ABOR) and a
logout (QUIT).
*/
m_pSocket.SendLine("221 FTP server signing off");
}
#endregion
#region method GetAndNormailizePath
private string GetAndNormailizePath(string path)
{
// If conatins \, replace with /
string dir = path.Replace("\\","/");
// If doesn't end with /, append it
if(!dir.EndsWith("/")){
dir += "/";
}
// Current path + path wanted if path not starting /
if(!path.StartsWith("/")){
dir = m_CurrentDir + dir;
}
//--- Normalize path, eg. /ivx/../test must be /test -----//
ArrayList pathParts = new ArrayList();
string[] p = dir.Split('/');
pathParts.AddRange(p);
for(int i=0;i<pathParts.Count;i++){
if(pathParts[i].ToString() == ".."){
// Don't let go over root path, eg. /../ - there wanted directory upper root.
// Just skip this movement.
if(i > 0){
pathParts.RemoveAt(i - 1);
i--;
}
pathParts.RemoveAt(i);
i--;
}
}
dir = dir.Replace("//","/");
return dir;
}
#endregion
#region method GetDataConnection
private Socket GetDataConnection()
{
Socket socket = null;
try{
if(m_PassiveMode){
//--- Wait ftp client connection ---------------------------//
long startTime = DateTime.Now.Ticks;
// Wait ftp server to connect
while(!m_pPassiveListener.Pending()){
System.Threading.Thread.Sleep(50);
// Time out after 30 seconds
if((DateTime.Now.Ticks - startTime) / 10000 > 20000){
throw new Exception("Ftp server didn't respond !");
}
}
//-----------------------------------------------------------//
socket = m_pPassiveListener.AcceptSocket();
m_pSocket.SendLine("125 Data connection open, Transfer starting.");
}
else{
m_pSocket.SendLine("150 Opening data connection.");
socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
socket.Connect(m_pDataConEndPoint);
}
}
catch{
m_pSocket.SendLine("425 Can't open data connection.");
return null;
}
m_PassiveMode = false;
return socket;
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets session ID.
/// </summary>
public string SessionID
{
get{ return m_SessionID; }
}
/// <summary>
/// Gets session start time.
/// </summary>
public DateTime SessionStartTime
{
get{ return m_SessionStartTime; }
}
/// <summary>
/// Gets last data activity time.
/// </summary>
public DateTime SessionLastDataTime
{
get{ return m_LastDataTime; }
}
/// <summary>
/// Gets loggded in user name (session owner).
/// </summary>
public string UserName
{
get{ return m_UserName; }
}
/// <summary>
/// Gets EndPoint which accepted conection.
/// </summary>
public IPEndPoint LocalEndPoint
{
get{ return (IPEndPoint)m_pSocket.LocalEndPoint; }
}
/// <summary>
/// Gets connected Host(client) EndPoint.
/// </summary>
public IPEndPoint RemoteEndPoint
{
get{ return (IPEndPoint)m_pSocket.RemoteEndPoint; }
}
/// <summary>
/// Gets if sessions is in passive mode.
/// </summary>
public bool PassiveMode
{
get{ return m_PassiveMode; }
}
/// <summary>
/// Gets or sets custom user data.
/// </summary>
public object Tag
{
get{ return m_Tag; }
set{ m_Tag = value; }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net.Sockets
{
// TODO:
// - Plumb status through async APIs to avoid callbacks on synchronous completion
// - NOTE: this will require refactoring in the *Async APIs to accommodate the lack
// of completion posting
// - Add support for unregistering + reregistering for events
// - This will require a new state for each queue, unregistred, to track whether or
// not the queue is currently registered to receive events
// - Audit Close()-related code for the possibility of file descriptor recycling issues
// - It might make sense to change _closeLock to a ReaderWriterLockSlim that is
// acquired for read by all public methods before attempting a completion and
// acquired for write by Close() and HandlEvents()
//
// NOTE: the publicly-exposed asynchronous methods should match the behavior of
// Winsock overlapped sockets as closely as possible. Especially important are
// completion semantics, as the consuming code relies on the Winsock behavior.
//
// Winsock queues a completion callback for an overlapped operation in two cases:
// 1. the operation successfully completes synchronously, or
// 2. the operation completes asynchronously, successfully or otherwise.
// In other words, a completion callback is queued iff an operation does not
// fail synchronously. The asynchronous methods below (e.g. ReceiveAsync) may
// fail synchronously for either of the following reasons:
// 1. an underlying system call fails synchronously, or
// 2. an underlying system call returns EAGAIN, but the socket is closed before
// the method is able to enqueue its corresponding operation.
// In the first case, the async method should return the SocketError that
// corresponds to the native error code; in the second, the method should return
// SocketError.OperationAborted (which matches what Winsock would return in this
// case). The publicly-exposed synchronous methods may also encounter the second
// case. In this situation these methods should return SocketError.Interrupted
// (which again matches Winsock).
internal sealed class SocketAsyncContext
{
private abstract class AsyncOperation
{
private enum State
{
Waiting = 0,
Running = 1,
Complete = 2,
Cancelled = 3
}
private int _state; // Actually AsyncOperation.State.
#if DEBUG
private int _callbackQueued; // When non-zero, the callback has been queued.
#endif
public AsyncOperation Next;
protected object CallbackOrEvent;
public SocketError ErrorCode;
public byte[] SocketAddress;
public int SocketAddressLen;
public ManualResetEventSlim Event
{
private get { return (ManualResetEventSlim)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
public AsyncOperation()
{
_state = (int)State.Waiting;
Next = this;
}
public void QueueCompletionCallback()
{
Debug.Assert(!(CallbackOrEvent is ManualResetEventSlim), $"Unexpected CallbackOrEvent: {CallbackOrEvent}");
Debug.Assert(_state != (int)State.Cancelled, $"Unexpected _state: {_state}");
#if DEBUG
Debug.Assert(Interlocked.CompareExchange(ref _callbackQueued, 1, 0) == 0, $"Unexpected _callbackQueued: {_callbackQueued}");
#endif
ThreadPool.QueueUserWorkItem(o => ((AsyncOperation)o).InvokeCallback(), this);
}
public bool TryComplete(SocketAsyncContext context)
{
Debug.Assert(_state == (int)State.Waiting, $"Unexpected _state: {_state}");
return DoTryComplete(context);
}
public bool TryCompleteAsync(SocketAsyncContext context)
{
return TryCompleteOrAbortAsync(context, abort: false);
}
public void AbortAsync()
{
bool completed = TryCompleteOrAbortAsync(null, abort: true);
Debug.Assert(completed, $"Expected TryCompleteOrAbortAsync to return true");
}
private bool TryCompleteOrAbortAsync(SocketAsyncContext context, bool abort)
{
Debug.Assert(context != null || abort, $"Unexpected values: context={context}, abort={abort}");
State oldState = (State)Interlocked.CompareExchange(ref _state, (int)State.Running, (int)State.Waiting);
if (oldState == State.Cancelled)
{
// This operation has been cancelled. The canceller is responsible for
// correctly updating any state that would have been handled by
// AsyncOperation.Abort.
return true;
}
Debug.Assert(oldState != State.Complete && oldState != State.Running, $"Unexpected oldState: {oldState}");
bool completed;
if (abort)
{
Abort();
ErrorCode = SocketError.OperationAborted;
completed = true;
}
else
{
completed = DoTryComplete(context);
}
if (completed)
{
var @event = CallbackOrEvent as ManualResetEventSlim;
if (@event != null)
{
@event.Set();
}
else
{
QueueCompletionCallback();
}
Volatile.Write(ref _state, (int)State.Complete);
return true;
}
Volatile.Write(ref _state, (int)State.Waiting);
return false;
}
public bool Wait(int timeout)
{
if (Event.Wait(timeout))
{
return true;
}
var spinWait = new SpinWait();
for (;;)
{
int state = Interlocked.CompareExchange(ref _state, (int)State.Cancelled, (int)State.Waiting);
switch ((State)state)
{
case State.Running:
// A completion attempt is in progress. Keep busy-waiting.
spinWait.SpinOnce();
break;
case State.Complete:
// A completion attempt succeeded. Consider this operation as having completed within the timeout.
return true;
case State.Waiting:
// This operation was successfully cancelled.
return false;
}
}
}
protected abstract void Abort();
protected abstract bool DoTryComplete(SocketAsyncContext context);
protected abstract void InvokeCallback();
}
private abstract class TransferOperation : AsyncOperation
{
public byte[] Buffer;
public int Offset;
public int Count;
public SocketFlags Flags;
public int BytesTransferred;
public SocketFlags ReceivedFlags;
protected sealed override void Abort() { }
}
private abstract class SendReceiveOperation : TransferOperation
{
public IList<ArraySegment<byte>> Buffers;
public int BufferIndex;
public Action<int, byte[], int, SocketFlags, SocketError> Callback
{
private get { return (Action<int, byte[], int, SocketFlags, SocketError>)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
protected sealed override void InvokeCallback()
{
Callback(BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, ErrorCode);
}
}
private sealed class SendOperation : SendReceiveOperation
{
protected override bool DoTryComplete(SocketAsyncContext context)
{
return SocketPal.TryCompleteSendTo(context._socket, Buffer, Buffers, ref BufferIndex, ref Offset, ref Count, Flags, SocketAddress, SocketAddressLen, ref BytesTransferred, out ErrorCode);
}
}
private sealed class ReceiveOperation : SendReceiveOperation
{
protected override bool DoTryComplete(SocketAsyncContext context)
{
return SocketPal.TryCompleteReceiveFrom(context._socket, Buffer, Buffers, Offset, Count, Flags, SocketAddress, ref SocketAddressLen, out BytesTransferred, out ReceivedFlags, out ErrorCode);
}
}
private sealed class ReceiveMessageFromOperation : TransferOperation
{
public bool IsIPv4;
public bool IsIPv6;
public IPPacketInformation IPPacketInformation;
public Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError> Callback
{
private get { return (Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError>)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
protected override bool DoTryComplete(SocketAsyncContext context)
{
return SocketPal.TryCompleteReceiveMessageFrom(context._socket, Buffer, Offset, Count, Flags, SocketAddress, ref SocketAddressLen, IsIPv4, IsIPv6, out BytesTransferred, out ReceivedFlags, out IPPacketInformation, out ErrorCode);
}
protected override void InvokeCallback()
{
Callback(BytesTransferred, SocketAddress, SocketAddressLen, ReceivedFlags, IPPacketInformation, ErrorCode);
}
}
private abstract class AcceptOrConnectOperation : AsyncOperation
{
}
private sealed class AcceptOperation : AcceptOrConnectOperation
{
public int AcceptedFileDescriptor;
public Action<int, byte[], int, SocketError> Callback
{
private get { return (Action<int, byte[], int, SocketError>)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
protected override void Abort()
{
AcceptedFileDescriptor = -1;
}
protected override bool DoTryComplete(SocketAsyncContext context)
{
bool completed = SocketPal.TryCompleteAccept(context._socket, SocketAddress, ref SocketAddressLen, out AcceptedFileDescriptor, out ErrorCode);
Debug.Assert(ErrorCode == SocketError.Success || AcceptedFileDescriptor == -1, $"Unexpected values: ErrorCode={ErrorCode}, AcceptedFileDescriptor={AcceptedFileDescriptor}");
return completed;
}
protected override void InvokeCallback()
{
Callback(AcceptedFileDescriptor, SocketAddress, SocketAddressLen, ErrorCode);
}
}
private sealed class ConnectOperation : AcceptOrConnectOperation
{
public Action<SocketError> Callback
{
private get { return (Action<SocketError>)CallbackOrEvent; }
set { CallbackOrEvent = value; }
}
protected override void Abort() { }
protected override bool DoTryComplete(SocketAsyncContext context)
{
bool result = SocketPal.TryCompleteConnect(context._socket, SocketAddressLen, out ErrorCode);
context.RegisterConnectResult(ErrorCode);
return result;
}
protected override void InvokeCallback()
{
Callback(ErrorCode);
}
}
private enum QueueState
{
Clear = 0,
Set = 1,
Stopped = 2,
}
private struct OperationQueue<TOperation>
where TOperation : AsyncOperation
{
private AsyncOperation _tail;
public QueueState State { get; set; }
public bool IsStopped { get { return State == QueueState.Stopped; } }
public bool IsEmpty { get { return _tail == null; } }
public void Enqueue(TOperation operation)
{
Debug.Assert(!IsStopped, "Expected !IsStopped");
Debug.Assert(operation.Next == operation, "Expected operation.Next == operation");
if (!IsEmpty)
{
operation.Next = _tail.Next;
_tail.Next = operation;
}
_tail = operation;
}
private bool TryDequeue(out TOperation operation)
{
if (_tail == null)
{
operation = null;
return false;
}
AsyncOperation head = _tail.Next;
if (head == _tail)
{
_tail = null;
}
else
{
_tail.Next = head.Next;
}
head.Next = null;
operation = (TOperation)head;
return true;
}
private void Requeue(TOperation operation)
{
// Insert at the head of the queue
Debug.Assert(!IsStopped, "Expected !IsStopped");
Debug.Assert(operation.Next == null, "Operation already in queue");
if (IsEmpty)
{
operation.Next = operation;
_tail = operation;
}
else
{
operation.Next = _tail.Next;
_tail.Next = operation;
}
}
public OperationQueue<TOperation> Stop()
{
OperationQueue<TOperation> result = this;
_tail = null;
State = QueueState.Stopped;
return result;
}
public void Complete(SocketAsyncContext context)
{
if (IsStopped)
return;
State = QueueState.Set;
TOperation op;
while (TryDequeue(out op))
{
if (!op.TryCompleteAsync(context))
{
Requeue(op);
return;
}
}
}
public void StopAndAbort()
{
OperationQueue<TOperation> queue = Stop();
TOperation op;
while (queue.TryDequeue(out op))
{
op.AbortAsync();
}
}
public bool AllOfType<TCandidate>() where TCandidate : TOperation
{
bool tailIsCandidateType = _tail is TCandidate;
#if DEBUG
// We assume that all items are of the specified type, or all are not. Check this invariant.
if (_tail != null)
{
AsyncOperation op = _tail;
do
{
Debug.Assert((op is TCandidate) == tailIsCandidateType, $"Unexpected values: op={op}, tailIsCandidateType={tailIsCandidateType}");
op = op.Next;
}
while (op != _tail);
}
#endif
return tailIsCandidateType;
}
}
private SafeCloseSocket _socket;
private OperationQueue<TransferOperation> _receiveQueue;
private OperationQueue<SendOperation> _sendQueue;
private OperationQueue<AcceptOrConnectOperation> _acceptOrConnectQueue;
private SocketAsyncEngine.Token _asyncEngineToken;
private Interop.Sys.SocketEvents _registeredEvents;
private bool _nonBlockingSet;
private bool _connectFailed;
private object _queueLock = new object();
public SocketAsyncContext(SafeCloseSocket socket)
{
_socket = socket;
}
private void Register(Interop.Sys.SocketEvents events)
{
Debug.Assert(Monitor.IsEntered(_queueLock), "Expected _queueLock to be held");
Debug.Assert((_registeredEvents & events) == Interop.Sys.SocketEvents.None, $"Unexpected values: _registeredEvents={_registeredEvents}, events={events}");
if (!_asyncEngineToken.WasAllocated)
{
_asyncEngineToken = new SocketAsyncEngine.Token(this);
}
events |= _registeredEvents;
Interop.Error errorCode;
if (!_asyncEngineToken.TryRegister(_socket, _registeredEvents, events, out errorCode))
{
// TODO: throw an appropiate exception
throw new Exception(string.Format("SocketAsyncContext.Register: {0}", errorCode));
}
_registeredEvents = events;
}
public void Close()
{
lock (_queueLock)
{
// Drain queues
_acceptOrConnectQueue.StopAndAbort();
_sendQueue.StopAndAbort();
_receiveQueue.StopAndAbort();
// Freeing the token will prevent any future event delivery. This socket will be unregistered
// from the event port automatically by the OS when it's closed.
_asyncEngineToken.Free();
}
}
public void SetNonBlocking()
{
//
// Our sockets may start as blocking, and later transition to non-blocking, either because the user
// explicitly requested non-blocking mode, or because we need non-blocking mode to support async
// operations. We never transition back to blocking mode, to avoid problems synchronizing that
// transition with the async infrastructure.
//
// Note that there's no synchronization here, so we may set the non-blocking option multiple times
// in a race. This should be fine.
//
if (!_nonBlockingSet)
{
if (Interop.Sys.Fcntl.SetIsNonBlocking(_socket, 1) != 0)
{
throw new SocketException((int)SocketPal.GetSocketErrorForErrorCode(Interop.Sys.GetLastError()));
}
_nonBlockingSet = true;
}
}
public void CheckForPriorConnectFailure()
{
if (_connectFailed)
{
throw new PlatformNotSupportedException(SR.net_sockets_connect_multiconnect_notsupported);
}
}
public void RegisterConnectResult(SocketError error)
{
if (error != SocketError.Success && error != SocketError.WouldBlock)
{
_connectFailed = true;
}
}
private bool TryBeginOperation<TOperation>(ref OperationQueue<TOperation> queue, TOperation operation, Interop.Sys.SocketEvents events, bool maintainOrder, out bool isStopped)
where TOperation : AsyncOperation
{
lock (_queueLock)
{
switch (queue.State)
{
case QueueState.Stopped:
isStopped = true;
return false;
case QueueState.Clear:
break;
case QueueState.Set:
if (queue.IsEmpty || !maintainOrder)
{
isStopped = false;
queue.State = QueueState.Clear;
return false;
}
break;
}
if ((_registeredEvents & events) == Interop.Sys.SocketEvents.None)
{
Register(events);
}
queue.Enqueue(operation);
isStopped = false;
return true;
}
}
public SocketError Accept(byte[] socketAddress, ref int socketAddressLen, int timeout, out int acceptedFd)
{
Debug.Assert(socketAddress != null, "Expected non-null socketAddress");
Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}");
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
SocketError errorCode;
if (SocketPal.TryCompleteAccept(_socket, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode))
{
Debug.Assert(errorCode == SocketError.Success || acceptedFd == -1, $"Unexpected values: errorCode={errorCode}, acceptedFd={acceptedFd}");
return errorCode;
}
using (var @event = new ManualResetEventSlim(false, 0))
{
var operation = new AcceptOperation {
Event = @event,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen
};
bool isStopped;
while (!TryBeginOperation(ref _acceptOrConnectQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: false, isStopped: out isStopped))
{
if (isStopped)
{
acceptedFd = -1;
return SocketError.Interrupted;
}
if (operation.TryComplete(this))
{
socketAddressLen = operation.SocketAddressLen;
acceptedFd = operation.AcceptedFileDescriptor;
return operation.ErrorCode;
}
}
if (!operation.Wait(timeout))
{
acceptedFd = -1;
return SocketError.TimedOut;
}
socketAddressLen = operation.SocketAddressLen;
acceptedFd = operation.AcceptedFileDescriptor;
return operation.ErrorCode;
}
}
public SocketError AcceptAsync(byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketError> callback)
{
Debug.Assert(socketAddress != null, "Expected non-null socketAddress");
Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}");
Debug.Assert(callback != null, "Expected non-null callback");
SetNonBlocking();
int acceptedFd;
SocketError errorCode;
if (SocketPal.TryCompleteAccept(_socket, socketAddress, ref socketAddressLen, out acceptedFd, out errorCode))
{
Debug.Assert(errorCode == SocketError.Success || acceptedFd == -1, $"Unexpected values: errorCode={errorCode}, acceptedFd={acceptedFd}");
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketError>, int, byte[], int>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, SocketError.Success);
}, Tuple.Create(callback, acceptedFd, socketAddress, socketAddressLen));
}
return errorCode;
}
var operation = new AcceptOperation {
Callback = callback,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen
};
bool isStopped;
while (!TryBeginOperation(ref _acceptOrConnectQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: false, isStopped: out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(this))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError Connect(byte[] socketAddress, int socketAddressLen, int timeout)
{
Debug.Assert(socketAddress != null, "Expected non-null socketAddress");
Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}");
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
CheckForPriorConnectFailure();
SocketError errorCode;
if (SocketPal.TryStartConnect(_socket, socketAddress, socketAddressLen, out errorCode))
{
RegisterConnectResult(errorCode);
return errorCode;
}
using (var @event = new ManualResetEventSlim(false, 0))
{
var operation = new ConnectOperation {
Event = @event,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen
};
bool isStopped;
while (!TryBeginOperation(ref _acceptOrConnectQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: false, isStopped: out isStopped))
{
if (isStopped)
{
return SocketError.Interrupted;
}
if (operation.TryComplete(this))
{
return operation.ErrorCode;
}
}
return operation.Wait(timeout) ? operation.ErrorCode : SocketError.TimedOut;
}
}
public SocketError ConnectAsync(byte[] socketAddress, int socketAddressLen, Action<SocketError> callback)
{
Debug.Assert(socketAddress != null, "Expected non-null socketAddress");
Debug.Assert(socketAddressLen > 0, $"Unexpected socketAddressLen: {socketAddressLen}");
Debug.Assert(callback != null, "Expected non-null callback");
CheckForPriorConnectFailure();
SetNonBlocking();
SocketError errorCode;
if (SocketPal.TryStartConnect(_socket, socketAddress, socketAddressLen, out errorCode))
{
RegisterConnectResult(errorCode);
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(arg => ((Action<SocketError>)arg)(SocketError.Success), callback);
}
return errorCode;
}
var operation = new ConnectOperation {
Callback = callback,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen
};
bool isStopped;
while (!TryBeginOperation(ref _acceptOrConnectQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: false, isStopped: out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(this))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
public SocketError Receive(byte[] buffer, int offset, int count, ref SocketFlags flags, int timeout, out int bytesReceived)
{
int socketAddressLen = 0;
return ReceiveFrom(buffer, offset, count, ref flags, null, ref socketAddressLen, timeout, out bytesReceived);
}
public SocketError ReceiveAsync(byte[] buffer, int offset, int count, SocketFlags flags, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
return ReceiveFromAsync(buffer, offset, count, flags, null, 0, callback);
}
public SocketError ReceiveFrom(byte[] buffer, int offset, int count, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, int timeout, out int bytesReceived)
{
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
ManualResetEventSlim @event = null;
try
{
ReceiveOperation operation;
lock (_queueLock)
{
SocketFlags receivedFlags;
SocketError errorCode;
if (_receiveQueue.IsEmpty &&
SocketPal.TryCompleteReceiveFrom(_socket, buffer, offset, count, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode))
{
flags = receivedFlags;
return errorCode;
}
@event = new ManualResetEventSlim(false, 0);
operation = new ReceiveOperation
{
Event = @event,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped))
{
if (isStopped)
{
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return SocketError.Interrupted;
}
if (operation.TryComplete(this))
{
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return operation.ErrorCode;
}
}
}
bool signaled = operation.Wait(timeout);
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
finally
{
if (@event != null) @event.Dispose();
}
}
public SocketError ReceiveFromAsync(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
SetNonBlocking();
lock (_queueLock)
{
int bytesReceived;
SocketFlags receivedFlags;
SocketError errorCode;
if (_receiveQueue.IsEmpty &&
SocketPal.TryCompleteReceiveFrom(_socket, buffer, offset, count, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketFlags, SocketError>, int, byte[], int, SocketFlags>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, tup.Item5, SocketError.Success);
}, Tuple.Create(callback, bytesReceived, socketAddress, socketAddressLen, receivedFlags));
}
return errorCode;
}
var operation = new ReceiveOperation
{
Callback = callback,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(this))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
}
public SocketError Receive(IList<ArraySegment<byte>> buffers, ref SocketFlags flags, int timeout, out int bytesReceived)
{
return ReceiveFrom(buffers, ref flags, null, 0, timeout, out bytesReceived);
}
public SocketError ReceiveAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
return ReceiveFromAsync(buffers, flags, null, 0, callback);
}
public SocketError ReceiveFrom(IList<ArraySegment<byte>> buffers, ref SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesReceived)
{
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
ManualResetEventSlim @event = null;
try
{
ReceiveOperation operation;
lock (_queueLock)
{
SocketFlags receivedFlags;
SocketError errorCode;
if (_receiveQueue.IsEmpty &&
SocketPal.TryCompleteReceiveFrom(_socket, buffers, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode))
{
flags = receivedFlags;
return errorCode;
}
@event = new ManualResetEventSlim(false, 0);
operation = new ReceiveOperation
{
Event = @event,
Buffers = buffers,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped))
{
if (isStopped)
{
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return SocketError.Interrupted;
}
if (operation.TryComplete(this))
{
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return operation.ErrorCode;
}
}
}
bool signaled = operation.Wait(timeout);
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
bytesReceived = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
finally
{
if (@event != null) @event.Dispose();
}
}
public SocketError ReceiveFromAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
SetNonBlocking();
ReceiveOperation operation;
lock (_queueLock)
{
int bytesReceived;
SocketFlags receivedFlags;
SocketError errorCode;
if (_receiveQueue.IsEmpty &&
SocketPal.TryCompleteReceiveFrom(_socket, buffers, flags, socketAddress, ref socketAddressLen, out bytesReceived, out receivedFlags, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketFlags, SocketError>, int, byte[], int, SocketFlags>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, tup.Item5, SocketError.Success);
}, Tuple.Create(callback, bytesReceived, socketAddress, socketAddressLen, receivedFlags));
}
return errorCode;
}
operation = new ReceiveOperation
{
Callback = callback,
Buffers = buffers,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(this))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
}
public SocketError ReceiveMessageFrom(byte[] buffer, int offset, int count, ref SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, int timeout, out IPPacketInformation ipPacketInformation, out int bytesReceived)
{
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
ManualResetEventSlim @event = null;
try
{
ReceiveMessageFromOperation operation;
lock (_queueLock)
{
SocketFlags receivedFlags;
SocketError errorCode;
if (_receiveQueue.IsEmpty &&
SocketPal.TryCompleteReceiveMessageFrom(_socket, buffer, offset, count, flags, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, out errorCode))
{
flags = receivedFlags;
return errorCode;
}
@event = new ManualResetEventSlim(false, 0);
operation = new ReceiveMessageFromOperation
{
Event = @event,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
IsIPv4 = isIPv4,
IsIPv6 = isIPv6,
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped))
{
if (isStopped)
{
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
ipPacketInformation = operation.IPPacketInformation;
bytesReceived = operation.BytesTransferred;
return SocketError.Interrupted;
}
if (operation.TryComplete(this))
{
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
ipPacketInformation = operation.IPPacketInformation;
bytesReceived = operation.BytesTransferred;
return operation.ErrorCode;
}
}
}
bool signaled = operation.Wait(timeout);
socketAddressLen = operation.SocketAddressLen;
flags = operation.ReceivedFlags;
ipPacketInformation = operation.IPPacketInformation;
bytesReceived = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
finally
{
if (@event != null) @event.Dispose();
}
}
public SocketError ReceiveMessageFromAsync(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, bool isIPv4, bool isIPv6, Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError> callback)
{
SetNonBlocking();
lock (_queueLock)
{
int bytesReceived;
SocketFlags receivedFlags;
IPPacketInformation ipPacketInformation;
SocketError errorCode;
if (_receiveQueue.IsEmpty &&
SocketPal.TryCompleteReceiveMessageFrom(_socket, buffer, offset, count, flags, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out bytesReceived, out receivedFlags, out ipPacketInformation, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketFlags, IPPacketInformation, SocketError>, int, byte[], int, SocketFlags, IPPacketInformation>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, tup.Item5, tup.Item6, SocketError.Success);
}, Tuple.Create(callback, bytesReceived, socketAddress, socketAddressLen, receivedFlags, ipPacketInformation));
}
return errorCode;
}
var operation = new ReceiveMessageFromOperation
{
Callback = callback,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
IsIPv4 = isIPv4,
IsIPv6 = isIPv6,
};
bool isStopped;
while (!TryBeginOperation(ref _receiveQueue, operation, Interop.Sys.SocketEvents.Read, maintainOrder: true, isStopped: out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(this))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
}
public SocketError Send(byte[] buffer, int offset, int count, SocketFlags flags, int timeout, out int bytesSent)
{
return SendTo(buffer, offset, count, flags, null, 0, timeout, out bytesSent);
}
public SocketError SendAsync(byte[] buffer, int offset, int count, SocketFlags flags, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
return SendToAsync(buffer, offset, count, flags, null, 0, callback);
}
public SocketError SendTo(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent)
{
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
ManualResetEventSlim @event = null;
try
{
SendOperation operation;
lock (_queueLock)
{
bytesSent = 0;
SocketError errorCode;
if (_sendQueue.IsEmpty &&
SocketPal.TryCompleteSendTo(_socket, buffer, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode))
{
return errorCode;
}
@event = new ManualResetEventSlim(false, 0);
operation = new SendOperation
{
Event = @event,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesSent
};
bool isStopped;
while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped))
{
if (isStopped)
{
bytesSent = operation.BytesTransferred;
return SocketError.Interrupted;
}
if (operation.TryComplete(this))
{
bytesSent = operation.BytesTransferred;
return operation.ErrorCode;
}
}
}
bool signaled = operation.Wait(timeout);
bytesSent = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
finally
{
if (@event != null) @event.Dispose();
}
}
public SocketError SendToAsync(byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
SetNonBlocking();
lock (_queueLock)
{
int bytesSent = 0;
SocketError errorCode;
if (_sendQueue.IsEmpty &&
SocketPal.TryCompleteSendTo(_socket, buffer, ref offset, ref count, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketFlags, SocketError>, int, byte[], int>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, 0, SocketError.Success);
}, Tuple.Create(callback, bytesSent, socketAddress, socketAddressLen));
}
return errorCode;
}
var operation = new SendOperation
{
Callback = callback,
Buffer = buffer,
Offset = offset,
Count = count,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesSent
};
bool isStopped;
while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(this))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
}
public SocketError Send(IList<ArraySegment<byte>> buffers, SocketFlags flags, int timeout, out int bytesSent)
{
return SendTo(buffers, flags, null, 0, timeout, out bytesSent);
}
public SocketError SendAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
return SendToAsync(buffers, flags, null, 0, callback);
}
public SocketError SendTo(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, int socketAddressLen, int timeout, out int bytesSent)
{
Debug.Assert(timeout == -1 || timeout > 0, $"Unexpected timeout: {timeout}");
ManualResetEventSlim @event = null;
try
{
SendOperation operation;
lock (_queueLock)
{
bytesSent = 0;
int bufferIndex = 0;
int offset = 0;
SocketError errorCode;
if (_sendQueue.IsEmpty &&
SocketPal.TryCompleteSendTo(_socket, buffers, ref bufferIndex, ref offset, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode))
{
return errorCode;
}
@event = new ManualResetEventSlim(false, 0);
operation = new SendOperation
{
Event = @event,
Buffers = buffers,
BufferIndex = bufferIndex,
Offset = offset,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
BytesTransferred = bytesSent
};
bool isStopped;
while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped))
{
if (isStopped)
{
bytesSent = operation.BytesTransferred;
return SocketError.Interrupted;
}
if (operation.TryComplete(this))
{
bytesSent = operation.BytesTransferred;
return operation.ErrorCode;
}
}
}
bool signaled = operation.Wait(timeout);
bytesSent = operation.BytesTransferred;
return signaled ? operation.ErrorCode : SocketError.TimedOut;
}
finally
{
if (@event != null) @event.Dispose();
}
}
public SocketError SendToAsync(IList<ArraySegment<byte>> buffers, SocketFlags flags, byte[] socketAddress, int socketAddressLen, Action<int, byte[], int, SocketFlags, SocketError> callback)
{
SetNonBlocking();
lock (_queueLock)
{
int bufferIndex = 0;
int offset = 0;
int bytesSent = 0;
SocketError errorCode;
if (_sendQueue.IsEmpty &&
SocketPal.TryCompleteSendTo(_socket, buffers, ref bufferIndex, ref offset, flags, socketAddress, socketAddressLen, ref bytesSent, out errorCode))
{
if (errorCode == SocketError.Success)
{
ThreadPool.QueueUserWorkItem(args =>
{
var tup = (Tuple<Action<int, byte[], int, SocketFlags, SocketError>, int, byte[], int>)args;
tup.Item1(tup.Item2, tup.Item3, tup.Item4, SocketFlags.None, SocketError.Success);
}, Tuple.Create(callback, bytesSent, socketAddress, socketAddressLen));
}
return errorCode;
}
var operation = new SendOperation
{
Callback = callback,
Buffers = buffers,
BufferIndex = bufferIndex,
Offset = offset,
Flags = flags,
SocketAddress = socketAddress,
SocketAddressLen = socketAddressLen,
};
bool isStopped;
while (!TryBeginOperation(ref _sendQueue, operation, Interop.Sys.SocketEvents.Write, maintainOrder: true, isStopped: out isStopped))
{
if (isStopped)
{
return SocketError.OperationAborted;
}
if (operation.TryComplete(this))
{
operation.QueueCompletionCallback();
break;
}
}
return SocketError.IOPending;
}
}
public unsafe void HandleEvents(Interop.Sys.SocketEvents events)
{
lock (_queueLock)
{
if ((events & Interop.Sys.SocketEvents.Error) != 0)
{
// Set the Read and Write flags as well; the processing for these events
// will pick up the error.
events |= Interop.Sys.SocketEvents.Read | Interop.Sys.SocketEvents.Write;
}
if ((events & Interop.Sys.SocketEvents.Read) != 0)
{
if (_acceptOrConnectQueue.AllOfType<AcceptOperation>())
{
_acceptOrConnectQueue.Complete(this);
}
_receiveQueue.Complete(this);
}
if ((events & Interop.Sys.SocketEvents.Write) != 0)
{
if (_acceptOrConnectQueue.AllOfType<ConnectOperation>())
{
_acceptOrConnectQueue.Complete(this);
}
_sendQueue.Complete(this);
}
}
}
}
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Management.ExpressRoute;
using Microsoft.WindowsAzure.Management.ExpressRoute.Models;
namespace Microsoft.WindowsAzure.Management.ExpressRoute
{
/// <summary>
/// The Express Route API provides programmatic access to the functionality
/// needed by the customer to set up Dedicated Circuits and Dedicated
/// Circuit Links. The Express Route Customer API is a REST API. All API
/// operations are performed over SSL and mutually authenticated using
/// X.509 v3 certificates. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
/// more information)
/// </summary>
public static partial class DedicatedCircuitPeeringRouteTableSummaryOperationsExtensions
{
/// <summary>
/// The Get DedicatedCircuitPeeringRouteTableSummary operation retrives
/// RouteTableSummary.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitPeeringRouteTableSummaryOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the circuit.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public or microsoft.
/// </param>
/// <param name='devicePath'>
/// Required. Whether the device is primary or secondary.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static ExpressRouteOperationResponse BeginGet(this IDedicatedCircuitPeeringRouteTableSummaryOperations operations, string serviceKey, BgpPeeringAccessType accessType, DevicePath devicePath)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDedicatedCircuitPeeringRouteTableSummaryOperations)s).BeginGetAsync(serviceKey, accessType, devicePath);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get DedicatedCircuitPeeringRouteTableSummary operation retrives
/// RouteTableSummary.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitPeeringRouteTableSummaryOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the circuit.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public or microsoft.
/// </param>
/// <param name='devicePath'>
/// Required. Whether the device is primary or secondary.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<ExpressRouteOperationResponse> BeginGetAsync(this IDedicatedCircuitPeeringRouteTableSummaryOperations operations, string serviceKey, BgpPeeringAccessType accessType, DevicePath devicePath)
{
return operations.BeginGetAsync(serviceKey, accessType, devicePath, CancellationToken.None);
}
/// <summary>
/// The Get DedicatedCircuitPeeringRouteTableSummary operation retrives
/// RouteTableSummary.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitPeeringRouteTableSummaryOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the circuit.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public or microsoft.
/// </param>
/// <param name='devicePath'>
/// Required. Whether the device is primary or secondary.
/// </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 static ExpressRouteOperationStatusResponse Get(this IDedicatedCircuitPeeringRouteTableSummaryOperations operations, string serviceKey, BgpPeeringAccessType accessType, DevicePath devicePath)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDedicatedCircuitPeeringRouteTableSummaryOperations)s).GetAsync(serviceKey, accessType, devicePath);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get DedicatedCircuitPeeringRouteTableSummary operation retrives
/// RouteTableSummary.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitPeeringRouteTableSummaryOperations.
/// </param>
/// <param name='serviceKey'>
/// Required. The service key representing the circuit.
/// </param>
/// <param name='accessType'>
/// Required. Whether the peering is private or public or microsoft.
/// </param>
/// <param name='devicePath'>
/// Required. Whether the device is primary or secondary.
/// </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 static Task<ExpressRouteOperationStatusResponse> GetAsync(this IDedicatedCircuitPeeringRouteTableSummaryOperations operations, string serviceKey, BgpPeeringAccessType accessType, DevicePath devicePath)
{
return operations.GetAsync(serviceKey, accessType, devicePath, CancellationToken.None);
}
/// <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='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitPeeringRouteTableSummaryOperations.
/// </param>
/// <param name='operationId'>
/// Required. The id of the operation.
/// </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 static ExpressRouteOperationStatusResponse GetOperationStatus(this IDedicatedCircuitPeeringRouteTableSummaryOperations operations, string operationId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDedicatedCircuitPeeringRouteTableSummaryOperations)s).GetOperationStatusAsync(operationId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <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='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.IDedicatedCircuitPeeringRouteTableSummaryOperations.
/// </param>
/// <param name='operationId'>
/// Required. The id of the operation.
/// </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 static Task<ExpressRouteOperationStatusResponse> GetOperationStatusAsync(this IDedicatedCircuitPeeringRouteTableSummaryOperations operations, string operationId)
{
return operations.GetOperationStatusAsync(operationId, CancellationToken.None);
}
}
}
| |
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 ConCantidadTurnosEspecialidad class.
/// </summary>
[Serializable]
public partial class ConCantidadTurnosEspecialidadCollection : ReadOnlyList<ConCantidadTurnosEspecialidad, ConCantidadTurnosEspecialidadCollection>
{
public ConCantidadTurnosEspecialidadCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the CON_CantidadTurnosEspecialidad view.
/// </summary>
[Serializable]
public partial class ConCantidadTurnosEspecialidad : ReadOnlyRecord<ConCantidadTurnosEspecialidad>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
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("CON_CantidadTurnosEspecialidad", TableType.View, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdAgenda = new TableSchema.TableColumn(schema);
colvarIdAgenda.ColumnName = "idAgenda";
colvarIdAgenda.DataType = DbType.Int32;
colvarIdAgenda.MaxLength = 0;
colvarIdAgenda.AutoIncrement = false;
colvarIdAgenda.IsNullable = false;
colvarIdAgenda.IsPrimaryKey = false;
colvarIdAgenda.IsForeignKey = false;
colvarIdAgenda.IsReadOnly = false;
schema.Columns.Add(colvarIdAgenda);
TableSchema.TableColumn colvarPorcentajeTurnosDia = new TableSchema.TableColumn(schema);
colvarPorcentajeTurnosDia.ColumnName = "porcentajeTurnosDia";
colvarPorcentajeTurnosDia.DataType = DbType.Int32;
colvarPorcentajeTurnosDia.MaxLength = 0;
colvarPorcentajeTurnosDia.AutoIncrement = false;
colvarPorcentajeTurnosDia.IsNullable = false;
colvarPorcentajeTurnosDia.IsPrimaryKey = false;
colvarPorcentajeTurnosDia.IsForeignKey = false;
colvarPorcentajeTurnosDia.IsReadOnly = false;
schema.Columns.Add(colvarPorcentajeTurnosDia);
TableSchema.TableColumn colvarPorcentajeTurnosAnticipado = new TableSchema.TableColumn(schema);
colvarPorcentajeTurnosAnticipado.ColumnName = "porcentajeTurnosAnticipado";
colvarPorcentajeTurnosAnticipado.DataType = DbType.Int32;
colvarPorcentajeTurnosAnticipado.MaxLength = 0;
colvarPorcentajeTurnosAnticipado.AutoIncrement = false;
colvarPorcentajeTurnosAnticipado.IsNullable = false;
colvarPorcentajeTurnosAnticipado.IsPrimaryKey = false;
colvarPorcentajeTurnosAnticipado.IsForeignKey = false;
colvarPorcentajeTurnosAnticipado.IsReadOnly = false;
schema.Columns.Add(colvarPorcentajeTurnosAnticipado);
TableSchema.TableColumn colvarHoraInicio = new TableSchema.TableColumn(schema);
colvarHoraInicio.ColumnName = "horaInicio";
colvarHoraInicio.DataType = DbType.AnsiStringFixedLength;
colvarHoraInicio.MaxLength = 5;
colvarHoraInicio.AutoIncrement = false;
colvarHoraInicio.IsNullable = false;
colvarHoraInicio.IsPrimaryKey = false;
colvarHoraInicio.IsForeignKey = false;
colvarHoraInicio.IsReadOnly = false;
schema.Columns.Add(colvarHoraInicio);
TableSchema.TableColumn colvarHoraFin = new TableSchema.TableColumn(schema);
colvarHoraFin.ColumnName = "horaFin";
colvarHoraFin.DataType = DbType.AnsiStringFixedLength;
colvarHoraFin.MaxLength = 5;
colvarHoraFin.AutoIncrement = false;
colvarHoraFin.IsNullable = false;
colvarHoraFin.IsPrimaryKey = false;
colvarHoraFin.IsForeignKey = false;
colvarHoraFin.IsReadOnly = false;
schema.Columns.Add(colvarHoraFin);
TableSchema.TableColumn colvarDuracion = new TableSchema.TableColumn(schema);
colvarDuracion.ColumnName = "duracion";
colvarDuracion.DataType = DbType.Int32;
colvarDuracion.MaxLength = 0;
colvarDuracion.AutoIncrement = false;
colvarDuracion.IsNullable = false;
colvarDuracion.IsPrimaryKey = false;
colvarDuracion.IsForeignKey = false;
colvarDuracion.IsReadOnly = false;
schema.Columns.Add(colvarDuracion);
TableSchema.TableColumn colvarCantidadTurnos = new TableSchema.TableColumn(schema);
colvarCantidadTurnos.ColumnName = "cantidadTurnos";
colvarCantidadTurnos.DataType = DbType.Int32;
colvarCantidadTurnos.MaxLength = 0;
colvarCantidadTurnos.AutoIncrement = false;
colvarCantidadTurnos.IsNullable = true;
colvarCantidadTurnos.IsPrimaryKey = false;
colvarCantidadTurnos.IsForeignKey = false;
colvarCantidadTurnos.IsReadOnly = false;
schema.Columns.Add(colvarCantidadTurnos);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_CantidadTurnosEspecialidad",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public ConCantidadTurnosEspecialidad()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public ConCantidadTurnosEspecialidad(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public ConCantidadTurnosEspecialidad(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public ConCantidadTurnosEspecialidad(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("IdAgenda")]
[Bindable(true)]
public int IdAgenda
{
get
{
return GetColumnValue<int>("idAgenda");
}
set
{
SetColumnValue("idAgenda", value);
}
}
[XmlAttribute("PorcentajeTurnosDia")]
[Bindable(true)]
public int PorcentajeTurnosDia
{
get
{
return GetColumnValue<int>("porcentajeTurnosDia");
}
set
{
SetColumnValue("porcentajeTurnosDia", value);
}
}
[XmlAttribute("PorcentajeTurnosAnticipado")]
[Bindable(true)]
public int PorcentajeTurnosAnticipado
{
get
{
return GetColumnValue<int>("porcentajeTurnosAnticipado");
}
set
{
SetColumnValue("porcentajeTurnosAnticipado", value);
}
}
[XmlAttribute("HoraInicio")]
[Bindable(true)]
public string HoraInicio
{
get
{
return GetColumnValue<string>("horaInicio");
}
set
{
SetColumnValue("horaInicio", value);
}
}
[XmlAttribute("HoraFin")]
[Bindable(true)]
public string HoraFin
{
get
{
return GetColumnValue<string>("horaFin");
}
set
{
SetColumnValue("horaFin", value);
}
}
[XmlAttribute("Duracion")]
[Bindable(true)]
public int Duracion
{
get
{
return GetColumnValue<int>("duracion");
}
set
{
SetColumnValue("duracion", value);
}
}
[XmlAttribute("CantidadTurnos")]
[Bindable(true)]
public int? CantidadTurnos
{
get
{
return GetColumnValue<int?>("cantidadTurnos");
}
set
{
SetColumnValue("cantidadTurnos", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdAgenda = @"idAgenda";
public static string PorcentajeTurnosDia = @"porcentajeTurnosDia";
public static string PorcentajeTurnosAnticipado = @"porcentajeTurnosAnticipado";
public static string HoraInicio = @"horaInicio";
public static string HoraFin = @"horaFin";
public static string Duracion = @"duracion";
public static string CantidadTurnos = @"cantidadTurnos";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using osu.Framework.Allocation;
using osuTK.Graphics;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Cursor;
using osu.Game.Online.Chat;
using osu.Framework.Graphics.Shapes;
using osu.Game.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Overlays.Chat
{
public class DrawableChannel : Container
{
public readonly Channel Channel;
protected FillFlowContainer ChatLineFlow;
private OsuScrollContainer scroll;
private bool scrollbarVisible = true;
public bool ScrollbarVisible
{
set
{
if (scrollbarVisible == value) return;
scrollbarVisible = value;
if (scroll != null)
scroll.ScrollbarVisible = value;
}
}
[Resolved]
private OsuColour colours { get; set; }
public DrawableChannel(Channel channel)
{
Channel = channel;
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load()
{
Child = new OsuContextMenuContainer
{
RelativeSizeAxes = Axes.Both,
Masking = true,
Child = scroll = new OsuScrollContainer
{
ScrollbarVisible = scrollbarVisible,
RelativeSizeAxes = Axes.Both,
// Some chat lines have effects that slightly protrude to the bottom,
// which we do not want to mask away, hence the padding.
Padding = new MarginPadding { Bottom = 5 },
Child = ChatLineFlow = new FillFlowContainer
{
Padding = new MarginPadding { Left = 20, Right = 20 },
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
}
},
};
newMessagesArrived(Channel.Messages);
Channel.NewMessagesArrived += newMessagesArrived;
Channel.MessageRemoved += messageRemoved;
Channel.PendingMessageResolved += pendingMessageResolved;
}
protected override void LoadComplete()
{
base.LoadComplete();
scrollToEnd();
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
Channel.NewMessagesArrived -= newMessagesArrived;
Channel.MessageRemoved -= messageRemoved;
Channel.PendingMessageResolved -= pendingMessageResolved;
}
protected virtual ChatLine CreateChatLine(Message m) => new ChatLine(m);
protected virtual DaySeparator CreateDaySeparator(DateTimeOffset time) => new DaySeparator(time)
{
Margin = new MarginPadding { Vertical = 10 },
Colour = colours.ChatBlue.Lighten(0.7f),
};
private void newMessagesArrived(IEnumerable<Message> newMessages)
{
bool shouldScrollToEnd = scroll.IsScrolledToEnd(10) || !chatLines.Any() || newMessages.Any(m => m is LocalMessage);
// Add up to last Channel.MAX_HISTORY messages
var displayMessages = newMessages.Skip(Math.Max(0, newMessages.Count() - Channel.MAX_HISTORY));
Message lastMessage = chatLines.LastOrDefault()?.Message;
foreach (var message in displayMessages)
{
if (lastMessage == null || lastMessage.Timestamp.ToLocalTime().Date != message.Timestamp.ToLocalTime().Date)
ChatLineFlow.Add(CreateDaySeparator(message.Timestamp));
ChatLineFlow.Add(CreateChatLine(message));
lastMessage = message;
}
var staleMessages = chatLines.Where(c => c.LifetimeEnd == double.MaxValue).ToArray();
int count = staleMessages.Length - Channel.MAX_HISTORY;
if (count > 0)
{
void expireAndAdjustScroll(Drawable d)
{
scroll.OffsetScrollPosition(-d.DrawHeight);
d.Expire();
}
for (int i = 0; i < count; i++)
expireAndAdjustScroll(staleMessages[i]);
// remove all adjacent day separators after stale message removal
for (int i = 0; i < ChatLineFlow.Count - 1; i++)
{
if (!(ChatLineFlow[i] is DaySeparator)) break;
if (!(ChatLineFlow[i + 1] is DaySeparator)) break;
expireAndAdjustScroll(ChatLineFlow[i]);
}
}
if (shouldScrollToEnd)
scrollToEnd();
}
private void pendingMessageResolved(Message existing, Message updated)
{
var found = chatLines.LastOrDefault(c => c.Message == existing);
if (found != null)
{
Trace.Assert(updated.Id.HasValue, "An updated message was returned with no ID.");
ChatLineFlow.Remove(found);
found.Message = updated;
ChatLineFlow.Add(found);
}
}
private void messageRemoved(Message removed)
{
chatLines.FirstOrDefault(c => c.Message == removed)?.FadeColour(Color4.Red, 400).FadeOut(600).Expire();
}
private IEnumerable<ChatLine> chatLines => ChatLineFlow.Children.OfType<ChatLine>();
private void scrollToEnd() => ScheduleAfterChildren(() => scroll.ScrollToEnd());
public class DaySeparator : Container
{
public float TextSize
{
get => text.Font.Size;
set => text.Font = text.Font.With(size: value);
}
private float lineHeight = 2;
public float LineHeight
{
get => lineHeight;
set => lineHeight = leftBox.Height = rightBox.Height = value;
}
private readonly SpriteText text;
private readonly Box leftBox;
private readonly Box rightBox;
public DaySeparator(DateTimeOffset time)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Child = new GridContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
new Dimension(),
},
RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), },
Content = new[]
{
new Drawable[]
{
leftBox = new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Height = lineHeight,
},
text = new OsuSpriteText
{
Margin = new MarginPadding { Horizontal = 10 },
Text = time.ToLocalTime().ToString("dd MMM yyyy"),
},
rightBox = new Box
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Height = lineHeight,
},
}
}
};
}
}
}
}
| |
// 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 System.Collections.Generic;
using System.Linq;
using Avalonia.Collections;
namespace Avalonia.Controls
{
/// <summary>
/// Holds a collection of style classes for an <see cref="IControl"/>.
/// </summary>
/// <remarks>
/// Similar to CSS, each control may have any number of styling classes applied.
/// </remarks>
public class Classes : AvaloniaList<string>, IPseudoClasses
{
/// <summary>
/// Initializes a new instance of the <see cref="Classes"/> class.
/// </summary>
public Classes()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Classes"/> class.
/// </summary>
/// <param name="items">The initial items.</param>
public Classes(IEnumerable<string> items)
: base(items)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Classes"/> class.
/// </summary>
/// <param name="items">The initial items.</param>
public Classes(params string[] items)
: base(items)
{
}
/// <summary>
/// Adds a style class to the collection.
/// </summary>
/// <param name="name">The class name.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override void Add(string name)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
base.Add(name);
}
}
/// <summary>
/// Adds a style classes to the collection.
/// </summary>
/// <param name="names">The class names.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override void AddRange(IEnumerable<string> names)
{
var c = new List<string>();
foreach (var name in names)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
c.Add(name);
}
}
base.AddRange(c);
}
/// <summary>
/// Remvoes all non-pseudoclasses from the collection.
/// </summary>
public override void Clear()
{
for (var i = Count - 1; i >= 0; --i)
{
if (!this[i].StartsWith(":"))
{
RemoveAt(i);
}
}
}
/// <summary>
/// Inserts a style class into the collection.
/// </summary>
/// <param name="index">The index to insert the class at.</param>
/// <param name="name">The class name.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override void Insert(int index, string name)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
base.Insert(index, name);
}
}
/// <summary>
/// Inserts style classes into the collection.
/// </summary>
/// <param name="index">The index to insert the class at.</param>
/// <param name="names">The class names.</param>
/// <remarks>
/// Only standard classes may be added via this method. To add pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override void InsertRange(int index, IEnumerable<string> names)
{
var c = new List<string>();
foreach (var name in names)
{
ThrowIfPseudoclass(name, "added");
if (!Contains(name))
{
c.Add(name);
}
}
base.InsertRange(index, c);
}
/// <summary>
/// Removes a style class from the collection.
/// </summary>
/// <param name="name">The class name.</param>
/// <remarks>
/// Only standard classes may be removed via this method. To remove pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override bool Remove(string name)
{
ThrowIfPseudoclass(name, "removed");
return base.Remove(name);
}
/// <summary>
/// Removes style classes from the collection.
/// </summary>
/// <param name="names">The class name.</param>
/// <remarks>
/// Only standard classes may be removed via this method. To remove pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override void RemoveAll(IEnumerable<string> names)
{
var c = new List<string>();
foreach (var name in names)
{
ThrowIfPseudoclass(name, "removed");
if (!Contains(name))
{
c.Add(name);
}
}
base.RemoveAll(c);
}
/// <summary>
/// Removes a style class from the collection.
/// </summary>
/// <param name="index">The index of the class in the collection.</param>
/// <remarks>
/// Only standard classes may be removed via this method. To remove pseudoclasses (classes
/// beginning with a ':' character) use the protected <see cref="Control.PseudoClasses"/>
/// property.
/// </remarks>
public override void RemoveAt(int index)
{
var name = this[index];
ThrowIfPseudoclass(name, "removed");
base.RemoveAt(index);
}
/// <summary>
/// Removes style classes from the collection.
/// </summary>
/// <param name="index">The first index to remove.</param>
/// <param name="count">The number of items to remove.</param>
public override void RemoveRange(int index, int count)
{
base.RemoveRange(index, count);
}
/// <summary>
/// Removes all non-pseudoclasses in the collection and adds a new set.
/// </summary>
/// <param name="source">The new contents of the collection.</param>
public void Replace(IList<string> source)
{
var toRemove = new List<string>();
foreach (var name in source)
{
ThrowIfPseudoclass(name, "added");
}
foreach (var name in this)
{
if (!name.StartsWith(":"))
{
toRemove.Add(name);
}
}
base.RemoveAll(toRemove);
base.AddRange(source);
}
/// <inheritdoc/>
void IPseudoClasses.Add(string name)
{
if (!Contains(name))
{
base.Add(name);
}
}
/// <inheritdoc/>
bool IPseudoClasses.Remove(string name)
{
return base.Remove(name);
}
private void ThrowIfPseudoclass(string name, string operation)
{
if (name.StartsWith(":"))
{
throw new ArgumentException(
$"The pseudoclass '{name}' may only be {operation} by the control itself.");
}
}
}
}
| |
using System.Collections.Generic;
using System.Collections.ObjectModel;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.IE
{
/// <summary>
/// Wrapper class for finding elements
/// </summary>
internal class Finder : ISearchContext, IFindsById, IFindsByLinkText, IFindsByName, IFindsByPartialLinkText, IFindsByTagName, IFindsByXPath, IFindsByClassName // , IFindsByCssSelector
{
private InternetExplorerDriver driver;
private SafeInternetExplorerWebElementHandle parent;
private SafeInternetExplorerDriverHandle handle;
/// <summary>
/// Initializes a new instance of the Finder class.
/// </summary>
/// <param name="driver">InternetExplorerDriver in use</param>
/// <param name="parent">ElementHandle to for use with the Native methods</param>
public Finder(InternetExplorerDriver driver, SafeInternetExplorerWebElementHandle parent)
{
this.driver = driver;
this.parent = parent;
handle = driver.GetUnderlayingHandle();
}
/// <summary>
/// Find the first element that has this ID
/// </summary>
/// <param name="id">ID of web element on the page</param>
/// <returns>Returns a IWebElement to use</returns>
public IWebElement FindElementById(string id)
{
SafeInternetExplorerWebElementHandle rawElement = new SafeInternetExplorerWebElementHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementById(handle, parent, id, ref rawElement);
ResultHandler.VerifyResultCode(result, "FindElementById");
return new InternetExplorerWebElement(driver, rawElement);
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the Element</param>
/// <returns>ReadOnlyCollection of Elements that match the object so that you can interact that object</returns>
public ReadOnlyCollection<IWebElement> FindElementsById(string id)
{
SafeWebElementCollectionHandle collectionHandle = new SafeWebElementCollectionHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementsById(handle, parent, id, ref collectionHandle);
ResultHandler.VerifyResultCode(result, "FindElementsById");
List<IWebElement> elementList = new List<IWebElement>();
using (InternetExplorerWebElementCollection elements = new InternetExplorerWebElementCollection(driver, collectionHandle))
{
elementList = elements.ToList();
}
return new ReadOnlyCollection<IWebElement>(elementList);
}
/// <summary>
/// Finds the first of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element </param>
/// <returns>IWebElement object so that you can interact that object</returns>
public IWebElement FindElementByLinkText(string linkText)
{
SafeInternetExplorerWebElementHandle rawElement = new SafeInternetExplorerWebElementHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementByLinkText(handle, parent, linkText, ref rawElement);
ResultHandler.VerifyResultCode(result, "FindElementByLinkText");
return new InternetExplorerWebElement(driver, rawElement);
}
/// <summary>
/// Finds a list of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element</param>
/// <returns>ReadOnlyCollection of IWebElement object so that you can interact with those objects</returns>
public ReadOnlyCollection<IWebElement> FindElementsByLinkText(string linkText)
{
SafeWebElementCollectionHandle collectionHandle = new SafeWebElementCollectionHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementsByLinkText(handle, parent, linkText, ref collectionHandle);
ResultHandler.VerifyResultCode(result, "FindElementsByLinkText");
List<IWebElement> elementList = new List<IWebElement>();
using (InternetExplorerWebElementCollection elements = new InternetExplorerWebElementCollection(driver, collectionHandle))
{
elementList = elements.ToList();
}
return new ReadOnlyCollection<IWebElement>(elementList);
}
/// <summary>
/// Find the first element that matches by name
/// </summary>
/// <param name="name">Name of the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
public IWebElement FindElementByName(string name)
{
SafeInternetExplorerWebElementHandle rawElement = new SafeInternetExplorerWebElementHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementByName(handle, parent, name, ref rawElement);
ResultHandler.VerifyResultCode(result, "FindElementByName");
return new InternetExplorerWebElement(driver, rawElement);
}
/// <summary>
/// Find all the elements that match the name
/// </summary>
/// <param name="name">Name of element on the page</param>
/// <returns>ReadOnlyCollection ofIWebElement object so that you can interact that object</returns>
public ReadOnlyCollection<IWebElement> FindElementsByName(string name)
{
SafeWebElementCollectionHandle collectionHandle = new SafeWebElementCollectionHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementsByName(handle, parent, name, ref collectionHandle);
ResultHandler.VerifyResultCode(result, "FindElementsByName");
List<IWebElement> elementList = new List<IWebElement>();
using (InternetExplorerWebElementCollection elements = new InternetExplorerWebElementCollection(driver, collectionHandle))
{
elementList = elements.ToList();
}
return new ReadOnlyCollection<IWebElement>(elementList);
}
/// <summary>
/// Find the first element that matches the XPath
/// </summary>
/// <param name="xpath">XPath to the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
public IWebElement FindElementByXPath(string xpath)
{
SafeInternetExplorerWebElementHandle rawElement = new SafeInternetExplorerWebElementHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementByXPath(handle, parent, xpath, ref rawElement);
ResultHandler.VerifyResultCode(result, "FindElementByXPath");
return new InternetExplorerWebElement(driver, rawElement);
}
/// <summary>
/// Find all the elements taht match the XPath
/// </summary>
/// <param name="xpath">XPath to the element</param>
/// <returns>ReadOnlyCollection of IWebElement object so that you can interact that object</returns>
public ReadOnlyCollection<IWebElement> FindElementsByXPath(string xpath)
{
SafeWebElementCollectionHandle collectionHandle = new SafeWebElementCollectionHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementsByXPath(handle, parent, xpath, ref collectionHandle);
ResultHandler.VerifyResultCode(result, "FindElementsByXPath");
List<IWebElement> elementList = new List<IWebElement>();
using (InternetExplorerWebElementCollection elements = new InternetExplorerWebElementCollection(driver, collectionHandle))
{
elementList = elements.ToList();
}
return new ReadOnlyCollection<IWebElement>(elementList);
}
/// <summary>
/// Find the first element that matches the tag
/// </summary>
/// <param name="tagName">tagName of element on the page</param>
/// <returns>IWebElement object so that you can interact that object</returns>
public IWebElement FindElementByTagName(string tagName)
{
SafeInternetExplorerWebElementHandle rawElement = new SafeInternetExplorerWebElementHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementByTagName(handle, parent, tagName, ref rawElement);
ResultHandler.VerifyResultCode(result, "FindElementByTagName");
return new InternetExplorerWebElement(driver, rawElement);
}
/// <summary>
/// Find all elements that match the tag
/// </summary>
/// <param name="tagName">tagName of element on the page</param>
/// <returns>ReadOnlyCollection of IWebElement object so that you can interact that object</returns>
public ReadOnlyCollection<IWebElement> FindElementsByTagName(string tagName)
{
SafeWebElementCollectionHandle collectionHandle = new SafeWebElementCollectionHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementsByTagName(handle, parent, tagName, ref collectionHandle);
ResultHandler.VerifyResultCode(result, "FindElementsByTagName");
List<IWebElement> elementList = new List<IWebElement>();
using (InternetExplorerWebElementCollection elements = new InternetExplorerWebElementCollection(driver, collectionHandle))
{
elementList = elements.ToList();
}
return new ReadOnlyCollection<IWebElement>(elementList);
}
/// <summary>
/// Find the first element that matches part of the text
/// </summary>
/// <param name="partialLinkText">text to be use</param>
/// <returns>IWebElement object so that you can interact that object</returns>
public IWebElement FindElementByPartialLinkText(string partialLinkText)
{
SafeInternetExplorerWebElementHandle rawElement = new SafeInternetExplorerWebElementHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementByPartialLinkText(handle, parent, partialLinkText, ref rawElement);
ResultHandler.VerifyResultCode(result, "FindElementByPartialLinkText");
return new InternetExplorerWebElement(driver, rawElement);
}
/// <summary>
/// Method to return all elements that match the link text passed in
/// </summary>
/// <param name="partialLinkText">Text to search for</param>
/// <returns>Returns a ReadOnlyCollection of IWebElements so you can interact with that object</returns>
public ReadOnlyCollection<IWebElement> FindElementsByPartialLinkText(string partialLinkText)
{
SafeWebElementCollectionHandle collectionHandle = new SafeWebElementCollectionHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementsByPartialLinkText(handle, parent, partialLinkText, ref collectionHandle);
ResultHandler.VerifyResultCode(result, "FindElementsByPartialLinkText");
List<IWebElement> elementList = new List<IWebElement>();
using (InternetExplorerWebElementCollection elements = new InternetExplorerWebElementCollection(driver, collectionHandle))
{
elementList = elements.ToList();
}
return new ReadOnlyCollection<IWebElement>(elementList);
}
/// <summary>
/// Method to return the first element that matches the CSS class passed in
/// </summary>
/// <param name="className">CSS class name</param>
/// <returns>IWebElement object so that you can interact that object</returns>
public IWebElement FindElementByClassName(string className)
{
SafeInternetExplorerWebElementHandle rawElement = new SafeInternetExplorerWebElementHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementByClassName(handle, parent, className, ref rawElement);
ResultHandler.VerifyResultCode(result, "FindElementByClassName");
return new InternetExplorerWebElement(driver, rawElement);
}
/// <summary>
/// Method to find all the elements on the page that match the CSS Classname
/// </summary>
/// <param name="className"> CSS Class you wish to find</param>
/// <returns>ReadOnlyCollection of IWebElement objects so that you can interact those objects</returns>
public ReadOnlyCollection<IWebElement> FindElementsByClassName(string className)
{
SafeWebElementCollectionHandle collectionHandle = new SafeWebElementCollectionHandle();
WebDriverResult result = NativeDriverLibrary.Instance.FindElementsByClassName(handle, parent, className, ref collectionHandle);
ResultHandler.VerifyResultCode(result, "FindElementsByClassName");
List<IWebElement> elementList = new List<IWebElement>();
using (InternetExplorerWebElementCollection elements = new InternetExplorerWebElementCollection(driver, collectionHandle))
{
elementList = elements.ToList();
}
return new ReadOnlyCollection<IWebElement>(elementList);
}
/*public IWebElement FindElementByCssSelector(string cssSelector)
*{
* throw new NotImplementedException("CSS selector is not supported in IE");
*}
*/
/*public ReadOnlyCollection<IWebElement> FindElementsByCssSelector(string cssSelector)
*{
* throw new NotImplementedException("CSS selector is not supported in IE");
*}
*/
/// <summary>
/// Find the first element that matches the By mechanism
/// </summary>
/// <param name="by">By mechanism</param>
/// <returns>IWebElement object so that you can interact that object</returns>
public IWebElement FindElement(By by)
{
return by.FindElement(this);
}
/// <summary>
/// Find all Elements that match the By mechanism
/// </summary>
/// <param name="by">By mechanism</param>
/// <returns>ReadOnlyCollection of IWebElement objects so that you can interact those objects</returns>
public ReadOnlyCollection<IWebElement> FindElements(By by)
{
return by.FindElements(this);
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using Fungus;
namespace Fungus
{
/**
* Controller for main camera.
* Supports several types of camera transition including snap, pan & fade.
*/
public class CameraController : MonoBehaviour
{
/**
* Full screen texture used for screen fade effect.
*/
public Texture2D screenFadeTexture;
/**
* Icon to display when swipe pan mode is active.
*/
public Texture2D swipePanIcon;
/**
* Position of continue and swipe icons in normalized screen space coords.
* (0,0) = top left, (1,1) = bottom right
*/
public Vector2 swipeIconPosition = new Vector2(1,0);
/**
* Fixed Z coordinate of main camera.
*/
public float cameraZ = -10f;
[HideInInspector]
public bool waiting;
protected float fadeAlpha = 0f;
// Swipe panning control
[HideInInspector]
public bool swipePanActive;
[HideInInspector]
public float swipeSpeedMultiplier = 1f;
protected View swipePanViewA;
protected View swipePanViewB;
protected Vector3 previousMousePos;
protected class CameraView
{
public Vector3 cameraPos;
public Quaternion cameraRot;
public float cameraSize;
};
protected Dictionary<string, CameraView> storedViews = new Dictionary<string, CameraView>();
protected static CameraController instance;
/**
* Returns the CameraController singleton instance.
* Will create a CameraController game object if none currently exists.
*/
static public CameraController GetInstance()
{
if (instance == null)
{
GameObject go = new GameObject("CameraController");
instance = go.AddComponent<CameraController>();
}
return instance;
}
public static Texture2D CreateColorTexture(Color color, int width, int height)
{
Color[] pixels = new Color[width * height];
for (int i = 0; i < pixels.Length; i++)
{
pixels[i] = color;
}
Texture2D texture = new Texture2D(width, height, TextureFormat.ARGB32, false);
texture.SetPixels(pixels);
texture.Apply();
return texture;
}
protected virtual void OnGUI()
{
if (swipePanActive)
{
// Draw the swipe panning icon
if (swipePanIcon)
{
float x = Screen.width * swipeIconPosition.x;
float y = Screen.height * swipeIconPosition.y;
float width = swipePanIcon.width;
float height = swipePanIcon.height;
x = Mathf.Max(x, 0);
y = Mathf.Max(y, 0);
x = Mathf.Min(x, Screen.width - width);
y = Mathf.Min(y, Screen.height - height);
Rect rect = new Rect(x, y, width, height);
GUI.DrawTexture(rect, swipePanIcon);
}
}
// Draw full screen fade texture
if (fadeAlpha > 0f &&
screenFadeTexture != null)
{
// 1 = scene fully visible
// 0 = scene fully obscured
GUI.color = new Color(1,1,1, fadeAlpha);
GUI.depth = -1000;
GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), screenFadeTexture);
}
}
/**
* Perform a fullscreen fade over a duration.
*/
public virtual void Fade(float targetAlpha, float fadeDuration, Action fadeAction)
{
StartCoroutine(FadeInternal(targetAlpha, fadeDuration, fadeAction));
}
/**
* Fade out, move camera to view and then fade back in.
*/
public virtual void FadeToView(View view, float fadeDuration, bool fadeOut, Action fadeAction)
{
swipePanActive = false;
fadeAlpha = 0f;
float outDuration;
float inDuration;
if (fadeOut)
{
outDuration = fadeDuration / 2f;
inDuration = fadeDuration / 2f;
}
else
{
outDuration = 0;
inDuration = fadeDuration;
}
// Fade out
Fade(1f, outDuration, delegate {
// Snap to new view
PanToPosition(view.transform.position, view.transform.rotation, view.viewSize, 0f, null);
// Fade in
Fade(0f, inDuration, delegate {
if (fadeAction != null)
{
fadeAction();
}
});
});
}
protected virtual IEnumerator FadeInternal(float targetAlpha, float fadeDuration, Action fadeAction)
{
float startAlpha = fadeAlpha;
float timer = 0;
// If already at the target alpha then complete immediately
if (startAlpha == targetAlpha)
{
yield return null;
}
else
{
while (timer < fadeDuration)
{
float t = timer / fadeDuration;
timer += Time.deltaTime;
t = Mathf.Clamp01(t);
fadeAlpha = Mathf.Lerp(startAlpha, targetAlpha, t);
yield return null;
}
}
fadeAlpha = targetAlpha;
if (fadeAction != null)
{
fadeAction();
}
}
/**
* Positions camera so sprite is centered and fills the screen.
* @param spriteRenderer The sprite to center the camera on
*/
public virtual void CenterOnSprite(SpriteRenderer spriteRenderer)
{
swipePanActive = false;
Sprite sprite = spriteRenderer.sprite;
Vector3 extents = sprite.bounds.extents;
float localScaleY = spriteRenderer.transform.localScale.y;
Camera camera = GetCamera();
if (camera != null)
{
camera.orthographicSize = extents.y * localScaleY;
Vector3 pos = spriteRenderer.transform.position;
camera.transform.position = new Vector3(pos.x, pos.y, 0);
SetCameraZ();
}
}
public virtual void PanToView(View view, float duration, Action arriveAction)
{
PanToPosition(view.transform.position, view.transform.rotation, view.viewSize, duration, arriveAction);
}
/**
* Moves camera from current position to a target position over a period of time.
*/
public virtual void PanToPosition(Vector3 targetPosition, Quaternion targetRotation, float targetSize, float duration, Action arriveAction)
{
// Stop any pan that is currently active
StopAllCoroutines();
swipePanActive = false;
if (duration == 0f)
{
// Move immediately
Camera camera = GetCamera();
if (camera != null)
{
camera.orthographicSize = targetSize;
camera.transform.position = targetPosition;
camera.transform.rotation = targetRotation;
}
SetCameraZ();
if (arriveAction != null)
{
arriveAction();
}
}
else
{
StartCoroutine(PanInternal(targetPosition, targetRotation, targetSize, duration, arriveAction));
}
}
/**
* Stores the current camera view using a name.
*/
public virtual void StoreView(string viewName)
{
Camera camera = GetCamera();
if (camera != null)
{
CameraView currentView = new CameraView();
currentView.cameraPos = camera.transform.position;
currentView.cameraRot = camera.transform.rotation;
currentView.cameraSize = camera.orthographicSize;
storedViews[viewName] = currentView;
}
}
/**
* Moves the camera to a previously stored camera view over a period of time.
*/
public virtual void PanToStoredView(string viewName, float duration, Action arriveAction)
{
if (!storedViews.ContainsKey(viewName))
{
// View has not previously been stored
if (arriveAction != null)
{
arriveAction();
}
return;
}
CameraView cameraView = storedViews[viewName];
if (duration == 0f)
{
// Move immediately
Camera camera = GetCamera();
if (camera != null)
{
camera.transform.position = cameraView.cameraPos;
camera.transform.rotation = cameraView.cameraRot;
camera.orthographicSize = cameraView.cameraSize;
}
SetCameraZ();
if (arriveAction != null)
{
arriveAction();
}
}
else
{
StartCoroutine(PanInternal(cameraView.cameraPos, cameraView.cameraRot, cameraView.cameraSize, duration, arriveAction));
}
}
protected virtual IEnumerator PanInternal(Vector3 targetPos, Quaternion targetRot, float targetSize, float duration, Action arriveAction)
{
Camera camera = GetCamera();
if (camera == null)
{
yield break;
}
float timer = 0;
float startSize = camera.orthographicSize;
float endSize = targetSize;
Vector3 startPos = camera.transform.position;
Vector3 endPos = targetPos;
Quaternion startRot = camera.transform.rotation;
Quaternion endRot = targetRot;
bool arrived = false;
while (!arrived)
{
timer += Time.deltaTime;
if (timer > duration)
{
arrived = true;
timer = duration;
}
// Apply smoothed lerp to camera position and orthographic size
float t = timer / duration;
camera.orthographicSize = Mathf.Lerp(startSize, endSize, Mathf.SmoothStep(0f, 1f, t));
camera.transform.position = Vector3.Lerp(startPos, endPos, Mathf.SmoothStep(0f, 1f, t));
camera.transform.rotation = Quaternion.Lerp(startRot, endRot, Mathf.SmoothStep(0f, 1f, t));
SetCameraZ();
if (arrived &&
arriveAction != null)
{
arriveAction();
}
yield return null;
}
}
/**
* Moves camera smoothly through a sequence of Views over a period of time
*/
public virtual void PanToPath(View[] viewList, float duration, Action arriveAction)
{
Camera camera = GetCamera();
if (camera == null)
{
return;
}
swipePanActive = false;
List<Vector3> pathList = new List<Vector3>();
// Add current camera position as first point in path
// Note: We use the z coord to tween the camera orthographic size
Vector3 startPos = new Vector3(camera.transform.position.x,
camera.transform.position.y,
camera.orthographicSize);
pathList.Add(startPos);
for (int i = 0; i < viewList.Length; ++i)
{
View view = viewList[i];
Vector3 viewPos = new Vector3(view.transform.position.x,
view.transform.position.y,
view.viewSize);
pathList.Add(viewPos);
}
StartCoroutine(PanToPathInternal(duration, arriveAction, pathList.ToArray()));
}
protected virtual IEnumerator PanToPathInternal(float duration, Action arriveAction, Vector3[] path)
{
Camera camera = GetCamera();
if (camera == null)
{
yield break;
}
float timer = 0;
while (timer < duration)
{
timer += Time.deltaTime;
timer = Mathf.Min(timer, duration);
float percent = timer / duration;
Vector3 point = iTween.PointOnPath(path, percent);
camera.transform.position = new Vector3(point.x, point.y, 0);
camera.orthographicSize = point.z;
SetCameraZ();
yield return null;
}
if (arriveAction != null)
{
arriveAction();
}
}
/**
* Activates swipe panning mode.
* The player can pan the camera within the area between viewA & viewB.
*/
public virtual void StartSwipePan(View viewA, View viewB, float duration, float speedMultiplier, Action arriveAction)
{
Camera camera = GetCamera();
if (camera == null)
{
return;
}
swipePanViewA = viewA;
swipePanViewB = viewB;
swipeSpeedMultiplier = speedMultiplier;
Vector3 cameraPos = camera.transform.position;
Vector3 targetPosition = CalcCameraPosition(cameraPos, swipePanViewA, swipePanViewB);
float targetSize = CalcCameraSize(cameraPos, swipePanViewA, swipePanViewB);
PanToPosition(targetPosition, Quaternion.identity, targetSize, duration, delegate {
swipePanActive = true;
if (arriveAction != null)
{
arriveAction();
}
});
}
/**
* Deactivates swipe panning mode.
*/
public virtual void StopSwipePan()
{
swipePanActive = false;
swipePanViewA = null;
swipePanViewB = null;
}
protected virtual void SetCameraZ()
{
Camera camera = GetCamera();
if (camera)
{
camera.transform.position = new Vector3(camera.transform.position.x, camera.transform.position.y, cameraZ);
}
}
protected virtual void Update()
{
if (!swipePanActive)
{
return;
}
Vector3 delta = Vector3.zero;
if (Input.touchCount > 0)
{
if (Input.GetTouch(0).phase == TouchPhase.Moved)
{
delta = Input.GetTouch(0).deltaPosition;
}
}
if (Input.GetMouseButtonDown(0))
{
previousMousePos = Input.mousePosition;
}
else if (Input.GetMouseButton(0))
{
delta = Input.mousePosition - previousMousePos;
previousMousePos = Input.mousePosition;
}
Camera camera = GetCamera();
if (camera != null)
{
Vector3 cameraDelta = camera.ScreenToViewportPoint(delta);
cameraDelta.x *= -2f * swipeSpeedMultiplier;
cameraDelta.y *= -2f * swipeSpeedMultiplier;
cameraDelta.z = 0f;
Vector3 cameraPos = camera.transform.position;
cameraPos += cameraDelta;
camera.transform.position = CalcCameraPosition(cameraPos, swipePanViewA, swipePanViewB);
camera.orthographicSize = CalcCameraSize(cameraPos, swipePanViewA, swipePanViewB);
}
}
// Clamp camera position to region defined by the two views
protected virtual Vector3 CalcCameraPosition(Vector3 pos, View viewA, View viewB)
{
Vector3 safePos = pos;
// Clamp camera position to region defined by the two views
safePos.x = Mathf.Max(safePos.x, Mathf.Min(viewA.transform.position.x, viewB.transform.position.x));
safePos.x = Mathf.Min(safePos.x, Mathf.Max(viewA.transform.position.x, viewB.transform.position.x));
safePos.y = Mathf.Max(safePos.y, Mathf.Min(viewA.transform.position.y, viewB.transform.position.y));
safePos.y = Mathf.Min(safePos.y, Mathf.Max(viewA.transform.position.y, viewB.transform.position.y));
return safePos;
}
// Smoothly interpolate camera orthographic size based on relative position to two views
protected virtual float CalcCameraSize(Vector3 pos, View viewA, View viewB)
{
// Get ray and point in same space
Vector3 toViewB = viewB.transform.position - viewA.transform.position;
Vector3 localPos = pos - viewA.transform.position;
// Normalize
float distance = toViewB.magnitude;
toViewB /= distance;
localPos /= distance;
// Project point onto ray
float t = Vector3.Dot(toViewB, localPos);
t = Mathf.Clamp01(t); // Not really necessary but no harm
float cameraSize = Mathf.Lerp(viewA.viewSize, viewB.viewSize, t);
return cameraSize;
}
protected Camera GetCamera()
{
Camera camera = Camera.main;
if (camera == null)
{
camera = GameObject.FindObjectOfType<Camera>() as Camera;
}
return camera;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GvrPointerInputModuleImpl.cs" company="Google Inc.">
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the MIT License, you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// http://www.opensource.org/licenses/mit-license.php
//
// 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 UnityEngine;
using UnityEngine.EventSystems;
using Gvr.Internal;
#if UNITY_2017_2_OR_NEWER
using UnityEngine.XR;
#else
using XRSettings = UnityEngine.VR.VRSettings;
#endif // UNITY_2017_2_OR_NEWER
/// Implementation of _GvrPointerInputModule_
public class GvrPointerInputModuleImpl
{
/// Interface for controlling the actual InputModule.
public IGvrInputModuleController ModuleController { get; set; }
/// Interface for executing events.
public IGvrEventExecutor EventExecutor { get; set; }
/// Determines whether pointer input is active in VR Mode only (`true`), or all of the
/// time (`false`). Set to false if you plan to use direct screen taps or other
/// input when not in VR Mode.
public bool VrModeOnly { get; set; }
/// The GvrPointerScrollInput used to route Scroll Events through _EventSystem_
public GvrPointerScrollInput ScrollInput { get; set; }
/// PointerEventData from the most recent frame.
public GvrPointerEventData CurrentEventData { get; private set; }
/// The GvrBasePointer which will be responding to pointer events.
public GvrBasePointer Pointer
{
get
{
return pointer;
}
set
{
if (pointer == value)
{
return;
}
TryExitPointer();
pointer = value;
}
}
private GvrBasePointer pointer;
private Vector2 lastPose;
private bool isPointerHovering = false;
// Active state
private bool isActive = false;
/// <summary>Returns true if the module should be activated.</summary>
[SuppressMemoryAllocationError(IsWarning = true, Reason = "Pending documentation.")]
public bool ShouldActivateModule()
{
bool isVrModeEnabled = !VrModeOnly;
isVrModeEnabled |= XRSettings.enabled;
bool activeState = ModuleController.ShouldActivate() && isVrModeEnabled;
if (activeState != isActive)
{
isActive = activeState;
}
return activeState;
}
/// <summary>Deactivates this input module.</summary>
[SuppressMemoryAllocationError(IsWarning = true, Reason = "Pending documentation.")]
public void DeactivateModule()
{
TryExitPointer();
ModuleController.Deactivate();
if (CurrentEventData != null)
{
HandlePendingClick();
HandlePointerExitAndEnter(CurrentEventData, null);
CurrentEventData = null;
}
ModuleController.eventSystem.SetSelectedGameObject(null, ModuleController.GetBaseEventData());
}
/// <summary>Returns true if the pointer is over a game object.</summary>
/// <param name="pointerId">The pointer id to check.</param>
public bool IsPointerOverGameObject(int pointerId)
{
return (CurrentEventData != null &&
CurrentEventData.pointerEnter != null &&
CurrentEventData.pointerId == pointerId);
}
/// <summary>Process the input for the current frame.</summary>
[SuppressMemoryAllocationError(IsWarning = true, Reason = "Pending documentation.")]
public void Process()
{
// If the pointer is inactive, make sure it is exited if necessary.
if (!IsPointerActiveAndAvailable())
{
TryExitPointer();
}
// Save the previous Game Object
GameObject previousObject = GetCurrentGameObject();
CastRay();
UpdateCurrentObject(previousObject);
UpdatePointer(previousObject);
// True during the frame that the trigger has been pressed.
bool triggerDown = false;
// True if the trigger is held down.
bool triggering = false;
if (IsPointerActiveAndAvailable())
{
triggerDown = Pointer.TriggerDown;
triggering = Pointer.Triggering;
}
bool handlePendingClickRequired = !triggering;
// Handle input
if (!triggerDown && triggering)
{
HandleDrag();
}
else if (triggerDown && !CurrentEventData.eligibleForClick)
{
// New trigger action.
HandleTriggerDown();
}
else if (handlePendingClickRequired)
{
// Check if there is a pending click to handle.
HandlePendingClick();
}
ScrollInput.HandleScroll(GetCurrentGameObject(), CurrentEventData, Pointer, EventExecutor);
}
private void CastRay()
{
Vector2 currentPose = lastPose;
if (IsPointerActiveAndAvailable())
{
currentPose = GvrMathHelpers.NormalizedCartesianToSpherical(Pointer.PointerTransform.forward);
}
if (CurrentEventData == null)
{
CurrentEventData = new GvrPointerEventData(ModuleController.eventSystem);
lastPose = currentPose;
}
// Store the previous raycast result.
RaycastResult previousRaycastResult = CurrentEventData.pointerCurrentRaycast;
// The initial cast must use the enter radius.
if (IsPointerActiveAndAvailable())
{
Pointer.ShouldUseExitRadiusForRaycast = false;
}
// Cast a ray into the scene
CurrentEventData.Reset();
// Set the position to the center of the camera.
// This is only necessary if using the built-in Unity raycasters.
RaycastResult raycastResult;
CurrentEventData.position = GvrVRHelpers.GetViewportCenter();
bool isPointerActiveAndAvailable = IsPointerActiveAndAvailable();
if (isPointerActiveAndAvailable)
{
RaycastAll();
raycastResult = ModuleController.FindFirstRaycast(ModuleController.RaycastResultCache);
if (Pointer.ControllerInputDevice == null || Pointer.ControllerInputDevice.IsDominantHand)
{
CurrentEventData.pointerId = (int)GvrControllerHand.Dominant;
}
else
{
CurrentEventData.pointerId = (int)GvrControllerHand.NonDominant;
}
}
else
{
raycastResult = new RaycastResult();
raycastResult.Clear();
}
// If we were already pointing at an object we must check that object against the exit radius
// to make sure we are no longer pointing at it to prevent flicker.
if (previousRaycastResult.gameObject != null
&& raycastResult.gameObject != previousRaycastResult.gameObject
&& isPointerActiveAndAvailable)
{
Pointer.ShouldUseExitRadiusForRaycast = true;
RaycastAll();
RaycastResult firstResult = ModuleController.FindFirstRaycast(ModuleController.RaycastResultCache);
if (firstResult.gameObject == previousRaycastResult.gameObject)
{
raycastResult = firstResult;
}
}
if (raycastResult.gameObject != null && raycastResult.worldPosition == Vector3.zero)
{
raycastResult.worldPosition = GvrMathHelpers.GetIntersectionPosition(CurrentEventData.enterEventCamera, raycastResult);
}
CurrentEventData.pointerCurrentRaycast = raycastResult;
// Find the real screen position associated with the raycast
// Based on the results of the hit and the state of the pointerData.
if (raycastResult.gameObject != null)
{
CurrentEventData.position = raycastResult.screenPosition;
}
else if (IsPointerActiveAndAvailable() && CurrentEventData.enterEventCamera != null)
{
Vector3 pointerPos = Pointer.MaxPointerEndPoint;
CurrentEventData.position = CurrentEventData.enterEventCamera.WorldToScreenPoint(pointerPos);
}
ModuleController.RaycastResultCache.Clear();
CurrentEventData.delta = currentPose - lastPose;
lastPose = currentPose;
// Check to make sure the Raycaster being used is a GvrRaycaster.
if (raycastResult.module != null
&& !(raycastResult.module is GvrPointerGraphicRaycaster)
&& !(raycastResult.module is GvrPointerPhysicsRaycaster))
{
Debug.LogWarning("Using Raycaster (Raycaster: " + raycastResult.module.GetType() +
", Object: " + raycastResult.module.name + "). It is recommended to use " +
"GvrPointerPhysicsRaycaster or GvrPointerGrahpicRaycaster with GvrPointerInputModule.");
}
}
private void UpdateCurrentObject(GameObject previousObject)
{
if (CurrentEventData == null)
{
return;
}
// Send enter events and update the highlight.
GameObject currentObject = GetCurrentGameObject(); // Get the pointer target
HandlePointerExitAndEnter(CurrentEventData, currentObject);
// Update the current selection, or clear if it is no longer the current object.
var selected = EventExecutor.GetEventHandler<ISelectHandler>(currentObject);
if (selected == ModuleController.eventSystem.currentSelectedGameObject)
{
EventExecutor.Execute(ModuleController.eventSystem.currentSelectedGameObject, ModuleController.GetBaseEventData(),
ExecuteEvents.updateSelectedHandler);
}
else
{
ModuleController.eventSystem.SetSelectedGameObject(null, CurrentEventData);
}
// Execute hover event.
if (currentObject != null && currentObject == previousObject)
{
EventExecutor.ExecuteHierarchy(currentObject, CurrentEventData, GvrExecuteEventsExtension.pointerHoverHandler);
}
}
private void UpdatePointer(GameObject previousObject)
{
if (CurrentEventData == null)
{
return;
}
GameObject currentObject = GetCurrentGameObject(); // Get the pointer target
bool isPointerActiveAndAvailable = IsPointerActiveAndAvailable();
bool isInteractive = CurrentEventData.pointerPress != null ||
EventExecutor.GetEventHandler<IPointerClickHandler>(currentObject) != null ||
EventExecutor.GetEventHandler<IDragHandler>(currentObject) != null;
if (isPointerHovering && currentObject != null && currentObject == previousObject)
{
if (isPointerActiveAndAvailable)
{
Pointer.OnPointerHover(CurrentEventData.pointerCurrentRaycast, isInteractive);
}
}
else
{
// If the object's don't match or the hovering object has been destroyed
// then the pointer has exited.
if (previousObject != null || (currentObject == null && isPointerHovering))
{
if (isPointerActiveAndAvailable)
{
Pointer.OnPointerExit(previousObject);
}
isPointerHovering = false;
}
if (currentObject != null)
{
if (isPointerActiveAndAvailable)
{
Pointer.OnPointerEnter(CurrentEventData.pointerCurrentRaycast, isInteractive);
}
isPointerHovering = true;
}
}
}
private static bool ShouldStartDrag(Vector2 pressPos, Vector2 currentPos, float threshold, bool useDragThreshold)
{
if (!useDragThreshold)
{
return true;
}
return (pressPos - currentPos).sqrMagnitude >= threshold * threshold;
}
private void HandleDrag()
{
bool moving = CurrentEventData.IsPointerMoving();
bool shouldStartDrag = ShouldStartDrag(CurrentEventData.pressPosition,
CurrentEventData.position,
ModuleController.eventSystem.pixelDragThreshold,
CurrentEventData.useDragThreshold);
if (moving && shouldStartDrag && CurrentEventData.pointerDrag != null && !CurrentEventData.dragging)
{
EventExecutor.Execute(CurrentEventData.pointerDrag, CurrentEventData,
ExecuteEvents.beginDragHandler);
CurrentEventData.dragging = true;
}
// Drag notification
if (CurrentEventData.dragging && moving && CurrentEventData.pointerDrag != null)
{
// Before doing drag we should cancel any pointer down state
// And clear selection!
if (CurrentEventData.pointerPress != CurrentEventData.pointerDrag)
{
EventExecutor.Execute(CurrentEventData.pointerPress, CurrentEventData, ExecuteEvents.pointerUpHandler);
CurrentEventData.eligibleForClick = false;
CurrentEventData.gvrButtonsDown = 0;
CurrentEventData.button = 0;
CurrentEventData.pointerPress = null;
CurrentEventData.rawPointerPress = null;
}
EventExecutor.Execute(CurrentEventData.pointerDrag, CurrentEventData, ExecuteEvents.dragHandler);
}
}
private void HandlePendingClick()
{
if (CurrentEventData == null || (!CurrentEventData.eligibleForClick && !CurrentEventData.dragging))
{
return;
}
if (IsPointerActiveAndAvailable())
{
Pointer.OnPointerClickUp();
}
var go = CurrentEventData.pointerCurrentRaycast.gameObject;
// Send pointer up and click events.
EventExecutor.Execute(CurrentEventData.pointerPress, CurrentEventData, ExecuteEvents.pointerUpHandler);
GameObject pointerClickHandler = EventExecutor.GetEventHandler<IPointerClickHandler>(go);
if (CurrentEventData.pointerPress == pointerClickHandler && CurrentEventData.eligibleForClick)
{
EventExecutor.Execute(CurrentEventData.pointerPress, CurrentEventData, ExecuteEvents.pointerClickHandler);
}
if (CurrentEventData != null && CurrentEventData.pointerDrag != null && CurrentEventData.dragging)
{
EventExecutor.ExecuteHierarchy(go, CurrentEventData, ExecuteEvents.dropHandler);
EventExecutor.Execute(CurrentEventData.pointerDrag, CurrentEventData, ExecuteEvents.endDragHandler);
}
if (CurrentEventData != null)
{
// Clear the click state.
CurrentEventData.gvrButtonsDown = 0;
CurrentEventData.button = 0;
CurrentEventData.pointerPress = null;
CurrentEventData.rawPointerPress = null;
CurrentEventData.eligibleForClick = false;
CurrentEventData.clickCount = 0;
CurrentEventData.clickTime = 0;
CurrentEventData.pointerDrag = null;
CurrentEventData.dragging = false;
}
}
private void HandleTriggerDown()
{
var go = CurrentEventData.pointerCurrentRaycast.gameObject;
// Send pointer down event.
CurrentEventData.gvrButtonsDown = Pointer.ControllerButtonDown;
CurrentEventData.button = Pointer.InputButtonDown;
CurrentEventData.pressPosition = CurrentEventData.position;
CurrentEventData.pointerPressRaycast = CurrentEventData.pointerCurrentRaycast;
CurrentEventData.pointerPress =
EventExecutor.ExecuteHierarchy(go, CurrentEventData, ExecuteEvents.pointerDownHandler) ??
EventExecutor.GetEventHandler<IPointerClickHandler>(go);
// Save the pending click state.
CurrentEventData.rawPointerPress = go;
CurrentEventData.eligibleForClick = true;
CurrentEventData.delta = Vector2.zero;
CurrentEventData.dragging = false;
CurrentEventData.useDragThreshold = true;
CurrentEventData.clickCount = 1;
CurrentEventData.clickTime = Time.unscaledTime;
// Save the drag handler as well
CurrentEventData.pointerDrag = EventExecutor.GetEventHandler<IDragHandler>(go);
if (CurrentEventData.pointerDrag != null)
{
EventExecutor.Execute(CurrentEventData.pointerDrag, CurrentEventData, ExecuteEvents.initializePotentialDrag);
}
if (IsPointerActiveAndAvailable())
{
Pointer.OnPointerClickDown();
}
}
private GameObject GetCurrentGameObject()
{
if (CurrentEventData != null)
{
return CurrentEventData.pointerCurrentRaycast.gameObject;
}
return null;
}
// Modified version of BaseInputModule.HandlePointerExitAndEnter that calls EventExecutor instead of
// UnityEngine.EventSystems.ExecuteEvents.
private void HandlePointerExitAndEnter(PointerEventData currentPointerData, GameObject newEnterTarget)
{
// If we have no target or pointerEnter has been deleted then
// just send exit events to anything we are tracking.
// Afterwards, exit.
if (newEnterTarget == null || currentPointerData.pointerEnter == null)
{
for (var i = 0; i < currentPointerData.hovered.Count; ++i)
{
EventExecutor.Execute(currentPointerData.hovered[i], currentPointerData, ExecuteEvents.pointerExitHandler);
}
currentPointerData.hovered.Clear();
if (newEnterTarget == null)
{
currentPointerData.pointerEnter = newEnterTarget;
return;
}
}
// If we have not changed hover target.
if (newEnterTarget && currentPointerData.pointerEnter == newEnterTarget)
{
return;
}
GameObject commonRoot = ModuleController.FindCommonRoot(currentPointerData.pointerEnter, newEnterTarget);
// We already an entered object from last time.
if (currentPointerData.pointerEnter != null)
{
// Send exit handler call to all elements in the chain
// until we reach the new target, or null!
Transform t = currentPointerData.pointerEnter.transform;
while (t != null)
{
// If we reach the common root break out!
if (commonRoot != null && commonRoot.transform == t)
{
break;
}
EventExecutor.Execute(t.gameObject, currentPointerData, ExecuteEvents.pointerExitHandler);
currentPointerData.hovered.Remove(t.gameObject);
t = t.parent;
}
}
// Now issue the enter call up to but not including the common root.
currentPointerData.pointerEnter = newEnterTarget;
if (newEnterTarget != null)
{
Transform t = newEnterTarget.transform;
while (t != null && t.gameObject != commonRoot)
{
EventExecutor.Execute(t.gameObject, currentPointerData, ExecuteEvents.pointerEnterHandler);
currentPointerData.hovered.Add(t.gameObject);
t = t.parent;
}
}
}
private void TryExitPointer()
{
if (Pointer == null)
{
return;
}
GameObject currentGameObject = GetCurrentGameObject();
if (currentGameObject)
{
Pointer.OnPointerExit(currentGameObject);
}
}
private bool IsPointerActiveAndAvailable()
{
return pointer != null && pointer.IsAvailable;
}
private void RaycastAll()
{
ModuleController.RaycastResultCache.Clear();
ModuleController.eventSystem.RaycastAll(CurrentEventData, ModuleController.RaycastResultCache);
}
}
| |
namespace org.apache.http
{
[global::MonoJavaBridge.JavaInterface(typeof(global::org.apache.http.HttpRequest_))]
public interface HttpRequest : HttpMessage
{
global::org.apache.http.RequestLine getRequestLine();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::org.apache.http.HttpRequest))]
public sealed partial class HttpRequest_ : java.lang.Object, HttpRequest
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static HttpRequest_()
{
InitJNI();
}
internal HttpRequest_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getRequestLine16217;
global::org.apache.http.RequestLine org.apache.http.HttpRequest.getRequestLine()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.RequestLine>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._getRequestLine16217)) as org.apache.http.RequestLine;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.RequestLine>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._getRequestLine16217)) as org.apache.http.RequestLine;
}
internal static global::MonoJavaBridge.MethodId _getProtocolVersion16218;
global::org.apache.http.ProtocolVersion org.apache.http.HttpMessage.getProtocolVersion()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._getProtocolVersion16218)) as org.apache.http.ProtocolVersion;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._getProtocolVersion16218)) as org.apache.http.ProtocolVersion;
}
internal static global::MonoJavaBridge.MethodId _getParams16219;
global::org.apache.http.@params.HttpParams org.apache.http.HttpMessage.getParams()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.@params.HttpParams>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._getParams16219)) as org.apache.http.@params.HttpParams;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.@params.HttpParams>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._getParams16219)) as org.apache.http.@params.HttpParams;
}
internal static global::MonoJavaBridge.MethodId _setParams16220;
void org.apache.http.HttpMessage.setParams(org.apache.http.@params.HttpParams arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._setParams16220, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._setParams16220, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getHeaders16221;
global::org.apache.http.Header[] org.apache.http.HttpMessage.getHeaders(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<org.apache.http.Header>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._getHeaders16221, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.Header[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<org.apache.http.Header>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._getHeaders16221, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.Header[];
}
internal static global::MonoJavaBridge.MethodId _containsHeader16222;
bool org.apache.http.HttpMessage.containsHeader(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._containsHeader16222, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._containsHeader16222, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getFirstHeader16223;
global::org.apache.http.Header org.apache.http.HttpMessage.getFirstHeader(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.Header>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._getFirstHeader16223, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.Header;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.Header>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._getFirstHeader16223, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.Header;
}
internal static global::MonoJavaBridge.MethodId _getLastHeader16224;
global::org.apache.http.Header org.apache.http.HttpMessage.getLastHeader(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.Header>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._getLastHeader16224, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.Header;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.Header>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._getLastHeader16224, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.Header;
}
internal static global::MonoJavaBridge.MethodId _getAllHeaders16225;
global::org.apache.http.Header[] org.apache.http.HttpMessage.getAllHeaders()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<org.apache.http.Header>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._getAllHeaders16225)) as org.apache.http.Header[];
else
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<org.apache.http.Header>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._getAllHeaders16225)) as org.apache.http.Header[];
}
internal static global::MonoJavaBridge.MethodId _addHeader16226;
void org.apache.http.HttpMessage.addHeader(org.apache.http.Header arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._addHeader16226, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._addHeader16226, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addHeader16227;
void org.apache.http.HttpMessage.addHeader(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._addHeader16227, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._addHeader16227, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setHeader16228;
void org.apache.http.HttpMessage.setHeader(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._setHeader16228, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._setHeader16228, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setHeader16229;
void org.apache.http.HttpMessage.setHeader(org.apache.http.Header arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._setHeader16229, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._setHeader16229, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setHeaders16230;
void org.apache.http.HttpMessage.setHeaders(org.apache.http.Header[] arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._setHeaders16230, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._setHeaders16230, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeHeader16231;
void org.apache.http.HttpMessage.removeHeader(org.apache.http.Header arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._removeHeader16231, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._removeHeader16231, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeHeaders16232;
void org.apache.http.HttpMessage.removeHeaders(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._removeHeaders16232, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._removeHeaders16232, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _headerIterator16233;
global::org.apache.http.HeaderIterator org.apache.http.HttpMessage.headerIterator()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.HeaderIterator>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._headerIterator16233)) as org.apache.http.HeaderIterator;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.HeaderIterator>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._headerIterator16233)) as org.apache.http.HeaderIterator;
}
internal static global::MonoJavaBridge.MethodId _headerIterator16234;
global::org.apache.http.HeaderIterator org.apache.http.HttpMessage.headerIterator(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.HeaderIterator>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_._headerIterator16234, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.HeaderIterator;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.HeaderIterator>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.HttpRequest_.staticClass, global::org.apache.http.HttpRequest_._headerIterator16234, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as org.apache.http.HeaderIterator;
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::org.apache.http.HttpRequest_.staticClass = @__env.NewGlobalRef(@__env.FindClass("org/apache/http/HttpRequest"));
global::org.apache.http.HttpRequest_._getRequestLine16217 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "getRequestLine", "()Lorg/apache/http/RequestLine;");
global::org.apache.http.HttpRequest_._getProtocolVersion16218 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;");
global::org.apache.http.HttpRequest_._getParams16219 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "getParams", "()Lorg/apache/http/@params/HttpParams;");
global::org.apache.http.HttpRequest_._setParams16220 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "setParams", "(Lorg/apache/http/@params/HttpParams;)V");
global::org.apache.http.HttpRequest_._getHeaders16221 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;");
global::org.apache.http.HttpRequest_._containsHeader16222 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "containsHeader", "(Ljava/lang/String;)Z");
global::org.apache.http.HttpRequest_._getFirstHeader16223 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;");
global::org.apache.http.HttpRequest_._getLastHeader16224 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;");
global::org.apache.http.HttpRequest_._getAllHeaders16225 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "getAllHeaders", "()[Lorg/apache/http/Header;");
global::org.apache.http.HttpRequest_._addHeader16226 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "addHeader", "(Lorg/apache/http/Header;)V");
global::org.apache.http.HttpRequest_._addHeader16227 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V");
global::org.apache.http.HttpRequest_._setHeader16228 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V");
global::org.apache.http.HttpRequest_._setHeader16229 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "setHeader", "(Lorg/apache/http/Header;)V");
global::org.apache.http.HttpRequest_._setHeaders16230 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "setHeaders", "([Lorg/apache/http/Header;)V");
global::org.apache.http.HttpRequest_._removeHeader16231 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "removeHeader", "(Lorg/apache/http/Header;)V");
global::org.apache.http.HttpRequest_._removeHeaders16232 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "removeHeaders", "(Ljava/lang/String;)V");
global::org.apache.http.HttpRequest_._headerIterator16233 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "headerIterator", "()Lorg/apache/http/HeaderIterator;");
global::org.apache.http.HttpRequest_._headerIterator16234 = @__env.GetMethodIDNoThrow(global::org.apache.http.HttpRequest_.staticClass, "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;");
}
}
}
| |
// <copyright file="LoggingTestLibraries.Generated.cs" company="MIT License">
// Licensed under the MIT License. See LICENSE file in the project root for license information.
// </copyright>
/// <summary>
/// This file is auto-generated by a build task. It shouldn't be edited by hand.
/// </summary>
namespace SmallBasic.Tests
{
#pragma warning disable CS0067 // The event '{0}' is never used
using System;
using System.Text;
using System.Threading.Tasks;
using SmallBasic.Compiler.Runtime;
internal sealed class LoggingArrayLibrary : IArrayLibrary
{
private readonly StringBuilder log;
public LoggingArrayLibrary(StringBuilder log)
{
this.log = log;
}
public bool ContainsIndex(ArrayValue array, string index)
{
this.log.AppendLine($"Array.ContainsIndex(array: '{array.ToDisplayString()}', index: '{index}')");
return false;
}
public bool ContainsValue(ArrayValue array, string value)
{
this.log.AppendLine($"Array.ContainsValue(array: '{array.ToDisplayString()}', value: '{value}')");
return false;
}
public ArrayValue GetAllIndices(ArrayValue array)
{
this.log.AppendLine($"Array.GetAllIndices(array: '{array.ToDisplayString()}')");
return new ArrayValue();
}
public decimal GetItemCount(ArrayValue array)
{
this.log.AppendLine($"Array.GetItemCount(array: '{array.ToDisplayString()}')");
return 0m;
}
public BaseValue GetValue(string arrayName, string index)
{
this.log.AppendLine($"Array.GetValue(arrayName: '{arrayName}', index: '{index}')");
return StringValue.Create(string.Empty);
}
public bool IsArray(BaseValue array)
{
this.log.AppendLine($"Array.IsArray(array: '{array.ToDisplayString()}')");
return false;
}
public void RemoveValue(string arrayName, string index)
{
this.log.AppendLine($"Array.RemoveValue(arrayName: '{arrayName}', index: '{index}')");
}
public void SetValue(string arrayName, string index, BaseValue value)
{
this.log.AppendLine($"Array.SetValue(arrayName: '{arrayName}', index: '{index}', value: '{value.ToDisplayString()}')");
}
}
internal sealed class LoggingClockLibrary : IClockLibrary
{
private readonly StringBuilder log;
public LoggingClockLibrary(StringBuilder log)
{
this.log = log;
}
public string Get_Date()
{
this.log.AppendLine($"Clock.Get_Date()");
return string.Empty;
}
public decimal Get_Day()
{
this.log.AppendLine($"Clock.Get_Day()");
return 0m;
}
public decimal Get_ElapsedMilliseconds()
{
this.log.AppendLine($"Clock.Get_ElapsedMilliseconds()");
return 0m;
}
public decimal Get_Hour()
{
this.log.AppendLine($"Clock.Get_Hour()");
return 0m;
}
public decimal Get_Millisecond()
{
this.log.AppendLine($"Clock.Get_Millisecond()");
return 0m;
}
public decimal Get_Minute()
{
this.log.AppendLine($"Clock.Get_Minute()");
return 0m;
}
public decimal Get_Month()
{
this.log.AppendLine($"Clock.Get_Month()");
return 0m;
}
public decimal Get_Second()
{
this.log.AppendLine($"Clock.Get_Second()");
return 0m;
}
public string Get_Time()
{
this.log.AppendLine($"Clock.Get_Time()");
return string.Empty;
}
public string Get_WeekDay()
{
this.log.AppendLine($"Clock.Get_WeekDay()");
return string.Empty;
}
public decimal Get_Year()
{
this.log.AppendLine($"Clock.Get_Year()");
return 0m;
}
}
internal sealed class LoggingControlsLibrary : IControlsLibrary
{
private readonly StringBuilder log;
public LoggingControlsLibrary(StringBuilder log)
{
this.log = log;
}
public event Action ButtonClicked;
public event Action TextTyped;
public string Get_LastClickedButton()
{
this.log.AppendLine($"Controls.Get_LastClickedButton()");
return string.Empty;
}
public string Get_LastTypedTextBox()
{
this.log.AppendLine($"Controls.Get_LastTypedTextBox()");
return string.Empty;
}
public string AddButton(string caption, decimal left, decimal top)
{
this.log.AppendLine($"Controls.AddButton(caption: '{caption}', left: '{left}', top: '{top}')");
return string.Empty;
}
public string AddMultiLineTextBox(decimal left, decimal top)
{
this.log.AppendLine($"Controls.AddMultiLineTextBox(left: '{left}', top: '{top}')");
return string.Empty;
}
public string AddTextBox(decimal left, decimal top)
{
this.log.AppendLine($"Controls.AddTextBox(left: '{left}', top: '{top}')");
return string.Empty;
}
public string GetButtonCaption(string buttonName)
{
this.log.AppendLine($"Controls.GetButtonCaption(buttonName: '{buttonName}')");
return string.Empty;
}
public string GetTextBoxText(string textBoxName)
{
this.log.AppendLine($"Controls.GetTextBoxText(textBoxName: '{textBoxName}')");
return string.Empty;
}
public void HideControl(string controlName)
{
this.log.AppendLine($"Controls.HideControl(controlName: '{controlName}')");
}
public void Move(string control, decimal x, decimal y)
{
this.log.AppendLine($"Controls.Move(control: '{control}', x: '{x}', y: '{y}')");
}
public void Remove(string controlName)
{
this.log.AppendLine($"Controls.Remove(controlName: '{controlName}')");
}
public void SetButtonCaption(string buttonName, string caption)
{
this.log.AppendLine($"Controls.SetButtonCaption(buttonName: '{buttonName}', caption: '{caption}')");
}
public void SetSize(string control, decimal width, decimal height)
{
this.log.AppendLine($"Controls.SetSize(control: '{control}', width: '{width}', height: '{height}')");
}
public void SetTextBoxText(string textBoxName, string text)
{
this.log.AppendLine($"Controls.SetTextBoxText(textBoxName: '{textBoxName}', text: '{text}')");
}
public void ShowControl(string controlName)
{
this.log.AppendLine($"Controls.ShowControl(controlName: '{controlName}')");
}
}
internal sealed class LoggingDesktopLibrary : IDesktopLibrary
{
private readonly StringBuilder log;
public LoggingDesktopLibrary(StringBuilder log)
{
this.log = log;
}
}
internal sealed class LoggingDictionaryLibrary : IDictionaryLibrary
{
private readonly StringBuilder log;
public LoggingDictionaryLibrary(StringBuilder log)
{
this.log = log;
}
}
internal sealed class LoggingFileLibrary : IFileLibrary
{
private readonly StringBuilder log;
public LoggingFileLibrary(StringBuilder log)
{
this.log = log;
}
public string Get_LastError()
{
this.log.AppendLine($"File.Get_LastError()");
return string.Empty;
}
public void Set_LastError(string value)
{
this.log.AppendLine($"File.Set_LastError('{value}')");
}
public Task<string> AppendContents(string filePath, string contents)
{
this.log.AppendLine($"File.AppendContents(filePath: '{filePath}', contents: '{contents}')");
return Task.FromResult(string.Empty);
}
public Task<string> CopyFile(string sourceFilePath, string destinationFilePath)
{
this.log.AppendLine($"File.CopyFile(sourceFilePath: '{sourceFilePath}', destinationFilePath: '{destinationFilePath}')");
return Task.FromResult(string.Empty);
}
public Task<string> CreateDirectory(string directoryPath)
{
this.log.AppendLine($"File.CreateDirectory(directoryPath: '{directoryPath}')");
return Task.FromResult(string.Empty);
}
public Task<string> DeleteDirectory(string directoryPath)
{
this.log.AppendLine($"File.DeleteDirectory(directoryPath: '{directoryPath}')");
return Task.FromResult(string.Empty);
}
public Task<string> DeleteFile(string filePath)
{
this.log.AppendLine($"File.DeleteFile(filePath: '{filePath}')");
return Task.FromResult(string.Empty);
}
public Task<BaseValue> GetDirectories(string directoryPath)
{
this.log.AppendLine($"File.GetDirectories(directoryPath: '{directoryPath}')");
return Task.FromResult(StringValue.Create(string.Empty));
}
public Task<BaseValue> GetFiles(string directoryPath)
{
this.log.AppendLine($"File.GetFiles(directoryPath: '{directoryPath}')");
return Task.FromResult(StringValue.Create(string.Empty));
}
public Task<BaseValue> GetTemporaryFilePath()
{
this.log.AppendLine($"File.GetTemporaryFilePath()");
return Task.FromResult(StringValue.Create(string.Empty));
}
public Task<string> InsertLine(string filePath, decimal lineNumber, string contents)
{
this.log.AppendLine($"File.InsertLine(filePath: '{filePath}', lineNumber: '{lineNumber}', contents: '{contents}')");
return Task.FromResult(string.Empty);
}
public Task<BaseValue> ReadContents(string filePath)
{
this.log.AppendLine($"File.ReadContents(filePath: '{filePath}')");
return Task.FromResult(StringValue.Create(string.Empty));
}
public Task<BaseValue> ReadLine(string filePath, decimal lineNumber)
{
this.log.AppendLine($"File.ReadLine(filePath: '{filePath}', lineNumber: '{lineNumber}')");
return Task.FromResult(StringValue.Create(string.Empty));
}
public Task<string> WriteContents(string filePath, string contents)
{
this.log.AppendLine($"File.WriteContents(filePath: '{filePath}', contents: '{contents}')");
return Task.FromResult(string.Empty);
}
public Task<string> WriteLine(string filePath, decimal lineNumber, string contents)
{
this.log.AppendLine($"File.WriteLine(filePath: '{filePath}', lineNumber: '{lineNumber}', contents: '{contents}')");
return Task.FromResult(string.Empty);
}
}
internal sealed class LoggingFlickrLibrary : IFlickrLibrary
{
private readonly StringBuilder log;
public LoggingFlickrLibrary(StringBuilder log)
{
this.log = log;
}
}
internal sealed class LoggingGraphicsWindowLibrary : IGraphicsWindowLibrary
{
private readonly StringBuilder log;
public LoggingGraphicsWindowLibrary(StringBuilder log)
{
this.log = log;
}
public event Action KeyDown;
public event Action KeyUp;
public event Action MouseDown;
public event Action MouseMove;
public event Action MouseUp;
public event Action TextInput;
public string Get_BackgroundColor()
{
this.log.AppendLine($"GraphicsWindow.Get_BackgroundColor()");
return string.Empty;
}
public void Set_BackgroundColor(string value)
{
this.log.AppendLine($"GraphicsWindow.Set_BackgroundColor('{value}')");
}
public string Get_BrushColor()
{
this.log.AppendLine($"GraphicsWindow.Get_BrushColor()");
return string.Empty;
}
public void Set_BrushColor(string value)
{
this.log.AppendLine($"GraphicsWindow.Set_BrushColor('{value}')");
}
public bool Get_FontBold()
{
this.log.AppendLine($"GraphicsWindow.Get_FontBold()");
return false;
}
public void Set_FontBold(bool value)
{
this.log.AppendLine($"GraphicsWindow.Set_FontBold('{value}')");
}
public bool Get_FontItalic()
{
this.log.AppendLine($"GraphicsWindow.Get_FontItalic()");
return false;
}
public void Set_FontItalic(bool value)
{
this.log.AppendLine($"GraphicsWindow.Set_FontItalic('{value}')");
}
public string Get_FontName()
{
this.log.AppendLine($"GraphicsWindow.Get_FontName()");
return string.Empty;
}
public void Set_FontName(string value)
{
this.log.AppendLine($"GraphicsWindow.Set_FontName('{value}')");
}
public decimal Get_FontSize()
{
this.log.AppendLine($"GraphicsWindow.Get_FontSize()");
return 0m;
}
public void Set_FontSize(decimal value)
{
this.log.AppendLine($"GraphicsWindow.Set_FontSize('{value}')");
}
public Task<decimal> Get_Height()
{
this.log.AppendLine($"GraphicsWindow.Get_Height()");
return Task.FromResult(0m);
}
public Task Set_Height(decimal value)
{
this.log.AppendLine($"GraphicsWindow.Set_Height('{value}')");
return Task.CompletedTask;
}
public string Get_LastKey()
{
this.log.AppendLine($"GraphicsWindow.Get_LastKey()");
return string.Empty;
}
public string Get_LastText()
{
this.log.AppendLine($"GraphicsWindow.Get_LastText()");
return string.Empty;
}
public decimal Get_MouseX()
{
this.log.AppendLine($"GraphicsWindow.Get_MouseX()");
return 0m;
}
public decimal Get_MouseY()
{
this.log.AppendLine($"GraphicsWindow.Get_MouseY()");
return 0m;
}
public string Get_PenColor()
{
this.log.AppendLine($"GraphicsWindow.Get_PenColor()");
return string.Empty;
}
public void Set_PenColor(string value)
{
this.log.AppendLine($"GraphicsWindow.Set_PenColor('{value}')");
}
public decimal Get_PenWidth()
{
this.log.AppendLine($"GraphicsWindow.Get_PenWidth()");
return 0m;
}
public void Set_PenWidth(decimal value)
{
this.log.AppendLine($"GraphicsWindow.Set_PenWidth('{value}')");
}
public string Get_Title()
{
this.log.AppendLine($"GraphicsWindow.Get_Title()");
return string.Empty;
}
public void Set_Title(string value)
{
this.log.AppendLine($"GraphicsWindow.Set_Title('{value}')");
}
public Task<decimal> Get_Width()
{
this.log.AppendLine($"GraphicsWindow.Get_Width()");
return Task.FromResult(0m);
}
public Task Set_Width(decimal value)
{
this.log.AppendLine($"GraphicsWindow.Set_Width('{value}')");
return Task.CompletedTask;
}
public void Clear()
{
this.log.AppendLine($"GraphicsWindow.Clear()");
}
public void DrawBoundText(decimal x, decimal y, decimal width, string text)
{
this.log.AppendLine($"GraphicsWindow.DrawBoundText(x: '{x}', y: '{y}', width: '{width}', text: '{text}')");
}
public void DrawEllipse(decimal x, decimal y, decimal width, decimal height)
{
this.log.AppendLine($"GraphicsWindow.DrawEllipse(x: '{x}', y: '{y}', width: '{width}', height: '{height}')");
}
public void DrawImage(string imageName, decimal x, decimal y)
{
this.log.AppendLine($"GraphicsWindow.DrawImage(imageName: '{imageName}', x: '{x}', y: '{y}')");
}
public void DrawLine(decimal x1, decimal y1, decimal x2, decimal y2)
{
this.log.AppendLine($"GraphicsWindow.DrawLine(x1: '{x1}', y1: '{y1}', x2: '{x2}', y2: '{y2}')");
}
public void DrawRectangle(decimal x, decimal y, decimal width, decimal height)
{
this.log.AppendLine($"GraphicsWindow.DrawRectangle(x: '{x}', y: '{y}', width: '{width}', height: '{height}')");
}
public void DrawResizedImage(string imageName, decimal x, decimal y, decimal width, decimal height)
{
this.log.AppendLine($"GraphicsWindow.DrawResizedImage(imageName: '{imageName}', x: '{x}', y: '{y}', width: '{width}', height: '{height}')");
}
public void DrawText(decimal x, decimal y, string text)
{
this.log.AppendLine($"GraphicsWindow.DrawText(x: '{x}', y: '{y}', text: '{text}')");
}
public void DrawTriangle(decimal x1, decimal y1, decimal x2, decimal y2, decimal x3, decimal y3)
{
this.log.AppendLine($"GraphicsWindow.DrawTriangle(x1: '{x1}', y1: '{y1}', x2: '{x2}', y2: '{y2}', x3: '{x3}', y3: '{y3}')");
}
public void FillEllipse(decimal x, decimal y, decimal width, decimal height)
{
this.log.AppendLine($"GraphicsWindow.FillEllipse(x: '{x}', y: '{y}', width: '{width}', height: '{height}')");
}
public void FillRectangle(decimal x, decimal y, decimal width, decimal height)
{
this.log.AppendLine($"GraphicsWindow.FillRectangle(x: '{x}', y: '{y}', width: '{width}', height: '{height}')");
}
public void FillTriangle(decimal x1, decimal y1, decimal x2, decimal y2, decimal x3, decimal y3)
{
this.log.AppendLine($"GraphicsWindow.FillTriangle(x1: '{x1}', y1: '{y1}', x2: '{x2}', y2: '{y2}', x3: '{x3}', y3: '{y3}')");
}
public string GetColorFromRGB(decimal red, decimal green, decimal blue)
{
this.log.AppendLine($"GraphicsWindow.GetColorFromRGB(red: '{red}', green: '{green}', blue: '{blue}')");
return string.Empty;
}
public string GetRandomColor()
{
this.log.AppendLine($"GraphicsWindow.GetRandomColor()");
return string.Empty;
}
public void Hide()
{
this.log.AppendLine($"GraphicsWindow.Hide()");
}
public void SetPixel(decimal x, decimal y, string color)
{
this.log.AppendLine($"GraphicsWindow.SetPixel(x: '{x}', y: '{y}', color: '{color}')");
}
public void Show()
{
this.log.AppendLine($"GraphicsWindow.Show()");
}
public Task ShowMessage(string text, string title)
{
this.log.AppendLine($"GraphicsWindow.ShowMessage(text: '{text}', title: '{title}')");
return Task.CompletedTask;
}
}
internal sealed class LoggingImageListLibrary : IImageListLibrary
{
private readonly StringBuilder log;
public LoggingImageListLibrary(StringBuilder log)
{
this.log = log;
}
public decimal GetHeightOfImage(string imageName)
{
this.log.AppendLine($"ImageList.GetHeightOfImage(imageName: '{imageName}')");
return 0m;
}
public decimal GetWidthOfImage(string imageName)
{
this.log.AppendLine($"ImageList.GetWidthOfImage(imageName: '{imageName}')");
return 0m;
}
public Task<string> LoadImage(string fileNameOrUrl)
{
this.log.AppendLine($"ImageList.LoadImage(fileNameOrUrl: '{fileNameOrUrl}')");
return Task.FromResult(string.Empty);
}
}
internal sealed class LoggingMathLibrary : IMathLibrary
{
private readonly StringBuilder log;
public LoggingMathLibrary(StringBuilder log)
{
this.log = log;
}
public decimal Get_Pi()
{
this.log.AppendLine($"Math.Get_Pi()");
return 0m;
}
public decimal Abs(decimal number)
{
this.log.AppendLine($"Math.Abs(number: '{number}')");
return 0m;
}
public decimal ArcCos(decimal cosValue)
{
this.log.AppendLine($"Math.ArcCos(cosValue: '{cosValue}')");
return 0m;
}
public decimal ArcSin(decimal sinValue)
{
this.log.AppendLine($"Math.ArcSin(sinValue: '{sinValue}')");
return 0m;
}
public decimal ArcTan(decimal tanValue)
{
this.log.AppendLine($"Math.ArcTan(tanValue: '{tanValue}')");
return 0m;
}
public decimal Ceiling(decimal number)
{
this.log.AppendLine($"Math.Ceiling(number: '{number}')");
return 0m;
}
public decimal Cos(decimal angle)
{
this.log.AppendLine($"Math.Cos(angle: '{angle}')");
return 0m;
}
public decimal Floor(decimal number)
{
this.log.AppendLine($"Math.Floor(number: '{number}')");
return 0m;
}
public decimal GetDegrees(decimal angle)
{
this.log.AppendLine($"Math.GetDegrees(angle: '{angle}')");
return 0m;
}
public decimal GetRadians(decimal angle)
{
this.log.AppendLine($"Math.GetRadians(angle: '{angle}')");
return 0m;
}
public decimal GetRandomNumber(decimal maxNumber)
{
this.log.AppendLine($"Math.GetRandomNumber(maxNumber: '{maxNumber}')");
return 0m;
}
public decimal Log(decimal number)
{
this.log.AppendLine($"Math.Log(number: '{number}')");
return 0m;
}
public decimal Max(decimal number1, decimal number2)
{
this.log.AppendLine($"Math.Max(number1: '{number1}', number2: '{number2}')");
return 0m;
}
public decimal Min(decimal number1, decimal number2)
{
this.log.AppendLine($"Math.Min(number1: '{number1}', number2: '{number2}')");
return 0m;
}
public decimal NaturalLog(decimal number)
{
this.log.AppendLine($"Math.NaturalLog(number: '{number}')");
return 0m;
}
public decimal Power(decimal baseNumber, decimal exponent)
{
this.log.AppendLine($"Math.Power(baseNumber: '{baseNumber}', exponent: '{exponent}')");
return 0m;
}
public decimal Remainder(decimal dividend, decimal divisor)
{
this.log.AppendLine($"Math.Remainder(dividend: '{dividend}', divisor: '{divisor}')");
return 0m;
}
public decimal Round(decimal number)
{
this.log.AppendLine($"Math.Round(number: '{number}')");
return 0m;
}
public decimal Sin(decimal angle)
{
this.log.AppendLine($"Math.Sin(angle: '{angle}')");
return 0m;
}
public decimal SquareRoot(decimal number)
{
this.log.AppendLine($"Math.SquareRoot(number: '{number}')");
return 0m;
}
public decimal Tan(decimal angle)
{
this.log.AppendLine($"Math.Tan(angle: '{angle}')");
return 0m;
}
}
internal sealed class LoggingMouseLibrary : IMouseLibrary
{
private readonly StringBuilder log;
public LoggingMouseLibrary(StringBuilder log)
{
this.log = log;
}
public bool Get_IsLeftButtonDown()
{
this.log.AppendLine($"Mouse.Get_IsLeftButtonDown()");
return false;
}
public bool Get_IsRightButtonDown()
{
this.log.AppendLine($"Mouse.Get_IsRightButtonDown()");
return false;
}
public decimal Get_MouseX()
{
this.log.AppendLine($"Mouse.Get_MouseX()");
return 0m;
}
public decimal Get_MouseY()
{
this.log.AppendLine($"Mouse.Get_MouseY()");
return 0m;
}
public void HideCursor()
{
this.log.AppendLine($"Mouse.HideCursor()");
}
public void ShowCursor()
{
this.log.AppendLine($"Mouse.ShowCursor()");
}
}
internal sealed class LoggingNetworkLibrary : INetworkLibrary
{
private readonly StringBuilder log;
public LoggingNetworkLibrary(StringBuilder log)
{
this.log = log;
}
public Task<string> DownloadFile(string url)
{
this.log.AppendLine($"Network.DownloadFile(url: '{url}')");
return Task.FromResult(string.Empty);
}
public Task<string> GetWebPageContents(string url)
{
this.log.AppendLine($"Network.GetWebPageContents(url: '{url}')");
return Task.FromResult(string.Empty);
}
}
internal sealed class LoggingProgramLibrary : IProgramLibrary
{
private readonly StringBuilder log;
public LoggingProgramLibrary(StringBuilder log)
{
this.log = log;
}
public Task Delay(decimal milliSeconds)
{
this.log.AppendLine($"Program.Delay(milliSeconds: '{milliSeconds}')");
return Task.CompletedTask;
}
public void End()
{
this.log.AppendLine($"Program.End()");
}
public void Pause()
{
this.log.AppendLine($"Program.Pause()");
}
}
internal sealed class LoggingShapesLibrary : IShapesLibrary
{
private readonly StringBuilder log;
public LoggingShapesLibrary(StringBuilder log)
{
this.log = log;
}
public string AddEllipse(decimal width, decimal height)
{
this.log.AppendLine($"Shapes.AddEllipse(width: '{width}', height: '{height}')");
return string.Empty;
}
public string AddImage(string imageName)
{
this.log.AppendLine($"Shapes.AddImage(imageName: '{imageName}')");
return string.Empty;
}
public string AddLine(decimal x1, decimal y1, decimal x2, decimal y2)
{
this.log.AppendLine($"Shapes.AddLine(x1: '{x1}', y1: '{y1}', x2: '{x2}', y2: '{y2}')");
return string.Empty;
}
public string AddRectangle(decimal width, decimal height)
{
this.log.AppendLine($"Shapes.AddRectangle(width: '{width}', height: '{height}')");
return string.Empty;
}
public string AddText(string text)
{
this.log.AppendLine($"Shapes.AddText(text: '{text}')");
return string.Empty;
}
public string AddTriangle(decimal x1, decimal y1, decimal x2, decimal y2, decimal x3, decimal y3)
{
this.log.AppendLine($"Shapes.AddTriangle(x1: '{x1}', y1: '{y1}', x2: '{x2}', y2: '{y2}', x3: '{x3}', y3: '{y3}')");
return string.Empty;
}
public Task Animate(string shapeName, decimal x, decimal y, decimal duration)
{
this.log.AppendLine($"Shapes.Animate(shapeName: '{shapeName}', x: '{x}', y: '{y}', duration: '{duration}')");
return Task.CompletedTask;
}
public decimal GetLeft(string shapeName)
{
this.log.AppendLine($"Shapes.GetLeft(shapeName: '{shapeName}')");
return 0m;
}
public decimal GetOpacity(string shapeName)
{
this.log.AppendLine($"Shapes.GetOpacity(shapeName: '{shapeName}')");
return 0m;
}
public decimal GetTop(string shapeName)
{
this.log.AppendLine($"Shapes.GetTop(shapeName: '{shapeName}')");
return 0m;
}
public void HideShape(string shapeName)
{
this.log.AppendLine($"Shapes.HideShape(shapeName: '{shapeName}')");
}
public void Move(string shapeName, decimal x, decimal y)
{
this.log.AppendLine($"Shapes.Move(shapeName: '{shapeName}', x: '{x}', y: '{y}')");
}
public void Remove(string shapeName)
{
this.log.AppendLine($"Shapes.Remove(shapeName: '{shapeName}')");
}
public void Rotate(string shapeName, decimal angle)
{
this.log.AppendLine($"Shapes.Rotate(shapeName: '{shapeName}', angle: '{angle}')");
}
public void SetOpacity(string shapeName, decimal level)
{
this.log.AppendLine($"Shapes.SetOpacity(shapeName: '{shapeName}', level: '{level}')");
}
public void SetText(string shapeName, string text)
{
this.log.AppendLine($"Shapes.SetText(shapeName: '{shapeName}', text: '{text}')");
}
public void ShowShape(string shapeName)
{
this.log.AppendLine($"Shapes.ShowShape(shapeName: '{shapeName}')");
}
public void Zoom(string shapeName, decimal scaleX, decimal scaleY)
{
this.log.AppendLine($"Shapes.Zoom(shapeName: '{shapeName}', scaleX: '{scaleX}', scaleY: '{scaleY}')");
}
}
internal sealed class LoggingSoundLibrary : ISoundLibrary
{
private readonly StringBuilder log;
public LoggingSoundLibrary(StringBuilder log)
{
this.log = log;
}
}
internal sealed class LoggingStackLibrary : IStackLibrary
{
private readonly StringBuilder log;
public LoggingStackLibrary(StringBuilder log)
{
this.log = log;
}
public decimal GetCount(string stackName)
{
this.log.AppendLine($"Stack.GetCount(stackName: '{stackName}')");
return 0m;
}
public string PopValue(string stackName)
{
this.log.AppendLine($"Stack.PopValue(stackName: '{stackName}')");
return string.Empty;
}
public void PushValue(string stackName, string value)
{
this.log.AppendLine($"Stack.PushValue(stackName: '{stackName}', value: '{value}')");
}
}
internal sealed class LoggingTextLibrary : ITextLibrary
{
private readonly StringBuilder log;
public LoggingTextLibrary(StringBuilder log)
{
this.log = log;
}
public string Append(string text1, string text2)
{
this.log.AppendLine($"Text.Append(text1: '{text1}', text2: '{text2}')");
return string.Empty;
}
public string ConvertToLowerCase(string text)
{
this.log.AppendLine($"Text.ConvertToLowerCase(text: '{text}')");
return string.Empty;
}
public string ConvertToUpperCase(string text)
{
this.log.AppendLine($"Text.ConvertToUpperCase(text: '{text}')");
return string.Empty;
}
public bool EndsWith(string text, string subText)
{
this.log.AppendLine($"Text.EndsWith(text: '{text}', subText: '{subText}')");
return false;
}
public string GetCharacter(decimal characterCode)
{
this.log.AppendLine($"Text.GetCharacter(characterCode: '{characterCode}')");
return string.Empty;
}
public decimal GetCharacterCode(string character)
{
this.log.AppendLine($"Text.GetCharacterCode(character: '{character}')");
return 0m;
}
public decimal GetIndexOf(string text, string subText)
{
this.log.AppendLine($"Text.GetIndexOf(text: '{text}', subText: '{subText}')");
return 0m;
}
public decimal GetLength(string text)
{
this.log.AppendLine($"Text.GetLength(text: '{text}')");
return 0m;
}
public string GetSubText(string text, decimal start, decimal length)
{
this.log.AppendLine($"Text.GetSubText(text: '{text}', start: '{start}', length: '{length}')");
return string.Empty;
}
public string GetSubTextToEnd(string text, decimal start)
{
this.log.AppendLine($"Text.GetSubTextToEnd(text: '{text}', start: '{start}')");
return string.Empty;
}
public bool IsSubText(string text, string subText)
{
this.log.AppendLine($"Text.IsSubText(text: '{text}', subText: '{subText}')");
return false;
}
public bool StartsWith(string text, string subText)
{
this.log.AppendLine($"Text.StartsWith(text: '{text}', subText: '{subText}')");
return false;
}
}
internal sealed class LoggingTextWindowLibrary : ITextWindowLibrary
{
private readonly StringBuilder log;
public LoggingTextWindowLibrary(StringBuilder log)
{
this.log = log;
}
public string Get_BackgroundColor()
{
this.log.AppendLine($"TextWindow.Get_BackgroundColor()");
return string.Empty;
}
public void Set_BackgroundColor(string value)
{
this.log.AppendLine($"TextWindow.Set_BackgroundColor('{value}')");
}
public string Get_ForegroundColor()
{
this.log.AppendLine($"TextWindow.Get_ForegroundColor()");
return string.Empty;
}
public void Set_ForegroundColor(string value)
{
this.log.AppendLine($"TextWindow.Set_ForegroundColor('{value}')");
}
public string Get_Title()
{
this.log.AppendLine($"TextWindow.Get_Title()");
return string.Empty;
}
public void Set_Title(string value)
{
this.log.AppendLine($"TextWindow.Set_Title('{value}')");
}
public void Clear()
{
this.log.AppendLine($"TextWindow.Clear()");
}
public string Read()
{
this.log.AppendLine($"TextWindow.Read()");
return string.Empty;
}
public decimal ReadNumber()
{
this.log.AppendLine($"TextWindow.ReadNumber()");
return 0m;
}
public Task Write(string data)
{
this.log.AppendLine($"TextWindow.Write(data: '{data}')");
return Task.CompletedTask;
}
public Task WriteLine(string data)
{
this.log.AppendLine($"TextWindow.WriteLine(data: '{data}')");
return Task.CompletedTask;
}
}
internal sealed class LoggingTimerLibrary : ITimerLibrary
{
private readonly StringBuilder log;
public LoggingTimerLibrary(StringBuilder log)
{
this.log = log;
}
public event Action Tick;
public decimal Get_Interval()
{
this.log.AppendLine($"Timer.Get_Interval()");
return 0m;
}
public void Set_Interval(decimal value)
{
this.log.AppendLine($"Timer.Set_Interval('{value}')");
}
public void Pause()
{
this.log.AppendLine($"Timer.Pause()");
}
public void Resume()
{
this.log.AppendLine($"Timer.Resume()");
}
}
internal sealed class LoggingTurtleLibrary : ITurtleLibrary
{
private readonly StringBuilder log;
public LoggingTurtleLibrary(StringBuilder log)
{
this.log = log;
}
public decimal Get_Angle()
{
this.log.AppendLine($"Turtle.Get_Angle()");
return 0m;
}
public void Set_Angle(decimal value)
{
this.log.AppendLine($"Turtle.Set_Angle('{value}')");
}
public decimal Get_Speed()
{
this.log.AppendLine($"Turtle.Get_Speed()");
return 0m;
}
public void Set_Speed(decimal value)
{
this.log.AppendLine($"Turtle.Set_Speed('{value}')");
}
public decimal Get_X()
{
this.log.AppendLine($"Turtle.Get_X()");
return 0m;
}
public void Set_X(decimal value)
{
this.log.AppendLine($"Turtle.Set_X('{value}')");
}
public decimal Get_Y()
{
this.log.AppendLine($"Turtle.Get_Y()");
return 0m;
}
public void Set_Y(decimal value)
{
this.log.AppendLine($"Turtle.Set_Y('{value}')");
}
public void Hide()
{
this.log.AppendLine($"Turtle.Hide()");
}
public Task Move(decimal distance)
{
this.log.AppendLine($"Turtle.Move(distance: '{distance}')");
return Task.CompletedTask;
}
public Task MoveTo(decimal x, decimal y)
{
this.log.AppendLine($"Turtle.MoveTo(x: '{x}', y: '{y}')");
return Task.CompletedTask;
}
public void PenDown()
{
this.log.AppendLine($"Turtle.PenDown()");
}
public void PenUp()
{
this.log.AppendLine($"Turtle.PenUp()");
}
public void Show()
{
this.log.AppendLine($"Turtle.Show()");
}
public Task Turn(decimal angle)
{
this.log.AppendLine($"Turtle.Turn(angle: '{angle}')");
return Task.CompletedTask;
}
public Task TurnLeft()
{
this.log.AppendLine($"Turtle.TurnLeft()");
return Task.CompletedTask;
}
public Task TurnRight()
{
this.log.AppendLine($"Turtle.TurnRight()");
return Task.CompletedTask;
}
}
internal sealed class LoggingEngineLibraries : IEngineLibraries
{
public LoggingEngineLibraries(StringBuilder log)
{
this.Array = new LoggingArrayLibrary(log);
this.Clock = new LoggingClockLibrary(log);
this.Controls = new LoggingControlsLibrary(log);
this.Desktop = new LoggingDesktopLibrary(log);
this.Dictionary = new LoggingDictionaryLibrary(log);
this.File = new LoggingFileLibrary(log);
this.Flickr = new LoggingFlickrLibrary(log);
this.GraphicsWindow = new LoggingGraphicsWindowLibrary(log);
this.ImageList = new LoggingImageListLibrary(log);
this.Math = new LoggingMathLibrary(log);
this.Mouse = new LoggingMouseLibrary(log);
this.Network = new LoggingNetworkLibrary(log);
this.Program = new LoggingProgramLibrary(log);
this.Shapes = new LoggingShapesLibrary(log);
this.Sound = new LoggingSoundLibrary(log);
this.Stack = new LoggingStackLibrary(log);
this.Text = new LoggingTextLibrary(log);
this.TextWindow = new LoggingTextWindowLibrary(log);
this.Timer = new LoggingTimerLibrary(log);
this.Turtle = new LoggingTurtleLibrary(log);
}
public IArrayLibrary Array { get; private set; }
public IClockLibrary Clock { get; private set; }
public IControlsLibrary Controls { get; private set; }
public IDesktopLibrary Desktop { get; private set; }
public IDictionaryLibrary Dictionary { get; private set; }
public IFileLibrary File { get; private set; }
public IFlickrLibrary Flickr { get; private set; }
public IGraphicsWindowLibrary GraphicsWindow { get; private set; }
public IImageListLibrary ImageList { get; private set; }
public IMathLibrary Math { get; private set; }
public IMouseLibrary Mouse { get; private set; }
public INetworkLibrary Network { get; private set; }
public IProgramLibrary Program { get; private set; }
public IShapesLibrary Shapes { get; private set; }
public ISoundLibrary Sound { get; private set; }
public IStackLibrary Stack { get; private set; }
public ITextLibrary Text { get; private set; }
public ITextWindowLibrary TextWindow { get; private set; }
public ITimerLibrary Timer { get; private set; }
public ITurtleLibrary Turtle { get; private set; }
}
#pragma warning restore CS0067 // The event '{0}' is never used
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Text.RegularExpressions;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Transactions;
/// <summary>
/// Managed environment. Acts as a gateway for native code.
/// </summary>
internal static class ExceptionUtils
{
/** NoClassDefFoundError fully-qualified class name which is important during startup phase. */
private const string ClsNoClsDefFoundErr = "java.lang.NoClassDefFoundError";
/** NoSuchMethodError fully-qualified class name which is important during startup phase. */
private const string ClsNoSuchMthdErr = "java.lang.NoSuchMethodError";
/** InteropCachePartialUpdateException. */
private const string ClsCachePartialUpdateErr = "org.apache.ignite.internal.processors.platform.cache.PlatformCachePartialUpdateException";
/** Map with predefined exceptions. */
private static readonly IDictionary<string, ExceptionFactory> Exs = new Dictionary<string, ExceptionFactory>();
/** Inner class regex. */
private static readonly Regex InnerClassRegex = new Regex(@"class ([^\s]+): (.*)", RegexOptions.Compiled);
/// <summary>
/// Static initializer.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline",
Justification = "Readability")]
static ExceptionUtils()
{
// Common Java exceptions mapped to common .NET exceptions.
Exs["java.lang.IllegalArgumentException"] = (c, m, e, i) => new ArgumentException(m, e);
Exs["java.lang.IllegalStateException"] = (c, m, e, i) => new InvalidOperationException(m, e);
Exs["java.lang.UnsupportedOperationException"] = (c, m, e, i) => new NotSupportedException(m, e);
Exs["java.lang.InterruptedException"] = (c, m, e, i) => new ThreadInterruptedException(m, e);
// Generic Ignite exceptions.
Exs["org.apache.ignite.IgniteException"] = (c, m, e, i) => new IgniteException(m, e);
Exs["org.apache.ignite.IgniteCheckedException"] = (c, m, e, i) => new IgniteException(m, e);
Exs["org.apache.ignite.IgniteClientDisconnectedException"] = (c, m, e, i) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask);
Exs["org.apache.ignite.internal.IgniteClientDisconnectedCheckedException"] = (c, m, e, i) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask);
Exs["org.apache.ignite.binary.BinaryObjectException"] = (c, m, e, i) => new BinaryObjectException(m, e);
// Cluster exceptions.
Exs["org.apache.ignite.cluster.ClusterGroupEmptyException"] = (c, m, e, i) => new ClusterGroupEmptyException(m, e);
Exs["org.apache.ignite.cluster.ClusterTopologyException"] = (c, m, e, i) => new ClusterTopologyException(m, e);
// Compute exceptions.
Exs["org.apache.ignite.compute.ComputeExecutionRejectedException"] = (c, m, e, i) => new ComputeExecutionRejectedException(m, e);
Exs["org.apache.ignite.compute.ComputeJobFailoverException"] = (c, m, e, i) => new ComputeJobFailoverException(m, e);
Exs["org.apache.ignite.compute.ComputeTaskCancelledException"] = (c, m, e, i) => new ComputeTaskCancelledException(m, e);
Exs["org.apache.ignite.compute.ComputeTaskTimeoutException"] = (c, m, e, i) => new ComputeTaskTimeoutException(m, e);
Exs["org.apache.ignite.compute.ComputeUserUndeclaredException"] = (c, m, e, i) => new ComputeUserUndeclaredException(m, e);
// Cache exceptions.
Exs["javax.cache.CacheException"] = (c, m, e, i) => new CacheException(m, e);
Exs["javax.cache.integration.CacheLoaderException"] = (c, m, e, i) => new CacheStoreException(m, e);
Exs["javax.cache.integration.CacheWriterException"] = (c, m, e, i) => new CacheStoreException(m, e);
Exs["javax.cache.processor.EntryProcessorException"] = (c, m, e, i) => new CacheEntryProcessorException(m, e);
Exs["org.apache.ignite.cache.CacheAtomicUpdateTimeoutException"] = (c, m, e, i) => new CacheAtomicUpdateTimeoutException(m, e);
// Transaction exceptions.
Exs["org.apache.ignite.transactions.TransactionOptimisticException"] = (c, m, e, i) => new TransactionOptimisticException(m, e);
Exs["org.apache.ignite.transactions.TransactionTimeoutException"] = (c, m, e, i) => new TransactionTimeoutException(m, e);
Exs["org.apache.ignite.transactions.TransactionRollbackException"] = (c, m, e, i) => new TransactionRollbackException(m, e);
Exs["org.apache.ignite.transactions.TransactionHeuristicException"] = (c, m, e, i) => new TransactionHeuristicException(m, e);
Exs["org.apache.ignite.transactions.TransactionDeadlockException"] = (c, m, e, i) => new TransactionDeadlockException(m, e);
// Security exceptions.
Exs["org.apache.ignite.IgniteAuthenticationException"] = (c, m, e, i) => new SecurityException(m, e);
Exs["org.apache.ignite.plugin.security.GridSecurityException"] = (c, m, e, i) => new SecurityException(m, e);
// Future exceptions
Exs["org.apache.ignite.lang.IgniteFutureCancelledException"] = (c, m, e, i) => new IgniteFutureCancelledException(m, e);
Exs["org.apache.ignite.internal.IgniteFutureCancelledCheckedException"] = (c, m, e, i) => new IgniteFutureCancelledException(m, e);
}
/// <summary>
/// Creates exception according to native code class and message.
/// </summary>
/// <param name="ignite">The ignite.</param>
/// <param name="clsName">Exception class name.</param>
/// <param name="msg">Exception message.</param>
/// <param name="stackTrace">Native stack trace.</param>
/// <param name="reader">Error data reader.</param>
/// <param name="innerException">Inner exception.</param>
/// <returns>Exception.</returns>
public static Exception GetException(Ignite ignite, string clsName, string msg, string stackTrace,
BinaryReader reader = null, Exception innerException = null)
{
// Set JavaException as inner only if there is no InnerException.
if (innerException == null)
innerException = new JavaException(clsName, msg, stackTrace);
ExceptionFactory ctor;
if (Exs.TryGetValue(clsName, out ctor))
{
var match = InnerClassRegex.Match(msg ?? string.Empty);
ExceptionFactory innerCtor;
if (match.Success && Exs.TryGetValue(match.Groups[1].Value, out innerCtor))
{
return ctor(clsName, msg,
innerCtor(match.Groups[1].Value, match.Groups[2].Value, innerException, ignite), ignite);
}
return ctor(clsName, msg, innerException, ignite);
}
if (ClsNoClsDefFoundErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
return new IgniteException("Java class is not found (did you set IGNITE_HOME environment " +
"variable?): " + msg, innerException);
if (ClsNoSuchMthdErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
return new IgniteException("Java class method is not found (did you set IGNITE_HOME environment " +
"variable?): " + msg, innerException);
if (ClsCachePartialUpdateErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
return ProcessCachePartialUpdateException(ignite, msg, stackTrace, reader);
// Predefined mapping not found - check plugins.
if (ignite != null)
{
ctor = ignite.PluginProcessor.GetExceptionMapping(clsName);
if (ctor != null)
{
return ctor(clsName, msg, innerException, ignite);
}
}
// Return default exception.
return new IgniteException(string.Format("Java exception occurred [class={0}, message={1}]", clsName, msg),
innerException);
}
/// <summary>
/// Process cache partial update exception.
/// </summary>
/// <param name="ignite">The ignite.</param>
/// <param name="msg">Message.</param>
/// <param name="stackTrace">Stack trace.</param>
/// <param name="reader">Reader.</param>
/// <returns>CachePartialUpdateException.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static Exception ProcessCachePartialUpdateException(Ignite ignite, string msg, string stackTrace,
BinaryReader reader)
{
if (reader == null)
return new CachePartialUpdateException(msg, new IgniteException("Failed keys are not available."));
bool dataExists = reader.ReadBoolean();
Debug.Assert(dataExists);
if (reader.ReadBoolean())
{
bool keepBinary = reader.ReadBoolean();
BinaryReader keysReader = reader.Marshaller.StartUnmarshal(reader.Stream, keepBinary);
try
{
return new CachePartialUpdateException(msg, ReadNullableList(keysReader));
}
catch (Exception e)
{
// Failed to deserialize data.
return new CachePartialUpdateException(msg, e);
}
}
// Was not able to write keys.
string innerErrCls = reader.ReadString();
string innerErrMsg = reader.ReadString();
Exception innerErr = GetException(ignite, innerErrCls, innerErrMsg, stackTrace);
return new CachePartialUpdateException(msg, innerErr);
}
/// <summary>
/// Create JVM initialization exception.
/// </summary>
/// <param name="clsName">Class name.</param>
/// <param name="msg">Message.</param>
/// <param name="stackTrace">Stack trace.</param>
/// <returns>Exception.</returns>
[ExcludeFromCodeCoverage] // Covered by a test in a separate process.
public static Exception GetJvmInitializeException(string clsName, string msg, string stackTrace)
{
if (clsName != null)
return new IgniteException("Failed to initialize JVM.", GetException(null, clsName, msg, stackTrace));
if (msg != null)
return new IgniteException("Failed to initialize JVM: " + msg + "\n" + stackTrace);
return new IgniteException("Failed to initialize JVM.");
}
/// <summary>
/// Reads nullable list.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>List.</returns>
private static List<object> ReadNullableList(BinaryReader reader)
{
if (!reader.ReadBoolean())
return null;
var size = reader.ReadInt();
var list = new List<object>(size);
for (int i = 0; i < size; i++)
list.Add(reader.ReadObject<object>());
return list;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.InteropServices;
namespace HFATest
{
public struct Config
{
public const string hfaType = "nested";
public const string dllType = "native_cpp";
public const string floatType = "f32";
public const string DllName = "hfa" + "_" + hfaType + "_" + floatType + "_" + dllType;
}
public class TestMan
{
//---------------------------------------------
// Init Methods
// ---------------------------------------------------
[DllImport(Config.DllName, EntryPoint = "init_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern void Init_HFA01(out HFA01 hfa);
[DllImport(Config.DllName, EntryPoint = "init_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern void Init_HFA02(out HFA02 hfa);
[DllImport(Config.DllName, EntryPoint = "init_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern void Init_HFA03(out HFA03 hfa);
[DllImport(Config.DllName, EntryPoint = "init_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern void Init_HFA05(out HFA05 hfa);
[DllImport(Config.DllName, EntryPoint = "init_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern void Init_HFA08(out HFA08 hfa);
[DllImport(Config.DllName, EntryPoint = "init_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern void Init_HFA11(out HFA11 hfa);
[DllImport(Config.DllName, EntryPoint = "init_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern void Init_HFA19(out HFA19 hfa);
// ---------------------------------------------------
// Identity Methods
// ---------------------------------------------------
[DllImport(Config.DllName, EntryPoint = "identity_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA01 Identity_HFA01(HFA01 hfa);
[DllImport(Config.DllName, EntryPoint = "identity_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA02 Identity_HFA02(HFA02 hfa);
[DllImport(Config.DllName, EntryPoint = "identity_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA03 Identity_HFA03(HFA03 hfa);
[DllImport(Config.DllName, EntryPoint = "identity_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA05 Identity_HFA05(HFA05 hfa);
[DllImport(Config.DllName, EntryPoint = "identity_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA08 Identity_HFA08(HFA08 hfa);
[DllImport(Config.DllName, EntryPoint = "identity_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA11 Identity_HFA11(HFA11 hfa);
[DllImport(Config.DllName, EntryPoint = "identity_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA19 Identity_HFA19(HFA19 hfa);
// ---------------------------------------------------
// Get Methods
// ---------------------------------------------------
[DllImport(Config.DllName, EntryPoint = "get_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA01 Get_HFA01();
[DllImport(Config.DllName, EntryPoint = "get_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA02 Get_HFA02();
[DllImport(Config.DllName, EntryPoint = "get_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA03 Get_HFA03();
[DllImport(Config.DllName, EntryPoint = "get_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA05 Get_HFA05();
[DllImport(Config.DllName, EntryPoint = "get_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA08 Get_HFA08();
[DllImport(Config.DllName, EntryPoint = "get_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA11 Get_HFA11();
[DllImport(Config.DllName, EntryPoint = "get_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern HFA19 Get_HFA19();
public static readonly float EXPECTED_SUM_HFA01 = Get_EXPECTED_SUM_HFA01();
public static readonly float EXPECTED_SUM_HFA02 = Get_EXPECTED_SUM_HFA02();
public static readonly float EXPECTED_SUM_HFA03 = Get_EXPECTED_SUM_HFA03();
public static readonly float EXPECTED_SUM_HFA05 = Get_EXPECTED_SUM_HFA05();
public static readonly float EXPECTED_SUM_HFA08 = Get_EXPECTED_SUM_HFA08();
public static readonly float EXPECTED_SUM_HFA11 = Get_EXPECTED_SUM_HFA11();
public static readonly float EXPECTED_SUM_HFA19 = Get_EXPECTED_SUM_HFA19();
[DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Get_EXPECTED_SUM_HFA01();
[DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Get_EXPECTED_SUM_HFA02();
[DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Get_EXPECTED_SUM_HFA03();
[DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Get_EXPECTED_SUM_HFA05();
[DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Get_EXPECTED_SUM_HFA08();
[DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Get_EXPECTED_SUM_HFA11();
[DllImport(Config.DllName, EntryPoint = "get_EXPECTED_SUM_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Get_EXPECTED_SUM_HFA19();
[DllImport(Config.DllName, EntryPoint = "sum_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum_HFA01(HFA01 hfa);
[DllImport(Config.DllName, EntryPoint = "sum_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum_HFA02(HFA02 hfa);
[DllImport(Config.DllName, EntryPoint = "sum_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum_HFA03(HFA03 hfa);
[DllImport(Config.DllName, EntryPoint = "sum_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum_HFA05(HFA05 hfa);
[DllImport(Config.DllName, EntryPoint = "sum_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum_HFA08(HFA08 hfa);
[DllImport(Config.DllName, EntryPoint = "sum_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum_HFA11(HFA11 hfa);
[DllImport(Config.DllName, EntryPoint = "sum_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum_HFA19(HFA19 hfa);
[DllImport(Config.DllName, EntryPoint = "sum3_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum3_HFA01(float v1, long v2, HFA01 hfa);
[DllImport(Config.DllName, EntryPoint = "sum3_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum3_HFA02(float v1, long v2, HFA02 hfa);
[DllImport(Config.DllName, EntryPoint = "sum3_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum3_HFA03(float v1, long v2, HFA03 hfa);
[DllImport(Config.DllName, EntryPoint = "sum3_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum3_HFA05(float v1, long v2, HFA05 hfa);
[DllImport(Config.DllName, EntryPoint = "sum3_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum3_HFA08(float v1, long v2, HFA08 hfa);
[DllImport(Config.DllName, EntryPoint = "sum3_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum3_HFA11(float v1, long v2, HFA11 hfa);
[DllImport(Config.DllName, EntryPoint = "sum3_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum3_HFA19(float v1, long v2, HFA19 hfa);
[DllImport(Config.DllName, EntryPoint = "sum5_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum5_HFA01(long v1, double v2, int v3, sbyte v4, HFA01 hfa);
[DllImport(Config.DllName, EntryPoint = "sum5_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum5_HFA02(long v1, double v2, int v3, sbyte v4, HFA02 hfa);
[DllImport(Config.DllName, EntryPoint = "sum5_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum5_HFA03(long v1, double v2, int v3, sbyte v4, HFA03 hfa);
[DllImport(Config.DllName, EntryPoint = "sum5_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum5_HFA05(long v1, double v2, int v3, sbyte v4, HFA05 hfa);
[DllImport(Config.DllName, EntryPoint = "sum5_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum5_HFA08(long v1, double v2, int v3, sbyte v4, HFA08 hfa);
[DllImport(Config.DllName, EntryPoint = "sum5_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum5_HFA11(long v1, double v2, int v3, sbyte v4, HFA11 hfa);
[DllImport(Config.DllName, EntryPoint = "sum5_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum5_HFA19(long v1, double v2, int v3, sbyte v4, HFA19 hfa);
[DllImport(Config.DllName, EntryPoint = "sum8_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum8_HFA01(float v1, double v2, long v3, sbyte v4, double v5, HFA01 hfa);
[DllImport(Config.DllName, EntryPoint = "sum8_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum8_HFA02(float v1, double v2, long v3, sbyte v4, double v5, HFA02 hfa);
[DllImport(Config.DllName, EntryPoint = "sum8_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum8_HFA03(float v1, double v2, long v3, sbyte v4, double v5, HFA03 hfa);
[DllImport(Config.DllName, EntryPoint = "sum8_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum8_HFA05(float v1, double v2, long v3, sbyte v4, double v5, HFA05 hfa);
[DllImport(Config.DllName, EntryPoint = "sum8_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum8_HFA08(float v1, double v2, long v3, sbyte v4, double v5, HFA08 hfa);
[DllImport(Config.DllName, EntryPoint = "sum8_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum8_HFA11(float v1, double v2, long v3, sbyte v4, double v5, HFA11 hfa);
[DllImport(Config.DllName, EntryPoint = "sum8_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum8_HFA19(float v1, double v2, long v3, sbyte v4, double v5, HFA19 hfa);
[DllImport(Config.DllName, EntryPoint = "sum11_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum11_HFA01(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA01 hfa);
[DllImport(Config.DllName, EntryPoint = "sum11_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum11_HFA02(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA02 hfa);
[DllImport(Config.DllName, EntryPoint = "sum11_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum11_HFA03(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA03 hfa);
[DllImport(Config.DllName, EntryPoint = "sum11_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum11_HFA05(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA05 hfa);
[DllImport(Config.DllName, EntryPoint = "sum11_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum11_HFA08(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA08 hfa);
[DllImport(Config.DllName, EntryPoint = "sum11_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum11_HFA11(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA11 hfa);
[DllImport(Config.DllName, EntryPoint = "sum11_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum11_HFA19(double v1, float v2, float v3, int v4, float v5, long v6, double v7, float v8, HFA19 hfa);
[DllImport(Config.DllName, EntryPoint = "sum19_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum19_HFA01(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA01 hfa);
[DllImport(Config.DllName, EntryPoint = "sum19_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum19_HFA02(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA02 hfa);
[DllImport(Config.DllName, EntryPoint = "sum19_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum19_HFA03(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA03 hfa);
[DllImport(Config.DllName, EntryPoint = "sum19_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum19_HFA05(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA05 hfa);
[DllImport(Config.DllName, EntryPoint = "sum19_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum19_HFA08(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA08 hfa);
[DllImport(Config.DllName, EntryPoint = "sum19_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum19_HFA11(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA11 hfa);
[DllImport(Config.DllName, EntryPoint = "sum19_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Sum19_HFA19(float v1, double v2, float v3, double v4, float v5, double v6, float v7, double v8, float v9, double v10, float v11, double v12, float v13, HFA19 hfa);
// ---------------------------------------------------
// Average Methods
// ---------------------------------------------------
[DllImport(Config.DllName, EntryPoint = "average_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average_HFA01(HFA01 hfa);
[DllImport(Config.DllName, EntryPoint = "average_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average_HFA02(HFA02 hfa);
[DllImport(Config.DllName, EntryPoint = "average_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average_HFA03(HFA03 hfa);
[DllImport(Config.DllName, EntryPoint = "average_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average_HFA05(HFA05 hfa);
[DllImport(Config.DllName, EntryPoint = "average_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average_HFA08(HFA08 hfa);
[DllImport(Config.DllName, EntryPoint = "average_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average_HFA11(HFA11 hfa);
[DllImport(Config.DllName, EntryPoint = "average_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average_HFA19(HFA19 hfa);
[DllImport(Config.DllName, EntryPoint = "average3_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average3_HFA01(HFA01 hfa1, HFA01 hfa2, HFA01 hfa3);
[DllImport(Config.DllName, EntryPoint = "average3_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average3_HFA02(HFA02 hfa1, HFA02 hfa2, HFA02 hfa3);
[DllImport(Config.DllName, EntryPoint = "average3_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average3_HFA03(HFA03 hfa1, HFA03 hfa2, HFA03 hfa3);
[DllImport(Config.DllName, EntryPoint = "average3_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average3_HFA05(HFA05 hfa1, HFA05 hfa2, HFA05 hfa3);
[DllImport(Config.DllName, EntryPoint = "average3_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average3_HFA08(HFA08 hfa1, HFA08 hfa2, HFA08 hfa3);
[DllImport(Config.DllName, EntryPoint = "average3_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average3_HFA11(HFA11 hfa1, HFA11 hfa2, HFA11 hfa3);
[DllImport(Config.DllName, EntryPoint = "average3_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average3_HFA19(HFA19 hfa1, HFA19 hfa2, HFA19 hfa3);
[DllImport(Config.DllName, EntryPoint = "average5_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average5_HFA01(HFA01 hfa1, HFA01 hfa2, HFA01 hfa3, HFA01 hfa4, HFA01 hfa5);
[DllImport(Config.DllName, EntryPoint = "average5_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average5_HFA02(HFA02 hfa1, HFA02 hfa2, HFA02 hfa3, HFA02 hfa4, HFA02 hfa5);
[DllImport(Config.DllName, EntryPoint = "average5_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average5_HFA03(HFA03 hfa1, HFA03 hfa2, HFA03 hfa3, HFA03 hfa4, HFA03 hfa5);
[DllImport(Config.DllName, EntryPoint = "average5_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average5_HFA05(HFA05 hfa1, HFA05 hfa2, HFA05 hfa3, HFA05 hfa4, HFA05 hfa5);
[DllImport(Config.DllName, EntryPoint = "average5_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average5_HFA08(HFA08 hfa1, HFA08 hfa2, HFA08 hfa3, HFA08 hfa4, HFA08 hfa5);
[DllImport(Config.DllName, EntryPoint = "average5_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average5_HFA11(HFA11 hfa1, HFA11 hfa2, HFA11 hfa3, HFA11 hfa4, HFA11 hfa5);
[DllImport(Config.DllName, EntryPoint = "average5_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average5_HFA19(HFA19 hfa1, HFA19 hfa2, HFA19 hfa3, HFA19 hfa4, HFA19 hfa5);
[DllImport(Config.DllName, EntryPoint = "average8_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average8_HFA01(HFA01 hfa1, HFA01 hfa2, HFA01 hfa3, HFA01 hfa4, HFA01 hfa5, HFA01 hfa6, HFA01 hfa7, HFA01 hfa8);
[DllImport(Config.DllName, EntryPoint = "average8_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average8_HFA02(HFA02 hfa1, HFA02 hfa2, HFA02 hfa3, HFA02 hfa4, HFA02 hfa5, HFA02 hfa6, HFA02 hfa7, HFA02 hfa8);
[DllImport(Config.DllName, EntryPoint = "average8_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average8_HFA03(HFA03 hfa1, HFA03 hfa2, HFA03 hfa3, HFA03 hfa4, HFA03 hfa5, HFA03 hfa6, HFA03 hfa7, HFA03 hfa8);
[DllImport(Config.DllName, EntryPoint = "average8_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average8_HFA05(HFA05 hfa1, HFA05 hfa2, HFA05 hfa3, HFA05 hfa4, HFA05 hfa5, HFA05 hfa6, HFA05 hfa7, HFA05 hfa8);
[DllImport(Config.DllName, EntryPoint = "average8_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average8_HFA08(HFA08 hfa1, HFA08 hfa2, HFA08 hfa3, HFA08 hfa4, HFA08 hfa5, HFA08 hfa6, HFA08 hfa7, HFA08 hfa8);
[DllImport(Config.DllName, EntryPoint = "average8_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average8_HFA11(HFA11 hfa1, HFA11 hfa2, HFA11 hfa3, HFA11 hfa4, HFA11 hfa5, HFA11 hfa6, HFA11 hfa7, HFA11 hfa8);
[DllImport(Config.DllName, EntryPoint = "average8_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average8_HFA19(HFA19 hfa1, HFA19 hfa2, HFA19 hfa3, HFA19 hfa4, HFA19 hfa5, HFA19 hfa6, HFA19 hfa7, HFA19 hfa8);
[DllImport(Config.DllName, EntryPoint = "average11_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average11_HFA01(HFA01 hfa1, HFA01 hfa2, HFA01 hfa3, HFA01 hfa4, HFA01 hfa5, HFA01 hfa6, HFA01 hfa7, HFA01 hfa8, HFA01 hfa9, HFA01 hfa10, HFA01 hfa11);
[DllImport(Config.DllName, EntryPoint = "average11_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average11_HFA02(HFA02 hfa1, HFA02 hfa2, HFA02 hfa3, HFA02 hfa4, HFA02 hfa5, HFA02 hfa6, HFA02 hfa7, HFA02 hfa8, HFA02 hfa9, HFA02 hfa10, HFA02 hfa11);
[DllImport(Config.DllName, EntryPoint = "average11_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average11_HFA03(HFA03 hfa1, HFA03 hfa2, HFA03 hfa3, HFA03 hfa4, HFA03 hfa5, HFA03 hfa6, HFA03 hfa7, HFA03 hfa8, HFA03 hfa9, HFA03 hfa10, HFA03 hfa11);
[DllImport(Config.DllName, EntryPoint = "average11_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average11_HFA05(HFA05 hfa1, HFA05 hfa2, HFA05 hfa3, HFA05 hfa4, HFA05 hfa5, HFA05 hfa6, HFA05 hfa7, HFA05 hfa8, HFA05 hfa9, HFA05 hfa10, HFA05 hfa11);
[DllImport(Config.DllName, EntryPoint = "average11_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average11_HFA08(HFA08 hfa1, HFA08 hfa2, HFA08 hfa3, HFA08 hfa4, HFA08 hfa5, HFA08 hfa6, HFA08 hfa7, HFA08 hfa8, HFA08 hfa9, HFA08 hfa10, HFA08 hfa11);
[DllImport(Config.DllName, EntryPoint = "average11_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average11_HFA11(HFA11 hfa1, HFA11 hfa2, HFA11 hfa3, HFA11 hfa4, HFA11 hfa5, HFA11 hfa6, HFA11 hfa7, HFA11 hfa8, HFA11 hfa9, HFA11 hfa10, HFA11 hfa11);
[DllImport(Config.DllName, EntryPoint = "average11_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average11_HFA19(HFA19 hfa1, HFA19 hfa2, HFA19 hfa3, HFA19 hfa4, HFA19 hfa5, HFA19 hfa6, HFA19 hfa7, HFA19 hfa8, HFA19 hfa9, HFA19 hfa10, HFA19 hfa11);
[DllImport(Config.DllName, EntryPoint = "average19_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average19_HFA01(HFA01 hfa1, HFA01 hfa2, HFA01 hfa3, HFA01 hfa4, HFA01 hfa5, HFA01 hfa6, HFA01 hfa7, HFA01 hfa8, HFA01 hfa9, HFA01 hfa10, HFA01 hfa11, HFA01 hfa12, HFA01 hfa13, HFA01 hfa14, HFA01 hfa15, HFA01 hfa16, HFA01 hfa17, HFA01 hfa18, HFA01 hfa19);
[DllImport(Config.DllName, EntryPoint = "average19_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average19_HFA02(HFA02 hfa1, HFA02 hfa2, HFA02 hfa3, HFA02 hfa4, HFA02 hfa5, HFA02 hfa6, HFA02 hfa7, HFA02 hfa8, HFA02 hfa9, HFA02 hfa10, HFA02 hfa11, HFA02 hfa12, HFA02 hfa13, HFA02 hfa14, HFA02 hfa15, HFA02 hfa16, HFA02 hfa17, HFA02 hfa18, HFA02 hfa19);
[DllImport(Config.DllName, EntryPoint = "average19_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average19_HFA03(HFA03 hfa1, HFA03 hfa2, HFA03 hfa3, HFA03 hfa4, HFA03 hfa5, HFA03 hfa6, HFA03 hfa7, HFA03 hfa8, HFA03 hfa9, HFA03 hfa10, HFA03 hfa11, HFA03 hfa12, HFA03 hfa13, HFA03 hfa14, HFA03 hfa15, HFA03 hfa16, HFA03 hfa17, HFA03 hfa18, HFA03 hfa19);
[DllImport(Config.DllName, EntryPoint = "average19_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average19_HFA05(HFA05 hfa1, HFA05 hfa2, HFA05 hfa3, HFA05 hfa4, HFA05 hfa5, HFA05 hfa6, HFA05 hfa7, HFA05 hfa8, HFA05 hfa9, HFA05 hfa10, HFA05 hfa11, HFA05 hfa12, HFA05 hfa13, HFA05 hfa14, HFA05 hfa15, HFA05 hfa16, HFA05 hfa17, HFA05 hfa18, HFA05 hfa19);
[DllImport(Config.DllName, EntryPoint = "average19_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average19_HFA08(HFA08 hfa1, HFA08 hfa2, HFA08 hfa3, HFA08 hfa4, HFA08 hfa5, HFA08 hfa6, HFA08 hfa7, HFA08 hfa8, HFA08 hfa9, HFA08 hfa10, HFA08 hfa11, HFA08 hfa12, HFA08 hfa13, HFA08 hfa14, HFA08 hfa15, HFA08 hfa16, HFA08 hfa17, HFA08 hfa18, HFA08 hfa19);
[DllImport(Config.DllName, EntryPoint = "average19_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average19_HFA11(HFA11 hfa1, HFA11 hfa2, HFA11 hfa3, HFA11 hfa4, HFA11 hfa5, HFA11 hfa6, HFA11 hfa7, HFA11 hfa8, HFA11 hfa9, HFA11 hfa10, HFA11 hfa11, HFA11 hfa12, HFA11 hfa13, HFA11 hfa14, HFA11 hfa15, HFA11 hfa16, HFA11 hfa17, HFA11 hfa18, HFA11 hfa19);
[DllImport(Config.DllName, EntryPoint = "average19_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Average19_HFA19(HFA19 hfa1, HFA19 hfa2, HFA19 hfa3, HFA19 hfa4, HFA19 hfa5, HFA19 hfa6, HFA19 hfa7, HFA19 hfa8, HFA19 hfa9, HFA19 hfa10, HFA19 hfa11, HFA19 hfa12, HFA19 hfa13, HFA19 hfa14, HFA19 hfa15, HFA19 hfa16, HFA19 hfa17, HFA19 hfa18, HFA19 hfa19);
// ---------------------------------------------------
// Add Methods
// ---------------------------------------------------
[DllImport(Config.DllName, EntryPoint = "add01_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add01_HFA01(HFA01 hfa1, float v1, HFA01 hfa2, int v2, HFA01 hfa3, short v3, double v4, HFA01 hfa4, HFA01 hfa5, float v5, long v6, float v7, HFA01 hfa6, float v8, HFA01 hfa7);
[DllImport(Config.DllName, EntryPoint = "add01_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add01_HFA02(HFA02 hfa1, float v1, HFA02 hfa2, int v2, HFA02 hfa3, short v3, double v4, HFA02 hfa4, HFA02 hfa5, float v5, long v6, float v7, HFA02 hfa6, float v8, HFA02 hfa7);
[DllImport(Config.DllName, EntryPoint = "add01_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add01_HFA03(HFA03 hfa1, float v1, HFA03 hfa2, int v2, HFA03 hfa3, short v3, double v4, HFA03 hfa4, HFA03 hfa5, float v5, long v6, float v7, HFA03 hfa6, float v8, HFA03 hfa7);
[DllImport(Config.DllName, EntryPoint = "add01_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add01_HFA05(HFA05 hfa1, float v1, HFA05 hfa2, int v2, HFA05 hfa3, short v3, double v4, HFA05 hfa4, HFA05 hfa5, float v5, long v6, float v7, HFA05 hfa6, float v8, HFA05 hfa7);
[DllImport(Config.DllName, EntryPoint = "add01_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add01_HFA08(HFA08 hfa1, float v1, HFA08 hfa2, int v2, HFA08 hfa3, short v3, double v4, HFA08 hfa4, HFA08 hfa5, float v5, long v6, float v7, HFA08 hfa6, float v8, HFA08 hfa7);
[DllImport(Config.DllName, EntryPoint = "add01_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add01_HFA11(HFA11 hfa1, float v1, HFA11 hfa2, int v2, HFA11 hfa3, short v3, double v4, HFA11 hfa4, HFA11 hfa5, float v5, long v6, float v7, HFA11 hfa6, float v8, HFA11 hfa7);
[DllImport(Config.DllName, EntryPoint = "add01_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add01_HFA19(HFA19 hfa1, float v1, HFA19 hfa2, int v2, HFA19 hfa3, short v3, double v4, HFA19 hfa4, HFA19 hfa5, float v5, long v6, float v7, HFA19 hfa6, float v8, HFA19 hfa7);
[DllImport(Config.DllName, EntryPoint = "add01_HFA00", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add01_HFA00(HFA03 hfa1, float v1, HFA02 hfa2, int v2, HFA19 hfa3, short v3, double v4, HFA05 hfa4, HFA08 hfa5, float v5, long v6, float v7, HFA11 hfa6, float v8, HFA01 hfa7);
[DllImport(Config.DllName, EntryPoint = "add02_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add02_HFA01(HFA01 hfa1, HFA01 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA01 hfa3, double v7, float v8, HFA01 hfa4, short v9, HFA01 hfa5, float v10, HFA01 hfa6, HFA01 hfa7);
[DllImport(Config.DllName, EntryPoint = "add02_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add02_HFA02(HFA02 hfa1, HFA02 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA02 hfa3, double v7, float v8, HFA02 hfa4, short v9, HFA02 hfa5, float v10, HFA02 hfa6, HFA02 hfa7);
[DllImport(Config.DllName, EntryPoint = "add02_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add02_HFA03(HFA03 hfa1, HFA03 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA03 hfa3, double v7, float v8, HFA03 hfa4, short v9, HFA03 hfa5, float v10, HFA03 hfa6, HFA03 hfa7);
[DllImport(Config.DllName, EntryPoint = "add02_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add02_HFA05(HFA05 hfa1, HFA05 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA05 hfa3, double v7, float v8, HFA05 hfa4, short v9, HFA05 hfa5, float v10, HFA05 hfa6, HFA05 hfa7);
[DllImport(Config.DllName, EntryPoint = "add02_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add02_HFA08(HFA08 hfa1, HFA08 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA08 hfa3, double v7, float v8, HFA08 hfa4, short v9, HFA08 hfa5, float v10, HFA08 hfa6, HFA08 hfa7);
[DllImport(Config.DllName, EntryPoint = "add02_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add02_HFA11(HFA11 hfa1, HFA11 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA11 hfa3, double v7, float v8, HFA11 hfa4, short v9, HFA11 hfa5, float v10, HFA11 hfa6, HFA11 hfa7);
[DllImport(Config.DllName, EntryPoint = "add02_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add02_HFA19(HFA19 hfa1, HFA19 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA19 hfa3, double v7, float v8, HFA19 hfa4, short v9, HFA19 hfa5, float v10, HFA19 hfa6, HFA19 hfa7);
[DllImport(Config.DllName, EntryPoint = "add02_HFA00", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add02_HFA00(HFA01 hfa1, HFA05 hfa2, long v1, short v2, float v3, int v4, double v5, float v6, HFA03 hfa3, double v7, float v8, HFA11 hfa4, short v9, HFA19 hfa5, float v10, HFA08 hfa6, HFA02 hfa7);
[DllImport(Config.DllName, EntryPoint = "add03_HFA01", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add03_HFA01(float v1, sbyte v2, HFA01 hfa1, double v3, sbyte v4, HFA01 hfa2, long v5, short v6, int v7, HFA01 hfa3, HFA01 hfa4, float v8, HFA01 hfa5, float v9, HFA01 hfa6, float v10, HFA01 hfa7);
[DllImport(Config.DllName, EntryPoint = "add03_HFA02", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add03_HFA02(float v1, sbyte v2, HFA02 hfa1, double v3, sbyte v4, HFA02 hfa2, long v5, short v6, int v7, HFA02 hfa3, HFA02 hfa4, float v8, HFA02 hfa5, float v9, HFA02 hfa6, float v10, HFA02 hfa7);
[DllImport(Config.DllName, EntryPoint = "add03_HFA03", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add03_HFA03(float v1, sbyte v2, HFA03 hfa1, double v3, sbyte v4, HFA03 hfa2, long v5, short v6, int v7, HFA03 hfa3, HFA03 hfa4, float v8, HFA03 hfa5, float v9, HFA03 hfa6, float v10, HFA03 hfa7);
[DllImport(Config.DllName, EntryPoint = "add03_HFA05", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add03_HFA05(float v1, sbyte v2, HFA05 hfa1, double v3, sbyte v4, HFA05 hfa2, long v5, short v6, int v7, HFA05 hfa3, HFA05 hfa4, float v8, HFA05 hfa5, float v9, HFA05 hfa6, float v10, HFA05 hfa7);
[DllImport(Config.DllName, EntryPoint = "add03_HFA08", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add03_HFA08(float v1, sbyte v2, HFA08 hfa1, double v3, sbyte v4, HFA08 hfa2, long v5, short v6, int v7, HFA08 hfa3, HFA08 hfa4, float v8, HFA08 hfa5, float v9, HFA08 hfa6, float v10, HFA08 hfa7);
[DllImport(Config.DllName, EntryPoint = "add03_HFA11", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add03_HFA11(float v1, sbyte v2, HFA11 hfa1, double v3, sbyte v4, HFA11 hfa2, long v5, short v6, int v7, HFA11 hfa3, HFA11 hfa4, float v8, HFA11 hfa5, float v9, HFA11 hfa6, float v10, HFA11 hfa7);
[DllImport(Config.DllName, EntryPoint = "add03_HFA19", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add03_HFA19(float v1, sbyte v2, HFA19 hfa1, double v3, sbyte v4, HFA19 hfa2, long v5, short v6, int v7, HFA19 hfa3, HFA19 hfa4, float v8, HFA19 hfa5, float v9, HFA19 hfa6, float v10, HFA19 hfa7);
[DllImport(Config.DllName, EntryPoint = "add03_HFA00", CallingConvention = CallingConvention.Cdecl)]
public static extern float Add03_HFA00(float v1, sbyte v2, HFA08 hfa1, double v3, sbyte v4, HFA19 hfa2, long v5, short v6, int v7, HFA03 hfa3, HFA01 hfa4, float v8, HFA11 hfa5, float v9, HFA02 hfa6, float v10, HFA05 hfa7);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// Options for creating and running scripts.
/// </summary>
public class ScriptOptions
{
private readonly ImmutableArray<MetadataReference> _references;
private readonly ImmutableArray<string> _namespaces;
private readonly AssemblyReferenceResolver _referenceResolver;
private readonly bool _isInteractive;
public ScriptOptions()
: this(ImmutableArray<MetadataReference>.Empty,
ImmutableArray<string>.Empty,
new AssemblyReferenceResolver(GacFileResolver.Default, MetadataFileReferenceProvider.Default),
isInteractive: true)
{
}
public static readonly ScriptOptions Default;
static ScriptOptions()
{
var paths = ImmutableArray.Create(RuntimeEnvironment.GetRuntimeDirectory());
Default = new ScriptOptions()
.WithReferences(typeof(int).Assembly)
.WithNamespaces("System")
.WithSearchPaths(paths);
}
private ScriptOptions(
ImmutableArray<MetadataReference> references,
ImmutableArray<string> namespaces,
AssemblyReferenceResolver referenceResolver,
bool isInteractive)
{
_references = references;
_namespaces = namespaces;
_referenceResolver = referenceResolver;
_isInteractive = isInteractive;
}
/// <summary>
/// The set of <see cref="MetadataReference"/>'s used by the script.
/// </summary>
public ImmutableArray<MetadataReference> References
{
get { return _references; }
}
/// <summary>
/// The namespaces automatically imported by the script.
/// </summary>
public ImmutableArray<string> Namespaces
{
get { return _namespaces; }
}
/// <summary>
/// The paths used when searching for references.
/// </summary>
public ImmutableArray<string> SearchPaths
{
get { return _referenceResolver.PathResolver.SearchPaths; }
}
/// <summary>
/// The base directory used when searching for references.
/// </summary>
public string BaseDirectory
{
get { return _referenceResolver.PathResolver.BaseDirectory; }
}
/// <summary>
/// The <see cref="MetadataFileReferenceProvider"/> scripts will use to translate assembly names into metadata file paths. (#r syntax)
/// </summary>
public MetadataReferenceResolver ReferenceResolver
{
get { return _referenceResolver; }
}
// TODO:
internal AssemblyReferenceResolver AssemblyResolver
{
get { return _referenceResolver; }
}
internal MetadataFileReferenceResolver FileReferenceResolver
{
get { return _referenceResolver.PathResolver; }
}
/// <summary>
/// True if the script is interactive.
/// Interactive scripts may contain a final expression whose value is returned when the script is run.
/// </summary>
public bool IsInteractive
{
get { return _isInteractive; }
}
private ScriptOptions With(
Optional<ImmutableArray<MetadataReference>> references = default(Optional<ImmutableArray<MetadataReference>>),
Optional<ImmutableArray<string>> namespaces = default(Optional<ImmutableArray<string>>),
Optional<AssemblyReferenceResolver> resolver = default(Optional<AssemblyReferenceResolver>),
Optional<bool> isInteractive = default(Optional<bool>))
{
var newReferences = references.HasValue ? references.Value : _references;
var newNamespaces = namespaces.HasValue ? namespaces.Value : _namespaces;
var newResolver = resolver.HasValue ? resolver.Value : _referenceResolver;
var newIsInteractive = isInteractive.HasValue ? isInteractive.Value : _isInteractive;
if (newReferences == _references &&
newNamespaces == _namespaces &&
newResolver == _referenceResolver &&
newIsInteractive == _isInteractive)
{
return this;
}
else
{
return new ScriptOptions(newReferences, newNamespaces, newResolver, newIsInteractive);
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(ImmutableArray<MetadataReference> references)
{
return With(references: references.IsDefault ? ImmutableArray<MetadataReference>.Empty : references);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(IEnumerable<MetadataReference> references)
{
return WithReferences(references != null ? references.ToImmutableArray() : ImmutableArray<MetadataReference>.Empty);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(params MetadataReference[] references)
{
return WithReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(IEnumerable<MetadataReference> references)
{
if (_references == null)
{
return this;
}
else
{
return this.WithReferences(this.References.AddRange(references.Where(r => r != null && !this.References.Contains(r))));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params MetadataReference[] references)
{
return AddReferences((IEnumerable<MetadataReference>)references);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(IEnumerable<System.Reflection.Assembly> assemblies)
{
if (assemblies == null)
{
return WithReferences((IEnumerable<MetadataReference>)null);
}
else
{
return WithReferences(assemblies.Select(MetadataReference.CreateFromAssemblyInternal));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(params System.Reflection.Assembly[] assemblies)
{
return WithReferences((IEnumerable<System.Reflection.Assembly>)assemblies);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(IEnumerable<System.Reflection.Assembly> assemblies)
{
if (assemblies == null)
{
return this;
}
else
{
return AddReferences(assemblies.Select(MetadataReference.CreateFromAssemblyInternal));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params System.Reflection.Assembly[] assemblies)
{
return AddReferences((IEnumerable<System.Reflection.Assembly>)assemblies);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(IEnumerable<string> references)
{
if (references == null)
{
return WithReferences(ImmutableArray<MetadataReference>.Empty);
}
else
{
return WithReferences(references.Where(name => name != null).Select(name => ResolveReference(name)));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the references changed.
/// </summary>
public ScriptOptions WithReferences(params string[] references)
{
return WithReferences((IEnumerable<string>)references);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(IEnumerable<string> references)
{
if (references == null)
{
return this;
}
else
{
return AddReferences(references.Where(name => name != null).Select(name => ResolveReference(name)));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with references added.
/// </summary>
public ScriptOptions AddReferences(params string[] references)
{
return AddReferences((IEnumerable<string>)references);
}
private MetadataReference ResolveReference(string assemblyDisplayNameOrPath)
{
// TODO:
string fullPath = _referenceResolver.PathResolver.ResolveReference(assemblyDisplayNameOrPath, baseFilePath: null);
if (fullPath == null)
{
throw new System.IO.FileNotFoundException(ScriptingResources.AssemblyNotFound, assemblyDisplayNameOrPath);
}
return _referenceResolver.Provider.GetReference(fullPath, MetadataReferenceProperties.Assembly);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the namespaces changed.
/// </summary>
public ScriptOptions WithNamespaces(ImmutableArray<string> namespaces)
{
return With(namespaces: namespaces.IsDefault ? ImmutableArray<string>.Empty : namespaces);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the namespaces changed.
/// </summary>
public ScriptOptions WithNamespaces(IEnumerable<string> namespaces)
{
return WithNamespaces(namespaces != null ? namespaces.ToImmutableArray() : ImmutableArray<string>.Empty);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the namespaces changed.
/// </summary>
public ScriptOptions WithNamespaces(params string[] namespaces)
{
return WithNamespaces((IEnumerable<string>)namespaces);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with namespaces added.
/// </summary>
public ScriptOptions AddNamespaces(IEnumerable<string> namespaces)
{
if (namespaces == null)
{
return this;
}
else
{
return this.WithNamespaces(this.Namespaces.AddRange(namespaces.Where(n => n != null && !this.Namespaces.Contains(n))));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with namespaces added.
/// </summary>
public ScriptOptions AddNamespaces(params string[] namespaces)
{
return AddNamespaces((IEnumerable<string>)namespaces);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the search paths changed.
/// </summary>
public ScriptOptions WithSearchPaths(IEnumerable<string> searchPaths)
{
if (this.SearchPaths.SequenceEqual(searchPaths))
{
return this;
}
else
{
// TODO:
var gacResolver = _referenceResolver.PathResolver as GacFileResolver;
if (gacResolver != null)
{
return With(resolver: new AssemblyReferenceResolver(
new GacFileResolver(
searchPaths,
gacResolver.BaseDirectory,
gacResolver.Architectures,
gacResolver.PreferredCulture),
_referenceResolver.Provider));
}
else
{
return With(resolver: new AssemblyReferenceResolver(
new MetadataFileReferenceResolver(
searchPaths,
_referenceResolver.PathResolver.BaseDirectory),
_referenceResolver.Provider));
}
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the search paths changed.
/// </summary>
public ScriptOptions WithSearchPaths(params string[] searchPaths)
{
return WithSearchPaths((IEnumerable<string>)searchPaths);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with search paths added.
/// </summary>
public ScriptOptions AddSearchPaths(params string[] searchPaths)
{
return AddSearchPaths((IEnumerable<string>)searchPaths);
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with search paths added.
/// </summary>
public ScriptOptions AddSearchPaths(IEnumerable<string> searchPaths)
{
if (searchPaths == null)
{
return this;
}
else
{
return WithSearchPaths(this.SearchPaths.AddRange(searchPaths.Where(s => s != null && !this.SearchPaths.Contains(s))));
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the base directory changed.
/// </summary>
public ScriptOptions WithBaseDirectory(string baseDirectory)
{
if (this.BaseDirectory == baseDirectory)
{
return this;
}
else
{
// TODO:
var gacResolver = _referenceResolver.PathResolver as GacFileResolver;
if (gacResolver != null)
{
return With(resolver: new AssemblyReferenceResolver(
new GacFileResolver(
_referenceResolver.PathResolver.SearchPaths,
baseDirectory,
gacResolver.Architectures,
gacResolver.PreferredCulture),
_referenceResolver.Provider));
}
else
{
return With(resolver: new AssemblyReferenceResolver(
new MetadataFileReferenceResolver(
_referenceResolver.PathResolver.SearchPaths,
baseDirectory),
_referenceResolver.Provider));
}
}
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the reference resolver specified.
/// </summary>
internal ScriptOptions WithReferenceResolver(MetadataFileReferenceResolver resolver)
{
if (resolver == _referenceResolver.PathResolver)
{
return this;
}
return With(resolver: new AssemblyReferenceResolver(resolver, _referenceResolver.Provider));
}
/// <summary>
/// Creates a new <see cref="ScriptOptions"/> with the reference provider specified.
/// </summary>
internal ScriptOptions WithReferenceProvider(MetadataFileReferenceProvider provider)
{
if (provider == _referenceResolver.Provider)
{
return this;
}
return With(resolver: new AssemblyReferenceResolver(_referenceResolver.PathResolver, provider));
}
/// <summary>
/// Create a new <see cref="ScriptOptions"/> with the interactive state specified.
/// Interactive scripts may contain a final expression whose value is returned when the script is run.
/// </summary>
public ScriptOptions WithIsInteractive(bool isInteractive)
{
return With(isInteractive: isInteractive);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.IO;
using System.Linq;
using NuGet.Common;
namespace NuGet.Commands
{
[Command(typeof(NuGetCommand), "pack", "PackageCommandDescription", MaxArgs = 1, UsageSummaryResourceName = "PackageCommandUsageSummary",
UsageDescriptionResourceName = "PackageCommandUsageDescription", UsageExampleResourceName = "PackCommandUsageExamples")]
public class PackCommand : Command
{
internal static readonly string SymbolsExtension = ".symbols" + Constants.PackageExtension;
private static readonly string[] _defaultExcludes = new[] {
// Exclude previous package files
@"**\*" + Constants.PackageExtension,
// Exclude all files and directories that begin with "."
@"**\\.**", ".**"
};
// Target file paths to exclude when building the lib package for symbol server scenario
private static readonly string[] _libPackageExcludes = new[] {
@"**\*.pdb",
@"src\**\*"
};
// Target file paths to exclude when building the symbols package for symbol server scenario
private static readonly string[] _symbolPackageExcludes = new[] {
@"content\**\*",
@"tools\**\*.ps1"
};
private readonly HashSet<string> _excludes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, string> _properties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private static readonly HashSet<string> _allowedExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
Constants.ManifestExtension,
".csproj",
".vbproj",
".fsproj",
".nproj",
".btproj",
".dxjsproj"
};
private Version _minClientVersionValue;
[Option(typeof(NuGetCommand), "PackageCommandOutputDirDescription")]
public string OutputDirectory { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandBasePathDescription")]
public string BasePath { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandVerboseDescription")]
public bool Verbose { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandVersionDescription")]
public string Version { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandExcludeDescription")]
public ICollection<string> Exclude
{
get { return _excludes; }
}
[Option(typeof(NuGetCommand), "PackageCommandSymbolsDescription")]
public bool Symbols { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandToolDescription")]
public bool Tool { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandBuildDescription")]
public bool Build { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandNoDefaultExcludes")]
public bool NoDefaultExcludes { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandNoRunAnalysis")]
public bool NoPackageAnalysis { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandExcludeEmptyDirectories")]
public bool ExcludeEmptyDirectories { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandIncludeReferencedProjects")]
public bool IncludeReferencedProjects { get; set; }
[Option(typeof(NuGetCommand), "PackageCommandPropertiesDescription")]
public Dictionary<string, string> Properties
{
get
{
return _properties;
}
}
[Option(typeof(NuGetCommand), "PackageCommandMinClientVersion")]
public string MinClientVersion { get; set; }
[ImportMany]
public IEnumerable<IPackageRule> Rules { get; set; }
// TODO: Temporarily hide the real ConfigFile parameter from the help text.
// When we fix #3230, we should remove this property.
public new string ConfigFile { get; set; }
public override void ExecuteCommand()
{
if (Verbose)
{
Console.WriteWarning(LocalizedResourceManager.GetString("Option_VerboseDeprecated"));
Verbosity = Verbosity.Detailed;
}
// Get the input file
string path = GetInputFile();
Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandAttemptingToBuildPackage"), Path.GetFileName(path));
// If the BasePath is not specified, use the directory of the input file (nuspec / proj) file
BasePath = String.IsNullOrEmpty(BasePath) ? Path.GetDirectoryName(Path.GetFullPath(path)) : BasePath;
if (!String.IsNullOrEmpty(MinClientVersion))
{
if (!System.Version.TryParse(MinClientVersion, out _minClientVersionValue))
{
throw new CommandLineException(LocalizedResourceManager.GetString("PackageCommandInvalidMinClientVersion"));
}
}
IPackage package = BuildPackage(path);
if (package != null && !NoPackageAnalysis)
{
AnalyzePackage(package);
}
}
private IPackage BuildPackage(PackageBuilder builder, string outputPath = null)
{
if (!String.IsNullOrEmpty(Version))
{
builder.Version = new SemanticVersion(Version);
}
if (_minClientVersionValue != null)
{
builder.MinClientVersion = _minClientVersionValue;
}
outputPath = outputPath ?? GetOutputPath(builder);
ExcludeFiles(builder.Files);
// Track if the package file was already present on disk
bool isExistingPackage = File.Exists(outputPath);
try
{
using (Stream stream = File.Create(outputPath))
{
builder.Save(stream);
}
}
catch
{
if (!isExistingPackage && File.Exists(outputPath))
{
File.Delete(outputPath);
}
throw;
}
if (Verbosity == Verbosity.Detailed)
{
PrintVerbose(outputPath);
}
Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandSuccess"), outputPath);
return new OptimizedZipPackage(outputPath);
}
private void PrintVerbose(string outputPath)
{
Console.WriteLine();
var package = new OptimizedZipPackage(outputPath);
Console.WriteLine("Id: {0}", package.Id);
Console.WriteLine("Version: {0}", package.Version);
Console.WriteLine("Authors: {0}", String.Join(", ", package.Authors));
Console.WriteLine("Description: {0}", package.Description);
if (package.LicenseUrl != null)
{
Console.WriteLine("License Url: {0}", package.LicenseUrl);
}
if (package.ProjectUrl != null)
{
Console.WriteLine("Project Url: {0}", package.ProjectUrl);
}
if (!String.IsNullOrEmpty(package.Tags))
{
Console.WriteLine("Tags: {0}", package.Tags.Trim());
}
if (package.DependencySets.Any())
{
Console.WriteLine("Dependencies: {0}", String.Join(", ", package.DependencySets.SelectMany(d => d.Dependencies).Select(d => d.ToString())));
}
else
{
Console.WriteLine("Dependencies: None");
}
Console.WriteLine();
foreach (var file in package.GetFiles().OrderBy(p => p.Path))
{
Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandAddedFile"), file.Path);
}
Console.WriteLine();
}
internal void ExcludeFiles(ICollection<IPackageFile> packageFiles)
{
// Always exclude the nuspec file
// Review: This exclusion should be done by the package builder because it knows which file would collide with the auto-generated
// manifest file.
var wildCards = _excludes.Concat(new[] { @"**\*" + Constants.ManifestExtension });
if (!NoDefaultExcludes)
{
// The user has not explicitly disabled default filtering.
wildCards = wildCards.Concat(_defaultExcludes);
}
PathResolver.FilterPackageFiles(packageFiles, ResolvePath, wildCards);
}
private string ResolvePath(IPackageFile packageFile)
{
var physicalPackageFile = packageFile as PhysicalPackageFile;
// For PhysicalPackageFiles, we want to filter by SourcePaths, the path on disk. The Path value maps to the TargetPath
if (physicalPackageFile == null)
{
return packageFile.Path;
}
var path = physicalPackageFile.SourcePath;
// Make sure that the basepath has a directory separator
int index = path.IndexOf(BasePath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
if (index != -1)
{
// Since wildcards are going to be relative to the base path, remove the BasePath portion of the file's source path.
// Also remove any leading path separator slashes
path = path.Substring(index + BasePath.Length).TrimStart(Path.DirectorySeparatorChar);
}
return path;
}
private string GetOutputPath(PackageBuilder builder, bool symbols = false)
{
string version = String.IsNullOrEmpty(Version) ? builder.Version.ToString() : Version;
// Output file is {id}.{version}
string outputFile = builder.Id + "." + version;
// If this is a source package then add .symbols.nupkg to the package file name
if (symbols)
{
outputFile += SymbolsExtension;
}
else
{
outputFile += Constants.PackageExtension;
}
string outputDirectory = OutputDirectory ?? Directory.GetCurrentDirectory();
return Path.Combine(outputDirectory, outputFile);
}
private IPackage BuildPackage(string path)
{
string extension = Path.GetExtension(path);
if (extension.Equals(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase))
{
return BuildFromNuspec(path);
}
else
{
return BuildFromProjectFile(path);
}
}
private IPackage BuildFromNuspec(string path)
{
PackageBuilder packageBuilder = CreatePackageBuilderFromNuspec(path);
if (Symbols)
{
// remove source related files when building the lib package
ExcludeFilesForLibPackage(packageBuilder.Files);
if (!packageBuilder.Files.Any())
{
throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("PackageCommandNoFilesForLibPackage"),
path, CommandLineConstants.NuGetDocs));
}
}
IPackage package = BuildPackage(packageBuilder);
if (Symbols)
{
BuildSymbolsPackage(path);
}
return package;
}
private void BuildSymbolsPackage(string path)
{
PackageBuilder symbolsBuilder = CreatePackageBuilderFromNuspec(path);
// remove unnecessary files when building the symbols package
ExcludeFilesForSymbolPackage(symbolsBuilder.Files);
if (!symbolsBuilder.Files.Any())
{
throw new CommandLineException(String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("PackageCommandNoFilesForSymbolsPackage"),
path, CommandLineConstants.NuGetDocs));
}
string outputPath = GetOutputPath(symbolsBuilder, symbols: true);
BuildPackage(symbolsBuilder, outputPath);
}
internal static void ExcludeFilesForLibPackage(ICollection<IPackageFile> files)
{
PathResolver.FilterPackageFiles(files, file => file.Path, _libPackageExcludes);
}
internal static void ExcludeFilesForSymbolPackage(ICollection<IPackageFile> files)
{
PathResolver.FilterPackageFiles(files, file => file.Path, _symbolPackageExcludes);
}
private PackageBuilder CreatePackageBuilderFromNuspec(string path)
{
// Set the version property if the flag is set
if (!String.IsNullOrEmpty(Version))
{
Properties["version"] = Version;
}
// Initialize the property provider based on what was passed in using the properties flag
var propertyProvider = new DictionaryPropertyProvider(Properties);
if (String.IsNullOrEmpty(BasePath))
{
return new PackageBuilder(path, propertyProvider, !ExcludeEmptyDirectories);
}
return new PackageBuilder(path, BasePath, propertyProvider, !ExcludeEmptyDirectories);
}
private IPackage BuildFromProjectFile(string path)
{
var factory = new ProjectFactory(path, Properties)
{
IsTool = Tool,
Logger = Console,
Build = Build,
IncludeReferencedProjects = IncludeReferencedProjects
};
// Add the additional Properties to the properties of the Project Factory
foreach (var property in Properties)
{
if (factory.ProjectProperties.ContainsKey(property.Key))
{
Console.WriteWarning(LocalizedResourceManager.GetString("Warning_DuplicatePropertyKey"), property.Key);
}
factory.ProjectProperties[property.Key] = property.Value;
}
// Create a builder for the main package as well as the sources/symbols package
PackageBuilder mainPackageBuilder = factory.CreateBuilder(BasePath);
// Build the main package
IPackage package = BuildPackage(mainPackageBuilder);
// If we're excluding symbols then do nothing else
if (!Symbols)
{
return package;
}
Console.WriteLine();
Console.WriteLine(LocalizedResourceManager.GetString("PackageCommandAttemptingToBuildSymbolsPackage"), Path.GetFileName(path));
factory.IncludeSymbols = true;
PackageBuilder symbolsBuilder = factory.CreateBuilder(BasePath);
symbolsBuilder.Version = mainPackageBuilder.Version;
// Get the file name for the sources package and build it
string outputPath = GetOutputPath(symbolsBuilder, symbols: true);
BuildPackage(symbolsBuilder, outputPath);
// this is the real package, not the symbol package
return package;
}
internal void AnalyzePackage(IPackage package)
{
IEnumerable<IPackageRule> packageRules = Rules;
if (!String.IsNullOrEmpty(package.Version.SpecialVersion))
{
// If a package contains a special token, we'll warn users if it does not strictly follow semver guidelines.
packageRules = packageRules.Concat(new[] { new StrictSemanticVersionValidationRule() });
}
IList<PackageIssue> issues = package.Validate(packageRules).OrderBy(p => p.Title, StringComparer.CurrentCulture).ToList();
if (issues.Count > 0)
{
Console.WriteLine();
Console.WriteWarning(LocalizedResourceManager.GetString("PackageCommandPackageIssueSummary"), issues.Count, package.Id);
foreach (var issue in issues)
{
PrintPackageIssue(issue);
}
}
}
private void PrintPackageIssue(PackageIssue issue)
{
Console.WriteLine();
Console.WriteWarning(
prependWarningText: false,
value: LocalizedResourceManager.GetString("PackageCommandIssueTitle"),
args: issue.Title);
Console.WriteWarning(
prependWarningText: false,
value: LocalizedResourceManager.GetString("PackageCommandIssueDescription"),
args: issue.Description);
if (!String.IsNullOrEmpty(issue.Solution))
{
Console.WriteWarning(
prependWarningText: false,
value: LocalizedResourceManager.GetString("PackageCommandIssueSolution"),
args: issue.Solution);
}
}
private string GetInputFile()
{
IEnumerable<string> files = Arguments.Any() ? Arguments : Directory.GetFiles(Directory.GetCurrentDirectory());
return GetInputFile(files);
}
internal static string GetInputFile(IEnumerable<string> files)
{
var candidates = files.Where(file => _allowedExtensions.Contains(Path.GetExtension(file)))
.ToList();
switch (candidates.Count)
{
case 1:
return candidates.Single();
case 2:
// Remove all nuspec files
candidates.RemoveAll(file => Path.GetExtension(file).Equals(Constants.ManifestExtension, StringComparison.OrdinalIgnoreCase));
if (candidates.Count == 1)
{
return candidates.Single();
}
goto default;
default:
throw new CommandLineException(LocalizedResourceManager.GetString("PackageCommandSpecifyInputFileError"));
}
}
private class DictionaryPropertyProvider : IPropertyProvider
{
private readonly IDictionary<string, string> _properties;
public DictionaryPropertyProvider(IDictionary<string, string> properties)
{
_properties = properties;
}
public dynamic GetPropertyValue(string propertyName)
{
string value;
if (_properties.TryGetValue(propertyName, out value))
{
return value;
}
return null;
}
}
}
}
| |
using FFImageLoading.Forms;
using FFImageLoading.Work;
using FFImageLoading.Extensions;
using FFImageLoading.Forms.Args;
using System;
using System.ComponentModel;
using Windows.Graphics.Imaging;
using System.Threading.Tasks;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Storage.Streams;
using System.IO;
#if WINDOWS_UWP
using FFImageLoading.Forms.WinUWP;
using Xamarin.Forms.Platform.UWP;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Controls;
#elif SILVERLIGHT
using FFImageLoading.Forms.WinSL;
using Xamarin.Forms.Platform.WinPhone;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
#else
using FFImageLoading.Forms.WinRT;
using Xamarin.Forms.Platform.WinRT;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Controls;
#endif
#if WINDOWS_UWP
[assembly: ExportRenderer(typeof(CachedImage), typeof(CachedImageRenderer))]
namespace FFImageLoading.Forms.WinUWP
#elif SILVERLIGHT
[assembly: Xamarin.Forms.ExportRenderer(typeof(CachedImage), typeof(CachedImageRenderer))]
namespace FFImageLoading.Forms.WinSL
#else
[assembly: ExportRenderer(typeof(CachedImage), typeof(CachedImageRenderer))]
namespace FFImageLoading.Forms.WinRT
#endif
{
/// <summary>
/// CachedImage Implementation
/// </summary>
#if SILVERLIGHT
public class CachedImageRenderer : ViewRenderer<CachedImage, Image>, IDisposable
#else
public class CachedImageRenderer : ViewRenderer<CachedImage, Image>
#endif
{
private IScheduledWork _currentTask;
/// <summary>
/// Used for registration with dependency service
/// </summary>
public static void Init()
{
CachedImage.InternalClearCache = new Action<FFImageLoading.Cache.CacheType>(ClearCache);
CachedImage.InternalInvalidateCache = new Action<string, FFImageLoading.Cache.CacheType>(InvalidateCache);
CachedImage.InternalSetPauseWork = new Action<bool>(SetPauseWork);
}
private static void InvalidateCache(string key, Cache.CacheType cacheType)
{
ImageService.Invalidate(key, cacheType);
}
private static void ClearCache(Cache.CacheType cacheType)
{
switch (cacheType)
{
case Cache.CacheType.Memory:
ImageService.InvalidateMemoryCache();
break;
case Cache.CacheType.Disk:
ImageService.InvalidateDiskCache();
break;
case Cache.CacheType.All:
ImageService.InvalidateMemoryCache();
ImageService.InvalidateDiskCache();
break;
}
}
private static void SetPauseWork(bool pauseWork)
{
ImageService.SetPauseWork(pauseWork);
}
private bool measured;
public override Xamarin.Forms.SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint)
{
var bitmapSource = Control.Source as BitmapSource;
if (bitmapSource == null)
return new Xamarin.Forms.SizeRequest();
measured = true;
return new Xamarin.Forms.SizeRequest(new Xamarin.Forms.Size()
{
Width = bitmapSource.PixelWidth,
Height = bitmapSource.PixelHeight
});
}
protected override void OnElementChanged(ElementChangedEventArgs<CachedImage> e)
{
base.OnElementChanged(e);
if (e.NewElement == null)
return;
if (Control == null)
{
Image control = new Image()
{
Stretch = GetStretch(Xamarin.Forms.Aspect.AspectFill)
};
control.ImageOpened += OnImageOpened;
SetNativeControl(control);
}
if (e.NewElement != null)
{
e.NewElement.InternalCancel = new Action(Cancel);
e.NewElement.InternalGetImageAsJPG = new Func<GetImageAsJpgArgs, Task<byte[]>>(GetImageAsJpgAsync);
e.NewElement.InternalGetImageAsPNG = new Func<GetImageAsPngArgs, Task<byte[]>>(GetImageAsPngAsync);
}
UpdateSource();
UpdateAspect();
}
#if SILVERLIGHT
public void Dispose()
{
if (Control != null)
{
Control.ImageOpened -= OnImageOpened;
}
}
#else
protected override void Dispose(bool disposing)
{
if (Control != null)
{
Control.ImageOpened -= OnImageOpened;
}
base.Dispose(disposing);
}
#endif
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == CachedImage.SourceProperty.PropertyName)
{
UpdateSource();
}
else
{
if (!(e.PropertyName == CachedImage.AspectProperty.PropertyName))
return;
UpdateAspect();
}
}
private void OnImageOpened(object sender, RoutedEventArgs routedEventArgs)
{
if (measured)
{
((Xamarin.Forms.IVisualElementController)Element).NativeSizeChanged();
}
}
private async void UpdateSource()
{
((Xamarin.Forms.IElementController)Element).SetValueFromRenderer(CachedImage.IsLoadingPropertyKey, true);
Xamarin.Forms.ImageSource source = Element.Source;
Cancel();
TaskParameter imageLoader = null;
var ffSource = await ImageSourceBinding.GetImageSourceBinding(source).ConfigureAwait(false);
if (ffSource == null)
{
if (Control != null)
Control.Source = null;
ImageLoadingFinished(Element);
}
else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.Url)
{
imageLoader = ImageService.LoadUrl(ffSource.Path, Element.CacheDuration);
}
else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.CompiledResource)
{
imageLoader = ImageService.LoadCompiledResource(ffSource.Path);
}
else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.ApplicationBundle)
{
imageLoader = ImageService.LoadFileFromApplicationBundle(ffSource.Path);
}
else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.Filepath)
{
imageLoader = ImageService.LoadFile(ffSource.Path);
}
else if (ffSource.ImageSource == FFImageLoading.Work.ImageSource.Stream)
{
imageLoader = ImageService.LoadStream(ffSource.Stream);
}
if (imageLoader != null)
{
// CustomKeyFactory
if (Element.CacheKeyFactory != null)
{
var bindingContext = Element.BindingContext;
imageLoader.CacheKey(Element.CacheKeyFactory.GetKey(source, bindingContext));
}
// LoadingPlaceholder
if (Element.LoadingPlaceholder != null)
{
var placeholderSource = await ImageSourceBinding.GetImageSourceBinding(Element.LoadingPlaceholder).ConfigureAwait(false);
if (placeholderSource != null)
imageLoader.LoadingPlaceholder(placeholderSource.Path, placeholderSource.ImageSource);
}
// ErrorPlaceholder
if (Element.ErrorPlaceholder != null)
{
var placeholderSource = await ImageSourceBinding.GetImageSourceBinding(Element.ErrorPlaceholder).ConfigureAwait(false);
if (placeholderSource != null)
imageLoader.ErrorPlaceholder(placeholderSource.Path, placeholderSource.ImageSource);
}
// Downsample
if (Element.DownsampleToViewSize && (Element.Width > 0 || Element.Height > 0))
{
if (Element.Height > Element.Width)
{
imageLoader.DownSample(height: Element.Height.PointsToPixels());
}
else
{
imageLoader.DownSample(width: Element.Width.PointsToPixels());
}
}
else if (Element.DownsampleToViewSize && (Element.WidthRequest > 0 || Element.HeightRequest > 0))
{
if (Element.HeightRequest > Element.WidthRequest)
{
imageLoader.DownSample(height: Element.HeightRequest.PointsToPixels());
}
else
{
imageLoader.DownSample(width: Element.WidthRequest.PointsToPixels());
}
}
else if ((int)Element.DownsampleHeight != 0 || (int)Element.DownsampleWidth != 0)
{
if (Element.DownsampleHeight > Element.DownsampleWidth)
{
imageLoader.DownSample(height: Element.DownsampleUseDipUnits
? Element.DownsampleHeight.PointsToPixels() : (int)Element.DownsampleHeight);
}
else
{
imageLoader.DownSample(width: Element.DownsampleUseDipUnits
? Element.DownsampleWidth.PointsToPixels() : (int)Element.DownsampleWidth);
}
}
// RetryCount
if (Element.RetryCount > 0)
{
imageLoader.Retry(Element.RetryCount, Element.RetryDelay);
}
// TransparencyChannel
if (Element.TransparencyEnabled.HasValue)
imageLoader.TransparencyChannel(Element.TransparencyEnabled.Value);
// FadeAnimation
if (Element.FadeAnimationEnabled.HasValue)
imageLoader.FadeAnimation(Element.FadeAnimationEnabled.Value);
// TransformPlaceholders
if (Element.TransformPlaceholders.HasValue)
imageLoader.TransformPlaceholders(Element.TransformPlaceholders.Value);
// Transformations
if (Element.Transformations != null && Element.Transformations.Count > 0)
{
imageLoader.Transform(Element.Transformations);
}
var element = Element;
imageLoader.Finish((work) =>
{
element.OnFinish(new CachedImageEvents.FinishEventArgs(work));
ImageLoadingFinished(element);
});
imageLoader.Success((imageSize, loadingResult) =>
element.OnSuccess(new CachedImageEvents.SuccessEventArgs(imageSize, loadingResult)));
imageLoader.Error((exception) =>
element.OnError(new CachedImageEvents.ErrorEventArgs(exception)));
_currentTask = imageLoader.Into(Control);
}
}
private void UpdateAspect()
{
Control.Stretch = GetStretch(Element.Aspect);
}
private static Stretch GetStretch(Xamarin.Forms.Aspect aspect)
{
switch (aspect)
{
case Xamarin.Forms.Aspect.AspectFill:
return Stretch.UniformToFill;
case Xamarin.Forms.Aspect.Fill:
return Stretch.Fill;
default:
return Stretch.Uniform;
}
}
private void ImageLoadingFinished(CachedImage element)
{
if (element != null)
{
((Xamarin.Forms.IElementController)element).SetValueFromRenderer(CachedImage.IsLoadingPropertyKey, false);
((Xamarin.Forms.IVisualElementController)element).NativeSizeChanged();
element.InvalidateViewMeasure();
}
}
private void Cancel()
{
if (_currentTask != null && !_currentTask.IsCancelled)
{
_currentTask.Cancel();
}
}
private Task<byte[]> GetImageAsJpgAsync(GetImageAsJpgArgs args)
{
return GetImageAsByteAsync(BitmapEncoder.JpegEncoderId, args.Quality, args.DesiredWidth, args.DesiredHeight);
}
private Task<byte[]> GetImageAsPngAsync(GetImageAsPngArgs args)
{
return GetImageAsByteAsync(BitmapEncoder.PngEncoderId, 90, args.DesiredWidth, args.DesiredHeight);
}
private async Task<byte[]> GetImageAsByteAsync(Guid format, int quality, int desiredWidth, int desiredHeight)
{
if (Control == null || Control.Source == null)
return null;
var bitmap = Control.Source as WriteableBitmap;
if (bitmap == null)
return null;
byte[] pixels = null;
uint pixelsWidth = (uint)bitmap.PixelWidth;
uint pixelsHeight = (uint)bitmap.PixelHeight;
if (desiredWidth != 0 || desiredHeight != 0)
{
double widthRatio = (double)desiredWidth / (double)bitmap.PixelWidth;
double heightRatio = (double)desiredHeight / (double)bitmap.PixelHeight;
double scaleRatio = Math.Min(widthRatio, heightRatio);
if (desiredWidth == 0)
scaleRatio = heightRatio;
if (desiredHeight == 0)
scaleRatio = widthRatio;
uint aspectWidth = (uint)((double)bitmap.PixelWidth * scaleRatio);
uint aspectHeight = (uint)((double)bitmap.PixelHeight * scaleRatio);
using (var tempStream = new InMemoryRandomAccessStream())
{
byte[] tempPixels = await GetBytesFromBitmapAsync(bitmap);
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, tempStream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
pixelsWidth, pixelsHeight, 96, 96, tempPixels);
await encoder.FlushAsync();
tempStream.Seek(0);
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(tempStream);
BitmapTransform transform = new BitmapTransform()
{
ScaledWidth = aspectWidth,
ScaledHeight = aspectHeight,
InterpolationMode = BitmapInterpolationMode.Linear
};
PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);
pixels = pixelData.DetachPixelData();
pixelsWidth = aspectWidth;
pixelsHeight = aspectHeight;
}
}
else
{
pixels = await GetBytesFromBitmapAsync(bitmap);
}
using (var stream = new InMemoryRandomAccessStream())
{
var encoder = await BitmapEncoder.CreateAsync(format, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
pixelsWidth, pixelsHeight, 96, 96, pixels);
await encoder.FlushAsync();
stream.Seek(0);
var bytes = new byte[stream.Size];
await stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None);
return bytes;
}
}
private async Task<byte[]> GetBytesFromBitmapAsync(WriteableBitmap bitmap)
{
#if SILVERLIGHT
return await Task.FromResult(bitmap.ToByteArray());
#else
byte[] tempPixels;
using (var sourceStream = bitmap.PixelBuffer.AsStream())
{
tempPixels = new byte[sourceStream.Length];
await sourceStream.ReadAsync(tempPixels, 0, tempPixels.Length).ConfigureAwait(false);
}
return tempPixels;
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using ServicoDeBooking.Areas.HelpPage.ModelDescriptions;
using ServicoDeBooking.Areas.HelpPage.Models;
namespace ServicoDeBooking.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
if (complexTypeDescription != null)
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using FluentAssertions;
using JsonApiDotNetCore.Serialization.Objects;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.Serialization
{
public sealed class ETagTests : IClassFixture<IntegrationTestContext<TestableStartup<SerializationDbContext>, SerializationDbContext>>
{
private readonly IntegrationTestContext<TestableStartup<SerializationDbContext>, SerializationDbContext> _testContext;
private readonly SerializationFakers _fakers = new();
public ETagTests(IntegrationTestContext<TestableStartup<SerializationDbContext>, SerializationDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<MeetingAttendeesController>();
testContext.UseController<MeetingsController>();
}
[Fact]
public async Task Returns_ETag_for_HEAD_request()
{
// Arrange
List<Meeting> meetings = _fakers.Meeting.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Meeting>();
dbContext.Meetings.AddRange(meetings);
await dbContext.SaveChangesAsync();
});
const string route = "/meetings";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteHeadAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
httpResponse.Headers.ETag.Should().NotBeNull();
httpResponse.Headers.ETag!.IsWeak.Should().BeFalse();
httpResponse.Headers.ETag.Tag.Should().NotBeNullOrEmpty();
responseDocument.Should().BeEmpty();
}
[Fact]
public async Task Returns_ETag_for_GET_request()
{
// Arrange
List<Meeting> meetings = _fakers.Meeting.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Meeting>();
dbContext.Meetings.AddRange(meetings);
await dbContext.SaveChangesAsync();
});
const string route = "/meetings";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
httpResponse.Headers.ETag.Should().NotBeNull();
httpResponse.Headers.ETag!.IsWeak.Should().BeFalse();
httpResponse.Headers.ETag.Tag.Should().NotBeNullOrEmpty();
responseDocument.Should().NotBeEmpty();
}
[Fact]
public async Task Returns_no_ETag_for_failed_GET_request()
{
// Arrange
string route = $"/meetings/{Unknown.StringId.For<Meeting, Guid>()}";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound);
httpResponse.Headers.ETag.Should().BeNull();
responseDocument.Should().NotBeEmpty();
}
[Fact]
public async Task Returns_no_ETag_for_POST_request()
{
// Arrange
string newTitle = _fakers.Meeting.Generate().Title;
var requestBody = new
{
data = new
{
type = "meetings",
attributes = new
{
title = newTitle
}
}
};
const string route = "/meetings";
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
httpResponse.Headers.ETag.Should().BeNull();
responseDocument.Should().NotBeEmpty();
}
[Fact]
public async Task Fails_on_ETag_in_PATCH_request()
{
// Arrange
Meeting existingMeeting = _fakers.Meeting.Generate();
string newTitle = _fakers.Meeting.Generate().Title;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Meetings.Add(existingMeeting);
await dbContext.SaveChangesAsync();
});
var requestBody = new
{
data = new
{
type = "meetings",
id = existingMeeting.StringId,
attributes = new
{
title = newTitle
}
}
};
string route = $"/meetings/{existingMeeting.StringId}";
Action<HttpRequestHeaders> setRequestHeaders = headers =>
{
headers.IfMatch.ParseAdd("\"12345\"");
};
// Act
(HttpResponseMessage httpResponse, Document responseDocument) =
await _testContext.ExecutePatchAsync<Document>(route, requestBody, setRequestHeaders: setRequestHeaders);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.PreconditionFailed);
responseDocument.Errors.Should().HaveCount(1);
ErrorObject error = responseDocument.Errors[0];
error.StatusCode.Should().Be(HttpStatusCode.PreconditionFailed);
error.Title.Should().Be("Detection of mid-air edit collisions using ETags is not supported.");
error.Detail.Should().BeNull();
error.Source.Header.Should().Be("If-Match");
}
[Fact]
public async Task Returns_NotModified_for_matching_ETag()
{
// Arrange
List<Meeting> meetings = _fakers.Meeting.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Meeting>();
dbContext.Meetings.AddRange(meetings);
await dbContext.SaveChangesAsync();
});
const string route = "/meetings";
(HttpResponseMessage httpResponse1, _) = await _testContext.ExecuteGetAsync<string>(route);
string responseETag = httpResponse1.Headers.ETag!.Tag;
Action<HttpRequestHeaders> setRequestHeaders2 = headers =>
{
headers.IfNoneMatch.ParseAdd($"\"12345\", W/\"67890\", {responseETag}");
};
// Act
(HttpResponseMessage httpResponse2, string responseDocument2) = await _testContext.ExecuteGetAsync<string>(route, setRequestHeaders2);
// Assert
httpResponse2.Should().HaveStatusCode(HttpStatusCode.NotModified);
httpResponse2.Headers.ETag.Should().NotBeNull();
httpResponse2.Headers.ETag!.IsWeak.Should().BeFalse();
httpResponse2.Headers.ETag.Tag.Should().NotBeNullOrEmpty();
responseDocument2.Should().BeEmpty();
}
[Fact]
public async Task Returns_content_for_mismatching_ETag()
{
// Arrange
List<Meeting> meetings = _fakers.Meeting.Generate(2);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<Meeting>();
dbContext.Meetings.AddRange(meetings);
await dbContext.SaveChangesAsync();
});
const string route = "/meetings";
Action<HttpRequestHeaders> setRequestHeaders = headers =>
{
headers.IfNoneMatch.ParseAdd("\"Not-a-matching-value\"");
};
// Act
(HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteGetAsync<string>(route, setRequestHeaders);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
httpResponse.Headers.ETag.Should().NotBeNull();
httpResponse.Headers.ETag!.IsWeak.Should().BeFalse();
httpResponse.Headers.ETag.Tag.Should().NotBeNullOrEmpty();
responseDocument.Should().NotBeEmpty();
}
}
}
| |
using NUnit.Framework;
namespace 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.
*/
/// <summary>
/// TestExplanations subclass focusing on span queries
/// </summary>
[TestFixture]
public class TestSpanExplanations : TestExplanations
{
/* simple SpanTermQueries */
[Test]
public virtual void TestST1()
{
SpanQuery q = St("w1");
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestST2()
{
SpanQuery q = St("w1");
q.Boost = 1000;
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestST4()
{
SpanQuery q = St("xx");
Qtest(q, new int[] { 2, 3 });
}
[Test]
public virtual void TestST5()
{
SpanQuery q = St("xx");
q.Boost = 1000;
Qtest(q, new int[] { 2, 3 });
}
/* some SpanFirstQueries */
[Test]
public virtual void TestSF1()
{
SpanQuery q = Sf(("w1"), 1);
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSF2()
{
SpanQuery q = Sf(("w1"), 1);
q.Boost = 1000;
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSF4()
{
SpanQuery q = Sf(("xx"), 2);
Qtest(q, new int[] { 2 });
}
[Test]
public virtual void TestSF5()
{
SpanQuery q = Sf(("yy"), 2);
Qtest(q, new int[] { });
}
[Test]
public virtual void TestSF6()
{
SpanQuery q = Sf(("yy"), 4);
q.Boost = 1000;
Qtest(q, new int[] { 2 });
}
/* some SpanOrQueries */
[Test]
public virtual void TestSO1()
{
SpanQuery q = Sor("w1", "QQ");
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSO2()
{
SpanQuery q = Sor("w1", "w3", "zz");
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSO3()
{
SpanQuery q = Sor("w5", "QQ", "yy");
Qtest(q, new int[] { 0, 2, 3 });
}
[Test]
public virtual void TestSO4()
{
SpanQuery q = Sor("w5", "QQ", "yy");
Qtest(q, new int[] { 0, 2, 3 });
}
/* some SpanNearQueries */
[Test]
public virtual void TestSNear1()
{
SpanQuery q = Snear("w1", "QQ", 100, true);
Qtest(q, new int[] { });
}
[Test]
public virtual void TestSNear2()
{
SpanQuery q = Snear("w1", "xx", 100, true);
Qtest(q, new int[] { 2, 3 });
}
[Test]
public virtual void TestSNear3()
{
SpanQuery q = Snear("w1", "xx", 0, true);
Qtest(q, new int[] { 2 });
}
[Test]
public virtual void TestSNear4()
{
SpanQuery q = Snear("w1", "xx", 1, true);
Qtest(q, new int[] { 2, 3 });
}
[Test]
public virtual void TestSNear5()
{
SpanQuery q = Snear("xx", "w1", 0, false);
Qtest(q, new int[] { 2 });
}
[Test]
public virtual void TestSNear6()
{
SpanQuery q = Snear("w1", "w2", "QQ", 100, true);
Qtest(q, new int[] { });
}
[Test]
public virtual void TestSNear7()
{
SpanQuery q = Snear("w1", "xx", "w2", 100, true);
Qtest(q, new int[] { 2, 3 });
}
[Test]
public virtual void TestSNear8()
{
SpanQuery q = Snear("w1", "xx", "w2", 0, true);
Qtest(q, new int[] { 2 });
}
[Test]
public virtual void TestSNear9()
{
SpanQuery q = Snear("w1", "xx", "w2", 1, true);
Qtest(q, new int[] { 2, 3 });
}
[Test]
public virtual void TestSNear10()
{
SpanQuery q = Snear("xx", "w1", "w2", 0, false);
Qtest(q, new int[] { 2 });
}
[Test]
public virtual void TestSNear11()
{
SpanQuery q = Snear("w1", "w2", "w3", 1, true);
Qtest(q, new int[] { 0, 1 });
}
/* some SpanNotQueries */
[Test]
public virtual void TestSNot1()
{
SpanQuery q = Snot(Sf("w1", 10), St("QQ"));
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSNot2()
{
SpanQuery q = Snot(Sf("w1", 10), St("QQ"));
q.Boost = 1000;
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSNot4()
{
SpanQuery q = Snot(Sf("w1", 10), St("xx"));
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSNot5()
{
SpanQuery q = Snot(Sf("w1", 10), St("xx"));
q.Boost = 1000;
Qtest(q, new int[] { 0, 1, 2, 3 });
}
[Test]
public virtual void TestSNot7()
{
SpanQuery f = Snear("w1", "w3", 10, true);
f.Boost = 1000;
SpanQuery q = Snot(f, St("xx"));
Qtest(q, new int[] { 0, 1, 3 });
}
[Test]
public virtual void TestSNot10()
{
SpanQuery t = St("xx");
t.Boost = 10000;
SpanQuery q = Snot(Snear("w1", "w3", 10, true), t);
Qtest(q, new int[] { 0, 1, 3 });
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
namespace System.Collections.Specialized.Tests
{
public class GetItemIntTests
{
[Fact]
public void Test01()
{
BitVector32 bv32;
int data = 0;
// array of positions to get bit for
int[] bits =
{
0, // bits[0] = 0
1, // bits[1] = 1
2, // bits[2] = 2
3, // bits[3] = 3
7, // bits[4] = 7
15, // bits[5] = 15
16, // bits[6] = 16
Int16.MaxValue, // bits[7] = Int16.MaxValue
Int32.MaxValue - 1, // bits[8] = Int32.MaxValue - 1
Int32.MinValue, // bits[9] = Int32.MinValue
Int16.MinValue, // bits[10] = Int16.MinValue
-1 // bits[11] = -1
};
// [] BitVector is constructed as expected and bit flags are as expected
//-----------------------------------------------------------------
bv32 = new BitVector32();
if (bv32.Data != 0)
{
Assert.False(true, string.Format("Error, Data = {0} after default ctor", bv32.Data));
}
// loop through bits
// all values should return false except 0
bool expected = false;
for (int i = 0; i < bits.Length; i++)
{
if (i == 0)
expected = true;
else
expected = false;
if (bv32[bits[i]] != expected)
{
Assert.False(true, string.Format("Error, bit[{3}]: returned {1} instead of {2}", i, bv32[bits[i]], expected, bits[i]));
}
}
//
// (-1)
//
data = -1;
bv32 = new BitVector32(data);
if (bv32.Data != data)
{
Assert.False(true, string.Format("Error, Data = {0} ", bv32.Data));
}
// loop through bits
// all values should return true
expected = true;
for (int i = 0; i < bits.Length; i++)
{
if (bv32[bits[i]] != expected)
{
string temp = "Error" + i;
Assert.False(true, string.Format("{0}: bit[{3}]: returned {1} instead of {2}", temp, bv32[bits[i]], expected, bits[i]));
}
}
//
// Int32.MaxValue
//
data = Int32.MaxValue;
bv32 = new BitVector32(data);
if (bv32.Data != data)
{
Assert.False(true, string.Format("Error, Data = {0} ", bv32.Data));
}
// loop through bits
// positive values should return true, negative should return false
for (int i = 0; i < bits.Length; i++)
{
if (i == (bits.Length - 1) || i == (bits.Length - 2) || i == (bits.Length - 3))
expected = false;
else
expected = true;
if (bv32[bits[i]] != expected)
{
string temp = "Error" + i;
Assert.False(true, string.Format("{0}: bit[{3}]: returned {1} instead of {2}", temp, bv32[bits[i]], expected, bits[i]));
}
}
//
// Int32.MinValue
//
data = Int32.MinValue;
bv32 = new BitVector32(data);
if (bv32.Data != data)
{
Assert.False(true, string.Format("Error, Data = {0} ", bv32.Data));
}
// loop through bits
// all values should return false, except 0, 9 = true
for (int i = 0; i < bits.Length; i++)
{
if (i == 0 || i == 9)
expected = true;
else
expected = false;
if (bv32[bits[i]] != expected)
{
string temp = "Error" + i;
Assert.False(true, string.Format("{0}: bit[{3}]: returned {1} instead of {2}", temp, bv32[bits[i]], expected, bits[i]));
}
}
//
// 1
//
data = 1;
bv32 = new BitVector32(data);
if (bv32.Data != data)
{
Assert.False(true, string.Format("Error, Data = {0} ", bv32.Data));
}
// loop through bits
// all values should return false, except 0, 1 = true
for (int i = 0; i < bits.Length; i++)
{
if (i == 0 || i == 1)
expected = true;
else
expected = false;
if (bv32[bits[i]] != expected)
{
string temp = "Error" + i;
Assert.False(true, string.Format("{0}: bit[{3}]: returned {1} instead of {2}", temp, bv32[bits[i]], expected, bits[i]));
}
}
//
// 2
//
data = 2;
bv32 = new BitVector32(data);
if (bv32.Data != data)
{
Assert.False(true, string.Format("Error, Data = {0} ", bv32.Data));
}
// loop through bits
// all values should return false, except 0, 2 = true
for (int i = 0; i < bits.Length; i++)
{
if (i == 0 || i == 2)
expected = true;
else
expected = false;
if (bv32[bits[i]] != expected)
{
string temp = "Error" + i;
Assert.False(true, string.Format("{0}: bit[{3}]: returned {1} instead of {2}", temp, bv32[bits[i]], expected, bits[i]));
}
}
//
// 3
//
data = 3;
bv32 = new BitVector32(data);
if (bv32.Data != data)
{
Assert.False(true, string.Format("Error, Data = {0} ", bv32.Data));
}
// loop through bits
// all values should return false, except 0, 1, 2, 3 = true
for (int i = 0; i < bits.Length; i++)
{
if (i < 4)
expected = true;
else
expected = false;
if (bv32[bits[i]] != expected)
{
string temp = "Error" + i;
Assert.False(true, string.Format("{0}: bit[{3}]: returned {1} instead of {2}", temp, bv32[bits[i]], expected, bits[i]));
}
}
//
// 7
//
data = 7;
bv32 = new BitVector32(data);
if (bv32.Data != data)
{
Assert.False(true, string.Format("Error, Data = {0} ", bv32.Data));
}
// loop through bits
// all values should return false, except 0, 1, 2, 3, 7 = true
for (int i = 0; i < bits.Length; i++)
{
if (i < 5)
expected = true;
else
expected = false;
if (bv32[bits[i]] != expected)
{
string temp = "Error" + i;
Assert.False(true, string.Format("{0}: bit[{3}]: returned {1} instead of {2}", temp, bv32[bits[i]], expected, bits[i]));
}
}
//
// Int16.MaxValue
//
data = Int16.MaxValue;
bv32 = new BitVector32(data);
if (bv32.Data != data)
{
Assert.False(true, string.Format("Error, Data = {0} ", bv32.Data));
}
// loop through bits
// all values should return true, except for last 3
for (int i = 0; i < bits.Length; i++)
{
if (i < 8)
expected = true;
else
expected = false;
if (bv32[bits[i]] != expected)
{
string temp = "Err" + i;
Assert.False(true, string.Format("{0}: bit[{3}]: returned {1} instead of {2}", temp, bv32[bits[i]], expected, bits[i]));
}
}
//
// Int16.MinValue
//
data = Int16.MinValue;
bv32 = new BitVector32(data);
if (bv32.Data != data)
{
Assert.False(true, string.Format("Error, Data = {0} ", bv32.Data));
}
// loop through bits
// all values should return false, except for 0, 9, 10
for (int i = 0; i < bits.Length; i++)
{
if (i == 0 || i == 9 || i == 10)
expected = true;
else
expected = false;
if (bv32[bits[i]] != expected)
{
string temp = "Error" + i;
Assert.False(true, string.Format("{0}: bit[{3}]: returned {1} instead of {2}", temp, bv32[bits[i]], expected, bits[i]));
}
}
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2013 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.Generic;
using System.Diagnostics.Contracts;
#if NETFX_CORE
using System.Reflection;
#endif
using System.Runtime.CompilerServices;
using System.Threading;
using System.Security;
namespace MsgPack.Serialization
{
/// <summary>
/// Repository for key type with RWlock scheme.
/// </summary>
internal class TypeKeyRepository : IDisposable
{
private volatile int _isFrozen;
public bool IsFrozen
{
get { return this._isFrozen != 0; }
}
private readonly ReaderWriterLockSlim _lock;
private readonly Dictionary<RuntimeTypeHandle, object> _table;
public TypeKeyRepository() : this( default( TypeKeyRepository ) ) { }
public TypeKeyRepository( TypeKeyRepository copiedFrom )
{
this._lock = new ReaderWriterLockSlim( LockRecursionPolicy.NoRecursion );
if ( copiedFrom == null )
{
this._table = new Dictionary<RuntimeTypeHandle, object>();
}
else
{
this._table = copiedFrom.GetClonedTable();
}
}
public TypeKeyRepository( Dictionary<RuntimeTypeHandle, object> table )
{
this._lock = new ReaderWriterLockSlim( LockRecursionPolicy.NoRecursion );
this._table = table;
}
public void Dispose()
{
this.Dispose( true );
GC.SuppressFinalize( this );
}
protected virtual void Dispose( bool disposing )
{
if ( disposing )
{
this._lock.Dispose();
}
}
#if !PARTIAL_TRUST && !SILVERLIGHT
[SecuritySafeCritical]
#endif
private Dictionary<RuntimeTypeHandle, object> GetClonedTable()
{
bool holdsReadLock = false;
#if !SILVERLIGHT && !NETFX_CORE
RuntimeHelpers.PrepareConstrainedRegions();
#endif
try { }
finally
{
this._lock.EnterReadLock();
holdsReadLock = true;
}
#if !SILVERLIGHT && !NETFX_CORE
RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
return new Dictionary<RuntimeTypeHandle, object>( this._table );
}
finally
{
if ( holdsReadLock )
{
this._lock.ExitReadLock();
}
}
}
public bool Get( Type type, out object matched, out object genericDefinitionMatched )
{
return this.GetCore( type, out matched, out genericDefinitionMatched );
}
#if !PARTIAL_TRUST && !SILVERLIGHT
[SecuritySafeCritical]
#endif
private bool GetCore( Type type, out object matched, out object genericDefinitionMatched )
{
bool holdsReadLock = false;
#if !SILVERLIGHT && !NETFX_CORE
RuntimeHelpers.PrepareConstrainedRegions();
#endif
try { }
finally
{
this._lock.EnterReadLock();
holdsReadLock = true;
}
#if !SILVERLIGHT && !NETFX_CORE
RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
object result;
if ( this._table.TryGetValue( type.TypeHandle, out result ) )
{
matched = result;
genericDefinitionMatched = null;
return true;
}
if ( type.GetIsGenericType() )
{
if ( this._table.TryGetValue( type.GetGenericTypeDefinition().TypeHandle, out result ) )
{
matched = null;
genericDefinitionMatched = result;
return true;
}
}
matched = null;
genericDefinitionMatched = null;
return false;
}
finally
{
if ( holdsReadLock )
{
this._lock.ExitReadLock();
}
}
}
public void Freeze()
{
this._isFrozen = 1;
}
public bool Register( Type type, object entry, bool allowOverwrite )
{
Contract.Assert( entry != null );
if ( this.IsFrozen )
{
throw new InvalidOperationException( "This repository is frozen." );
}
return this.RegisterCore( type, entry, allowOverwrite );
}
#if !PARTIAL_TRUST && !SILVERLIGHT
[SecuritySafeCritical]
#endif
private bool RegisterCore( Type key, object value, bool allowOverwrite )
{
if ( allowOverwrite || !this._table.ContainsKey( key.TypeHandle ) )
{
bool holdsWriteLock = false;
#if !SILVERLIGHT && !NETFX_CORE
RuntimeHelpers.PrepareConstrainedRegions();
#endif
try { }
finally
{
this._lock.EnterWriteLock();
holdsWriteLock = true;
}
#if !SILVERLIGHT && !NETFX_CORE
RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
if ( allowOverwrite || !this._table.ContainsKey( key.TypeHandle ) )
{
this._table[ key.TypeHandle ] = value;
return true;
}
}
finally
{
if ( holdsWriteLock )
{
this._lock.ExitWriteLock();
}
}
}
return false;
}
public bool Unregister( Type type )
{
if ( this.IsFrozen )
{
throw new InvalidOperationException( "This repository is frozen." );
}
return this.UnregisterCore( type );
}
#if !PARTIAL_TRUST && !SILVERLIGHT
[SecuritySafeCritical]
#endif
private bool UnregisterCore( Type key )
{
if ( this._table.ContainsKey( key.TypeHandle ) )
{
bool holdsWriteLock = false;
#if !SILVERLIGHT && !NETFX_CORE
RuntimeHelpers.PrepareConstrainedRegions();
#endif
try { }
finally
{
this._lock.EnterWriteLock();
holdsWriteLock = true;
}
#if !SILVERLIGHT && !NETFX_CORE
RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
return this._table.Remove( key.TypeHandle );
}
finally
{
if ( holdsWriteLock )
{
this._lock.ExitWriteLock();
}
}
}
return false;
}
#if !PARTIAL_TRUST && !SILVERLIGHT
[SecuritySafeCritical]
#endif
internal bool Coontains( Type type )
{
bool holdsReadLock = false;
#if !SILVERLIGHT && !NETFX_CORE
RuntimeHelpers.PrepareConstrainedRegions();
#endif
try { }
finally
{
this._lock.EnterReadLock();
holdsReadLock = true;
}
#if !SILVERLIGHT && !NETFX_CORE
RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
return this._table.ContainsKey( type.TypeHandle );
}
finally
{
if ( holdsReadLock )
{
this._lock.ExitReadLock();
}
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using OpenLiveWriter.Api;
using OpenLiveWriter.ApplicationFramework.Skinning;
using OpenLiveWriter.BlogClient.Detection;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.HtmlEditor;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.HtmlParser.Parser;
using OpenLiveWriter.Localization;
//using OpenLiveWriter.SpellChecker;
namespace OpenLiveWriter.PostEditor.PostHtmlEditing
{
public class BlogPostHtmlSourceEditorControl : UserControl, IBlogPostHtmlEditor
{
private Panel panelSourceEditor;
private TextBox textBoxTitle;
private HtmlSourceEditorControl sourceControl;
//private readonly IBlogPostSpellCheckingContext spellingContext;
private IBlogPostImageEditingContext editingContext;
//ToDo: OLW Spell Checker
//public BlogPostHtmlSourceEditorControl(IBlogPostSpellCheckingContext spellingContext, CommandManager commandManager, IBlogPostImageEditingContext editingContext)
public BlogPostHtmlSourceEditorControl(CommandManager commandManager, IBlogPostImageEditingContext editingContext)
{
//this.spellingContext = spellingContext;
this.editingContext = editingContext;
InitializeComponent();
//sourceControl = new HtmlSourceEditorControl(spellingContext.SpellingChecker, commandManager, editingContext);
sourceControl = new HtmlSourceEditorControl(commandManager, editingContext);
sourceControl.EditorControl.TextChanged += new EventHandler(EditorControl_TextChanged);
sourceControl.EditorControl.GotFocus += new EventHandler(EditorControl_GotFocus);
BorderControl borderControl = new BorderControl();
borderControl.SuppressBottomBorder = true;
borderControl.Control = sourceControl.EditorControl;
borderControl.Dock = DockStyle.Fill;
panelSourceEditor.Controls.Add(borderControl);
ColorizedResources.Instance.RegisterControlForBackColorUpdates(this);
textBoxTitle.AccessibleName = Res.Get(StringId.PostEditorTitleRegion);
sourceControl.EditorControl.AccessibleName = Res.Get(StringId.PostEditorBodyRegion);
}
public SmartContentEditor CurrentEditor
{
get
{
return null;
}
}
void EditorControl_TextChanged(object sender, EventArgs e)
{
IsDirty = true;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (sourceControl != null)
sourceControl.Dispose();
}
base.Dispose(disposing);
}
public void ChangeSelection(SelectionPosition position)
{
sourceControl.ChangeSelection(position);
}
protected override void OnVisibleChanged(EventArgs e)
{
if (Visible)
BackColor = ColorizedResources.Instance.WorkspaceBackgroundColor;
base.OnVisibleChanged(e);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//set the default focus for the editor
TimerHelper.CallbackOnDelay(new InvokeInUIThreadDelegate(sourceControl.Focus), 50);
}
private void InitializeComponent()
{
this.textBoxTitle = new TextBox();
this.panelSourceEditor = new Panel();
this.SuspendLayout();
//
// textBoxTitle
//
this.textBoxTitle.Anchor = ((AnchorStyles)(((AnchorStyles.Top | AnchorStyles.Left)
| AnchorStyles.Right)));
this.textBoxTitle.Location = new Point(2, 0);
this.textBoxTitle.Name = "textBoxTitle";
this.textBoxTitle.Size = new Size(326, 20);
this.textBoxTitle.TabIndex = 0;
this.textBoxTitle.Text = "post title";
this.textBoxTitle.TextChanged += new EventHandler(this.textBoxTitle_TextChanged);
this.textBoxTitle.GotFocus += new EventHandler(this.textBoxTitle_TitleGotFocus);
//
// panelSourceEditor
//
this.panelSourceEditor.Anchor = ((AnchorStyles)((((AnchorStyles.Top | AnchorStyles.Bottom)
| AnchorStyles.Left)
| AnchorStyles.Right)));
this.panelSourceEditor.Location = new Point(2, 24);
this.panelSourceEditor.Name = "panelSourceEditor";
this.panelSourceEditor.Size = new Size(326, 272);
this.panelSourceEditor.TabIndex = 1;
//
// BlogPostHtmlSourceEditorControl
//
this.BackColor = SystemColors.Control;
this.Controls.Add(this.panelSourceEditor);
this.Controls.Add(this.textBoxTitle);
this.Name = "BlogPostHtmlSourceEditorControl";
this.Size = new Size(332, 296);
this.ResumeLayout(false);
}
#region IBlogPostHtmlEditor
public event EventHandler TitleChanged;
protected void OnTitleChanged()
{
titleIsDirty = true;
if (TitleChanged != null)
TitleChanged(this, EventArgs.Empty);
}
public event EventHandler EditableRegionFocusChanged;
public void UpdateEditingContext()
{
//ToDo: OLW Spell Checker
//sourceControl.SpellingChecker.StopChecking();
//sourceControl.SpellingChecker.StartChecking(spellingContext.PostSpellingContextDirectory);
}
private void textBoxTitle_TitleGotFocus(object sender, EventArgs e)
{
OnEditableRegionFocusChanged(new EditableRegionFocusChangedEventArgs(false));
sourceControl.InBody = false;
//sourceControl.CommandSource.CanInsertLink = false;
}
private void EditorControl_GotFocus(object sender, EventArgs e)
{
OnEditableRegionFocusChanged(new EditableRegionFocusChangedEventArgs(true));
}
protected virtual void OnEditableRegionFocusChanged(EventArgs e)
{
if (EditableRegionFocusChanged != null)
EditableRegionFocusChanged(this, e);
}
public void LoadHtmlFragment(string title, string postBodyHtml, string baseUrl, BlogEditingTemplate editingTemplate)
{
const int SPACE_BETWEEN_TITLE_AND_BODY = 4;
if (editingTemplate.ContainsTitle)
{
// Make sure the title textbox is showing if there is a title.
textBoxTitle.Visible = true;
panelSourceEditor.Top = textBoxTitle.Bottom + SPACE_BETWEEN_TITLE_AND_BODY;
panelSourceEditor.Height = Height - panelSourceEditor.Top;
textBoxTitle.Text = title;
}
else
{
// We need to hide the title textbox if there is no title.
textBoxTitle.Visible = false;
panelSourceEditor.Top = textBoxTitle.Top;
panelSourceEditor.Height = Height - panelSourceEditor.Top;
}
//make the post body HTML look pretty
postBodyHtml = ApplyPostBodyFormatting(postBodyHtml);
sourceControl.LoadHtmlFragment(postBodyHtml);
sourceControl.Focus();
}
public string GetEditedTitleHtml()
{
return textBoxTitle.Text;
}
public string GetEditedHtml(bool preferWellFormed)
{
return sourceControl.GetEditedHtml(preferWellFormed);
}
public string GetEditedHtmlFast()
{
return sourceControl.GetEditedHtmlFast();
}
IFocusableControl IBlogPostHtmlEditor.FocusControl
{
get { return new FocusableControl(this); }
}
void IBlogPostHtmlEditor.Focus()
{
sourceControl.Focus();
}
public void FocusTitle()
{
textBoxTitle.Focus();
}
public void FocusBody()
{
sourceControl.Focus();
}
public bool DocumentHasFocus()
{
return sourceControl.HasFocus;
}
public Control EditorControl
{
get { return this; }
}
public void LoadHtmlFile(string filePath)
{
sourceControl.LoadHtmlFile(filePath);
}
public string SelectedText
{
get
{
if (ActiveControl == this.textBoxTitle)
return textBoxTitle.Text;
else
return sourceControl.SelectedText;
}
}
public string SelectedHtml
{
get
{
if (ActiveControl == this.textBoxTitle)
return textBoxTitle.Text;
else
return sourceControl.SelectedHtml;
}
}
public void EmptySelection()
{
if (ActiveControl == this.textBoxTitle)
textBoxTitle.SelectionLength = 0;
else
sourceControl.EmptySelection();
}
public void InsertHtml(string content, bool moveSelectionRight)
{
sourceControl.InsertHtml(content, moveSelectionRight);
}
public void InsertHtml(string content, HtmlInsertionOptions options)
{
sourceControl.InsertHtml(content, options);
}
public void InsertLink(string url, string linkText, string linkTitle, string rel, bool newWindow)
{
sourceControl.InsertLink(url, linkText, linkTitle, rel, newWindow);
}
public void InsertHorizontalLine(bool plainText)
{
sourceControl.InsertHtml(plainText ? "<br />" + BlogPost.PlainTextHorizontalLine : BlogPost.HorizontalLine, true);
}
public void InsertClearBreak()
{
sourceControl.InsertHtml(BlogPost.ClearBreak, true);
}
public void InsertExtendedEntryBreak()
{
if (sourceControl.GetRawText().IndexOf(BlogPost.ExtendedEntryBreak) == -1)
{
sourceControl.InsertHtml(BlogPost.ExtendedEntryBreak, true);
}
}
public bool IsDirty
{
get { return sourceControl.IsDirty || titleIsDirty; }
set
{
sourceControl.IsDirty = value;
titleIsDirty = value;
}
}
bool titleIsDirty;
public event EventHandler IsDirtyEvent
{
add
{
sourceControl.IsDirtyEvent += value;
}
remove
{
sourceControl.IsDirtyEvent -= value;
}
}
public bool SuspendAutoSave
{
get { return sourceControl.SuspendAutoSave; }
}
public IHtmlEditorCommandSource CommandSource
{
get { return sourceControl.CommandSource; }
}
public bool FullyEditableRegionActive
{
get { return sourceControl.FullyEditableRegionActive; }
set { sourceControl.FullyEditableRegionActive = value; }
}
#endregion
#region Event handlers
private void textBoxTitle_TextChanged(object sender, EventArgs e)
{
OnTitleChanged();
}
#endregion
#region Private Helpers
private static string ApplyPostBodyFormatting(string postBodyHtml)
{
//If the extended entry break exists, put some line breaks around it so that it
//sits on its own line.
if (postBodyHtml.IndexOf(BlogPost.ExtendedEntryBreak) != -1)
{
string moreExtendedEntryBreakWS = String.Format(CultureInfo.InvariantCulture, "\r\n{0}\r\n", BlogPost.ExtendedEntryBreak);
if (postBodyHtml.IndexOf(moreExtendedEntryBreakWS) == -1)
postBodyHtml = postBodyHtml.Replace(BlogPost.ExtendedEntryBreak, moreExtendedEntryBreakWS);
}
return postBodyHtml;
}
#endregion
public bool SelectAndDelete(string startMaker, string endMarker)
{
return sourceControl.SelectAndDelete(startMaker, endMarker);
}
}
/// <summary>
/// Summary description for BlogPostHtmlSourceEditorControl.
/// </summary>
public class HtmlSourceEditorControl : HtmlEditor.HtmlSourceEditorControl
{
private ReplaceAbsoluteFilePathsOperation _replaceOperation = new ReplaceAbsoluteFilePathsOperation();
private IBlogPostImageEditingContext editingContext;
//ToDo: OLW Spell Checker
//public HtmlSourceEditorControl(ISpellingChecker spellingChecker, CommandManager commandManager, IBlogPostImageEditingContext editingContext)
// : base(spellingChecker, commandManager)
public HtmlSourceEditorControl(CommandManager commandManager, IBlogPostImageEditingContext editingContext)
: base(commandManager)
{
this.editingContext = editingContext;
}
internal string GetRawText()
{
return EditorControl.Text;
}
public void LoadHtmlFragment(string postBodyHtml)
{
// save current selection state so we can restore it
int editorPosition = SourceEditor.SelectionStart;
using (TextReader htmlReader = new StringReader(CleanupHtml(postBodyHtml, SourceEditor.Width - 5)))
{
String htmlText = htmlReader.ReadToEnd();
//shorten all absolute file URLs into variable names so that they don't clutter the source code.
//the replace operation can be used later to undo the conversions.
_replaceOperation.Mode = ReplaceAbsoluteFilePathsOperation.REPLACE_MODE.ABS2VAR;
htmlText = _replaceOperation.Execute(htmlText);
SourceEditor.Text = htmlText;
}
SourceEditor.SelectionStart = editorPosition;
OnCommandStateChanged();
}
public void Focus()
{
EditorControl.Focus();
}
public override string GetEditedHtml(bool preferWellFormed)
{
//get the raw HTML out of the source control's text box
String htmlText = base.GetEditedHtml(preferWellFormed);
//undo any URL variable-name conversions that were previously applied by the replace operation.
_replaceOperation.Mode = ReplaceAbsoluteFilePathsOperation.REPLACE_MODE.VAR2ABS;
htmlText = _replaceOperation.Execute(htmlText);
return htmlText;
}
/// <summary>
/// If the specified markers exist in the editor text,
/// delete the first instance of each and position the
/// selection at the markers.
/// </summary>
public bool SelectAndDelete(string startMarker, string endMarker)
{
string html = SourceEditor.Text;
int startIndex, startLen;
FindMarker(html, startMarker, out startIndex, out startLen);
int endIndex, endLen;
FindMarker(html, endMarker, out endIndex, out endLen);
if (startIndex > endIndex)
{
Trace.Fail("Selection startIndex is before endIndex--this should never happen");
int temp = startIndex;
startIndex = endIndex;
endIndex = temp;
temp = startLen;
startLen = endLen;
endLen = temp;
}
if (endIndex >= 0)
{
html = html.Substring(0, endIndex) + html.Substring(endIndex + endLen);
}
if (startIndex >= 0)
{
html = html.Substring(0, startIndex) + html.Substring(startIndex + startLen);
if (endIndex >= 0)
endIndex -= startLen;
}
SourceEditor.Text = html;
if (startIndex >= 0)
{
SourceEditor.Select(startIndex, endIndex - startIndex);
SourceEditor.ScrollToCaret();
return true;
}
return false;
}
private static void FindMarker(string html, string marker, out int index, out int length)
{
Match m = Regex.Match(html, Regex.Escape("<!--") + @"\s*" + Regex.Escape(marker) + @"\s*" + Regex.Escape("-->"));
if (m.Success)
{
index = m.Index;
length = m.Length;
}
else
{
index = -1;
length = 0;
}
}
public void ChangeSelection(SelectionPosition position)
{
SourceEditor.Select(
position == SelectionPosition.BodyStart ? 0
: position == SelectionPosition.BodyEnd ? SourceEditor.TextLength
: 0,
0);
}
protected override bool ShowAllLinkOptions
{
get
{
return GlobalEditorOptions.SupportsFeature(ContentEditorFeature.ShowAllLinkOptions);
}
}
}
/// <summary>
/// Converts URLs to/from absolute file and shortened variable name formats.
/// </summary>
public class ReplaceAbsoluteFilePathsOperation : ReplaceOperation
{
public enum REPLACE_MODE { ABS2VAR, VAR2ABS };
private readonly Hashtable var2abs;
private readonly Hashtable abs2var;
public REPLACE_MODE Mode;
public ReplaceAbsoluteFilePathsOperation()
{
var2abs = new Hashtable();
abs2var = new Hashtable();
}
protected override string Replace(Element el)
{
if (el is BeginTag)
{
BeginTag beginTag = (BeginTag)el;
if (beginTag.NameEquals("a"))
{
Attr href = beginTag.GetAttribute("href");
if (href != null && href.Value != null)
{
href.Value = ConvertUrl(href.Value);
return beginTag.ToString();
}
}
else if (beginTag.NameEquals("img"))
{
Attr src = beginTag.GetAttribute("src");
if (src != null && src.Value != null)
{
src.Value = ConvertUrl(src.Value);
return beginTag.ToString();
}
}
}
return base.Replace(el);
}
/// <summary>
/// Converts a URL's representation between absolute and variable formats based on the Mode.
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private string ConvertUrl(String url)
{
if (Mode == REPLACE_MODE.ABS2VAR)
{
if (UrlHelper.IsFileUrl(url))
{
//then this URL is an absolute file URL, so convert it to a shortened variable name.
string varName = abs2var[url] as string;
if (varName == null)
{
varName = createUniqueVarNameForFileUrl(url);
}
return varName;
}
}
else if (Mode == REPLACE_MODE.VAR2ABS)
{
if (url.StartsWith("$"))
{
//this URL is a variable that was previously converted from ab ABS url, so convert it back
string newUrl = var2abs[url] as string;
if (newUrl != null)
return newUrl;
}
}
return url;
}
/// <summary>
/// Generates a unique variable name that can be used to convert this URL in a shortened format.
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private string createUniqueVarNameForFileUrl(string url)
{
string localPath = new Uri(url).LocalPath;
string fileName = Path.GetFileNameWithoutExtension(localPath);
string ext = Path.GetExtension(localPath);
string varName = String.Format(CultureInfo.InvariantCulture, "${0}{1}", fileName, ext);
for (int i = 0; var2abs.ContainsKey(varName); i++)
{
varName = String.Format(CultureInfo.InvariantCulture, "${0}-{1}{2}", fileName, i, ext);
}
var2abs[varName] = url;
abs2var[url] = varName;
return varName;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Localisation;
using osu.Framework.Testing;
using osuTK;
using osuTK.Graphics;
namespace osu.Framework.Tests.Visual.Sprites
{
[System.ComponentModel.Description("various visual SpriteText displays")]
public class TestSceneSpriteTextScenarios : GridTestScene
{
public TestSceneSpriteTextScenarios()
: base(4, 5)
{
Cell(0, 0).Child = new SpriteText { Text = "Basic: Hello world!" };
Cell(1, 0).Child = new SpriteText
{
Text = "Font size = 15",
Font = new FontUsage(size: 15),
};
Cell(2, 0).Child = new SpriteText
{
Text = "Colour = green",
Colour = Color4.Green
};
Cell(3, 0).Child = new SpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Text = "Rotation = 45",
Rotation = 45
};
Cell(0, 1).Child = new SpriteText
{
Text = "Scale = 2",
Scale = new Vector2(2)
};
Cell(1, 1).Child = new CircularContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Masking = true,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box { RelativeSizeAxes = Axes.Both },
new SpriteText
{
Colour = Color4.Red,
Text = "||MASKED||"
}
}
};
Cell(2, 1).Child = new SpriteText
{
Text = "Explicit width",
Width = 50
};
Cell(3, 1).Child = new SpriteText
{
Text = "AllowMultiline = false",
Width = 50,
AllowMultiline = false
};
Cell(0, 2).Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Width = 50,
AutoSizeAxes = Axes.Y,
Child = new SpriteText
{
Text = "Relative size",
RelativeSizeAxes = Axes.X
}
};
Cell(1, 2).Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Width = 50,
AutoSizeAxes = Axes.Y,
Child = new SpriteText
{
Text = "GlyphHeight = false",
RelativeSizeAxes = Axes.X,
UseFullGlyphHeight = false
}
};
Cell(2, 2).Child = new SpriteText
{
Text = "Fixed width",
Font = new FontUsage(fixedWidth: true),
};
Cell(3, 2).Child = new SpriteText
{
Text = "Scale = -1",
Y = 20,
Scale = new Vector2(-1)
};
Cell(0, 3).Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box { RelativeSizeAxes = Axes.Both },
new SpriteText
{
Text = "Shadow = true",
Shadow = true
}
}
};
Cell(1, 3).Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.SlateGray
},
new SpriteText
{
Text = "Padded (autosize)",
Padding = new MarginPadding(10)
},
}
};
Cell(2, 3).Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.SlateGray
},
new SpriteText
{
Text = "Padded (fixed size)",
Width = 50,
Padding = new MarginPadding(10)
},
}
};
Cell(3, 3).Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
AutoSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box { RelativeSizeAxes = Axes.Both },
new SpriteText
{
Text = "Red text + pink shadow",
Shadow = true,
Colour = Color4.Red,
ShadowColour = Color4.Pink.Opacity(0.5f)
}
}
};
Cell(0, 4).Child = new NoFixedWidthSpaceText { Text = "No fixed width spaces" };
Cell(1, 4).Child = new LocalisableTestContainer
{
RelativeSizeAxes = Axes.Both,
Child = new FillFlowContainer
{
RelativeSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 10),
Children = new[]
{
new SpriteText { Text = FakeStorage.LOCALISABLE_STRING_EN },
new SpriteText { Text = new TranslatableString(FakeStorage.LOCALISABLE_STRING_EN, FakeStorage.LOCALISABLE_STRING_EN) },
}
}
};
Bindable<string> boundString = new Bindable<string>("bindable: 0");
int boundStringValue = 0;
Cell(2, 4).Child = new LocalisableTestContainer
{
RelativeSizeAxes = Axes.Both,
Child = new SpriteText { Current = boundString },
};
Scheduler.AddDelayed(() => boundString.Value = $"bindable: {++boundStringValue}", 200, true);
}
private class NoFixedWidthSpaceText : SpriteText
{
public NoFixedWidthSpaceText()
{
Font = new FontUsage(fixedWidth: true);
}
protected override char[] FixedWidthExcludeCharacters { get; } = { ' ' };
}
private class LocalisableTestContainer : Container
{
[Cached]
private readonly LocalisationManager localisation;
public LocalisableTestContainer()
{
var config = new FakeFrameworkConfigManager();
localisation = new LocalisationManager(config);
localisation.AddLanguage("en", new FakeStorage("en"));
localisation.AddLanguage("ja", new FakeStorage("ja"));
config.SetValue(FrameworkSetting.Locale, "ja");
}
}
private class FakeFrameworkConfigManager : FrameworkConfigManager
{
protected override string Filename => null;
public FakeFrameworkConfigManager()
: base(null)
{
}
protected override void InitialiseDefaults()
{
SetDefault(FrameworkSetting.Locale, "ja");
SetDefault(FrameworkSetting.ShowUnicode, false);
}
}
private class FakeStorage : ILocalisationStore
{
public const string LOCALISABLE_STRING_EN = "localised EN";
public const string LOCALISABLE_STRING_JA = "localised JA";
public CultureInfo EffectiveCulture { get; }
private readonly string locale;
public FakeStorage(string locale)
{
this.locale = locale;
EffectiveCulture = new CultureInfo(locale);
}
public async Task<string> GetAsync(string name, CancellationToken cancellationToken = default) =>
await Task.Run(() => Get(name), cancellationToken).ConfigureAwait(false);
public string Get(string name)
{
switch (name)
{
case LOCALISABLE_STRING_EN:
switch (locale)
{
default:
return LOCALISABLE_STRING_EN;
case "ja":
return LOCALISABLE_STRING_JA;
}
default:
return name;
}
}
public Stream GetStream(string name) => throw new NotSupportedException();
public void Dispose()
{
}
public IEnumerable<string> GetAvailableResources() => Enumerable.Empty<string>();
}
}
}
| |
// 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 System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using Avalonia.Diagnostics;
using Avalonia.Platform;
namespace Avalonia.Collections
{
/// <summary>
/// Describes the action notified on a clear of a <see cref="AvaloniaList{T}"/>.
/// </summary>
public enum ResetBehavior
{
/// <summary>
/// Clearing the list notifies a with a
/// <see cref="NotifyCollectionChangedAction.Reset"/>.
/// </summary>
Reset,
/// <summary>
/// Clearing the list notifies a with a
/// <see cref="NotifyCollectionChangedAction.Remove"/>.
/// </summary>
Remove,
}
/// <summary>
/// A notifying list.
/// </summary>
/// <typeparam name="T">The type of the list items.</typeparam>
/// <remarks>
/// <para>
/// AvaloniaList is similar to <see cref="System.Collections.ObjectModel.ObservableCollection{T}"/>
/// with a few added features:
/// </para>
///
/// <list type="bullet">
/// <item>
/// It can be configured to notify the <see cref="CollectionChanged"/> event with a
/// <see cref="NotifyCollectionChangedAction.Remove"/> action instead of a
/// <see cref="NotifyCollectionChangedAction.Reset"/> when the list is cleared by
/// setting <see cref="ResetBehavior"/> to <see cref="ResetBehavior.Remove"/>.
/// removed
/// </item>
/// <item>
/// A <see cref="Validate"/> function can be used to validate each item before insertion.
/// removed
/// </item>
/// </list>
/// </remarks>
public class AvaloniaList<T> : IAvaloniaList<T>, IList, INotifyCollectionChangedDebug
{
private List<T> _inner;
private NotifyCollectionChangedEventHandler _collectionChanged;
/// <summary>
/// Initializes a new instance of the <see cref="AvaloniaList{T}"/> class.
/// </summary>
public AvaloniaList()
: this(Enumerable.Empty<T>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AvaloniaList{T}"/> class.
/// </summary>
/// <param name="items">The initial items for the collection.</param>
public AvaloniaList(IEnumerable<T> items)
{
_inner = new List<T>(items);
}
/// <summary>
/// Initializes a new instance of the <see cref="AvaloniaList{T}"/> class.
/// </summary>
/// <param name="items">The initial items for the collection.</param>
public AvaloniaList(params T[] items)
{
_inner = new List<T>(items);
}
/// <summary>
/// Raised when a change is made to the collection's items.
/// </summary>
public event NotifyCollectionChangedEventHandler CollectionChanged
{
add { _collectionChanged += value; }
remove { _collectionChanged -= value; }
}
/// <summary>
/// Raised when a property on the collection changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets the number of items in the collection.
/// </summary>
public int Count => _inner.Count;
/// <summary>
/// Gets or sets the reset behavior of the list.
/// </summary>
public ResetBehavior ResetBehavior { get; set; }
/// <summary>
/// Gets or sets a validation routine that can be used to validate items before they are
/// added.
/// </summary>
public Action<T> Validate { get; set; }
/// <inheritdoc/>
bool IList.IsFixedSize => false;
/// <inheritdoc/>
bool IList.IsReadOnly => false;
/// <inheritdoc/>
int ICollection.Count => _inner.Count;
/// <inheritdoc/>
bool ICollection.IsSynchronized => false;
/// <inheritdoc/>
object ICollection.SyncRoot => null;
/// <inheritdoc/>
bool ICollection<T>.IsReadOnly => false;
/// <summary>
/// Gets or sets the item at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns>The item.</returns>
public T this[int index]
{
get
{
return _inner[index];
}
set
{
Validate?.Invoke(value);
T old = _inner[index];
if (!object.Equals(old, value))
{
_inner[index] = value;
if (_collectionChanged != null)
{
var e = new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Replace,
value,
old,
index);
_collectionChanged(this, e);
}
}
}
}
/// <summary>
/// Gets or sets the item at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns>The item.</returns>
object IList.this[int index]
{
get { return this[index]; }
set { this[index] = (T)value; }
}
/// <summary>
/// Adds an item to the collection.
/// </summary>
/// <param name="item">The item.</param>
public virtual void Add(T item)
{
Validate?.Invoke(item);
int index = _inner.Count;
_inner.Add(item);
NotifyAdd(new[] { item }, index);
}
/// <summary>
/// Adds multiple items to the collection.
/// </summary>
/// <param name="items">The items.</param>
public virtual void AddRange(IEnumerable<T> items)
{
Contract.Requires<ArgumentNullException>(items != null);
var list = (items as IList) ?? items.ToList();
if (list.Count > 0)
{
if (Validate != null)
{
foreach (var item in list)
{
Validate((T)item);
}
}
int index = _inner.Count;
_inner.AddRange(items);
NotifyAdd(list, index);
}
}
/// <summary>
/// Removes all items from the collection.
/// </summary>
public virtual void Clear()
{
if (this.Count > 0)
{
var old = _inner;
_inner = new List<T>();
NotifyReset(old);
}
}
/// <summary>
/// Tests if the collection contains the specified item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>True if the collection contains the item; otherwise false.</returns>
public bool Contains(T item)
{
return _inner.Contains(item);
}
/// <summary>
/// Copies the collection's contents to an array.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="arrayIndex">The first index of the array to copy to.</param>
public void CopyTo(T[] array, int arrayIndex)
{
_inner.CopyTo(array, arrayIndex);
}
/// <summary>
/// Returns an enumerator that enumerates the items in the collection.
/// </summary>
/// <returns>An <see cref="IEnumerator{T}"/>.</returns>
public IEnumerator<T> GetEnumerator()
{
return _inner.GetEnumerator();
}
/// <summary>
/// Gets a range of items from the collection.
/// </summary>
/// <param name="index">The first index to remove.</param>
/// <param name="count">The number of items to remove.</param>
public IEnumerable<T> GetRange(int index, int count)
{
return _inner.GetRange(index, count);
}
/// <summary>
/// Gets the index of the specified item in the collection.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>
/// The index of the item or -1 if the item is not contained in the collection.
/// </returns>
public int IndexOf(T item)
{
return _inner.IndexOf(item);
}
/// <summary>
/// Inserts an item at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="item">The item.</param>
public virtual void Insert(int index, T item)
{
Validate?.Invoke(item);
_inner.Insert(index, item);
NotifyAdd(new[] { item }, index);
}
/// <summary>
/// Inserts multiple items at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="items">The items.</param>
public virtual void InsertRange(int index, IEnumerable<T> items)
{
Contract.Requires<ArgumentNullException>(items != null);
var list = (items as IList) ?? items.ToList();
if (list.Count > 0)
{
if (Validate != null)
{
foreach (var item in list)
{
Validate((T)item);
}
}
_inner.InsertRange(index, items);
NotifyAdd((items as IList) ?? items.ToList(), index);
}
}
/// <summary>
/// Moves an item to a new index.
/// </summary>
/// <param name="oldIndex">The index of the item to move.</param>
/// <param name="newIndex">The index to move the item to.</param>
public void Move(int oldIndex, int newIndex)
{
var item = this[oldIndex];
_inner.RemoveAt(oldIndex);
_inner.Insert(newIndex, item);
if (_collectionChanged != null)
{
var e = new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Move,
item,
newIndex,
oldIndex);
_collectionChanged(this, e);
}
}
/// <summary>
/// Moves multiple items to a new index.
/// </summary>
/// <param name="oldIndex">The first index of the items to move.</param>
/// <param name="count">The number of items to move.</param>
/// <param name="newIndex">The index to move the items to.</param>
public void MoveRange(int oldIndex, int count, int newIndex)
{
var items = _inner.GetRange(oldIndex, count);
_inner.RemoveRange(oldIndex, count);
if (newIndex > oldIndex)
{
newIndex -= count;
}
_inner.InsertRange(newIndex, items);
if (_collectionChanged != null)
{
var e = new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Move,
items,
newIndex,
oldIndex);
_collectionChanged(this, e);
}
}
/// <summary>
/// Removes an item from the collection.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>True if the item was found and removed, otherwise false.</returns>
public virtual bool Remove(T item)
{
int index = _inner.IndexOf(item);
if (index != -1)
{
_inner.RemoveAt(index);
NotifyRemove(new[] { item }, index);
return true;
}
return false;
}
/// <summary>
/// Removes multiple items from the collection.
/// </summary>
/// <param name="items">The items.</param>
public virtual void RemoveAll(IEnumerable<T> items)
{
Contract.Requires<ArgumentNullException>(items != null);
foreach (var i in items)
{
// TODO: Optimize to only send as many notifications as necessary.
Remove(i);
}
}
/// <summary>
/// Removes the item at the specified index.
/// </summary>
/// <param name="index">The index.</param>
public virtual void RemoveAt(int index)
{
T item = _inner[index];
_inner.RemoveAt(index);
NotifyRemove(new[] { item }, index);
}
/// <summary>
/// Removes a range of elements from the collection.
/// </summary>
/// <param name="index">The first index to remove.</param>
/// <param name="count">The number of items to remove.</param>
public virtual void RemoveRange(int index, int count)
{
if (count > 0)
{
var list = _inner.GetRange(index, count);
_inner.RemoveRange(index, count);
NotifyRemove(list, index);
}
}
/// <inheritdoc/>
int IList.Add(object value)
{
int index = Count;
Add((T)value);
return index;
}
/// <inheritdoc/>
bool IList.Contains(object value)
{
return Contains((T)value);
}
/// <inheritdoc/>
void IList.Clear()
{
Clear();
}
/// <inheritdoc/>
int IList.IndexOf(object value)
{
return IndexOf((T)value);
}
/// <inheritdoc/>
void IList.Insert(int index, object value)
{
Insert(index, (T)value);
}
/// <inheritdoc/>
void IList.Remove(object value)
{
Remove((T)value);
}
/// <inheritdoc/>
void IList.RemoveAt(int index)
{
RemoveAt(index);
}
/// <inheritdoc/>
void ICollection.CopyTo(Array array, int index)
{
_inner.CopyTo((T[])array, index);
}
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator()
{
return _inner.GetEnumerator();
}
/// <inheritdoc/>
Delegate[] INotifyCollectionChangedDebug.GetCollectionChangedSubscribers() => _collectionChanged?.GetInvocationList();
/// <summary>
/// Raises the <see cref="CollectionChanged"/> event with an add action.
/// </summary>
/// <param name="t">The items that were added.</param>
/// <param name="index">The starting index.</param>
private void NotifyAdd(IList t, int index)
{
if (_collectionChanged != null)
{
var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, t, index);
_collectionChanged(this, e);
}
NotifyCountChanged();
}
/// <summary>
/// Raises the <see cref="PropertyChanged"/> event when the <see cref="Count"/> property
/// changes.
/// </summary>
private void NotifyCountChanged()
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Count"));
}
/// <summary>
/// Raises the <see cref="CollectionChanged"/> event with a remove action.
/// </summary>
/// <param name="t">The items that were removed.</param>
/// <param name="index">The starting index.</param>
private void NotifyRemove(IList t, int index)
{
if (_collectionChanged != null)
{
var e = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, t, index);
_collectionChanged(this, e);
}
NotifyCountChanged();
}
/// <summary>
/// Raises the <see cref="CollectionChanged"/> event with a reset action.
/// </summary>
/// <param name="t">The items that were removed.</param>
private void NotifyReset(IList t)
{
if (_collectionChanged != null)
{
NotifyCollectionChangedEventArgs e;
e = ResetBehavior == ResetBehavior.Reset ?
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset) :
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, t, 0);
_collectionChanged(this, e);
}
NotifyCountChanged();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Infrastructure.Common;
using Xunit;
public class StreamingTests : ConditionalWcfTest
{
[ConditionalFact(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed))]
[OuterLoop]
#if !FEATURE_NETNATIVE
[ActiveIssue(851, PlatformID.AnyUnix)] // NegotiateStream works on Windows but limitations related to credentials means automated tests can't work on Unix at this point.
#else
[ActiveIssue(832)] // Windows Stream Security is not supported in NET Native
#endif
public static void NetTcp_TransportSecurity_StreamedRequest_RoundTrips_String()
{
string testString = "Hello";
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = binding = new NetTcpBinding(SecurityMode.Transport);
binding.TransferMode = TransferMode.StreamedRequest;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var result = serviceProxy.GetStringFromStream(stream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[ConditionalFact(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed))]
[OuterLoop]
#if !FEATURE_NETNATIVE
[ActiveIssue(851, PlatformID.AnyUnix)] // NegotiateStream works on Windows but limitations related to credentials means automated tests can't work on Unix at this point.
#else
[ActiveIssue(832)] // Windows Stream Security is not supported in NET Native
#endif
public static void NetTcp_TransportSecurity_StreamedResponse_RoundTrips_String()
{
string testString = "Hello";
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
binding = new NetTcpBinding(SecurityMode.Transport);
binding.TransferMode = TransferMode.StreamedResponse;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address));
serviceProxy = factory.CreateChannel();
// *** EXECUTE *** \\
var returnStream = serviceProxy.GetStreamFromString(testString);
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[ConditionalFact(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed))]
[OuterLoop]
#if !FEATURE_NETNATIVE
[ActiveIssue(851, PlatformID.AnyUnix)] // NegotiateStream works on Windows but limitations related to credentials means automated tests can't work on Unix at this point.
#else
[ActiveIssue(832)] // Windows Stream Security is not supported in NET Native
#endif
public static void NetTcp_TransportSecurity_Streamed_RoundTrips_String()
{
string testString = "Hello";
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new NetTcpBinding(SecurityMode.Transport);
binding.TransferMode = TransferMode.Streamed;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var returnStream = serviceProxy.EchoStream(stream);
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[ConditionalFact(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed))]
[OuterLoop]
#if !FEATURE_NETNATIVE
[ActiveIssue(851, PlatformID.AnyUnix)] // NegotiateStream works on Windows but limitations related to credentials means automated tests can't work on Unix at this point.
#else
[ActiveIssue(832)] // Windows Stream Security is not supported in NET Native
#endif
public static void NetTcp_TransportSecurity_Streamed_TimeOut_Long_Running_Operation()
{
string testString = "Hello";
NetTcpBinding binding = null;
TimeSpan serviceOperationTimeout = TimeSpan.FromMilliseconds(10000);
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
try
{
// *** SETUP *** \\
binding = new NetTcpBinding(SecurityMode.Transport);
binding.TransferMode = TransferMode.Streamed;
binding.SendTimeout = TimeSpan.FromMilliseconds(5000);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address));
serviceProxy = factory.CreateChannel();
Stopwatch watch = new Stopwatch();
watch.Start();
// *** EXECUTE *** \\
try
{
Assert.Throws<TimeoutException>(() =>
{
string returnString = serviceProxy.EchoWithTimeout(testString, serviceOperationTimeout);
});
}
finally
{
watch.Stop();
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
// *** VALIDATE *** \\
// want to assert that this completed in > 5 s as an upper bound since the SendTimeout is 5 sec
// (usual case is around 5001-5005 ms)
Assert.True(watch.ElapsedMilliseconds >= 4985 && watch.ElapsedMilliseconds < 6000,
String.Format("Expected timeout was {0}ms but actual was {1}ms",
serviceOperationTimeout.TotalMilliseconds,
watch.ElapsedMilliseconds));
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[ConditionalFact(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed))]
[OuterLoop]
#if !FEATURE_NETNATIVE
[ActiveIssue(851, PlatformID.AnyUnix)] // NegotiateStream works on Windows but limitations related to credentials means automated tests can't work on Unix at this point.
#else
[ActiveIssue(832)] // Windows Stream Security is not supported in NET Native
#endif
public static void NetTcp_TransportSecurity_Streamed_Async_RoundTrips_String()
{
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new NetTcpBinding(SecurityMode.Transport);
binding.TransferMode = TransferMode.Streamed;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var returnStream = serviceProxy.EchoStreamAsync(stream).Result;
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[ConditionalFact(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed))]
[OuterLoop]
#if !FEATURE_NETNATIVE
[ActiveIssue(851, PlatformID.AnyUnix)] // NegotiateStream works on Windows but limitations related to credentials means automated tests can't work on Unix at this point.
#else
[ActiveIssue(832)] // Windows Stream Security is not supported in NET Native
#endif
public static void NetTcp_TransportSecurity_StreamedRequest_Async_RoundTrips_String()
{
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new NetTcpBinding(SecurityMode.Transport);
binding.TransferMode = TransferMode.StreamedRequest;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var returnStream = serviceProxy.EchoStreamAsync(stream).Result;
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[ConditionalFact(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed))]
[OuterLoop]
#if !FEATURE_NETNATIVE
[ActiveIssue(851, PlatformID.AnyUnix)] // NegotiateStream works on Windows but limitations related to credentials means automated tests can't work on Unix at this point.
#else
[ActiveIssue(832)] // Windows Stream Security is not supported in NET Native
#endif
public static void NetTcp_TransportSecurity_StreamedResponse_Async_RoundTrips_String()
{
string testString = "Hello";
StringBuilder errorBuilder = new StringBuilder();
NetTcpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
Stream stream = null;
try
{
// *** SETUP *** \\
binding = new NetTcpBinding(SecurityMode.Transport);
binding.TransferMode = TransferMode.StreamedResponse;
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address));
serviceProxy = factory.CreateChannel();
stream = StringToStream(testString);
// *** EXECUTE *** \\
var returnStream = serviceProxy.EchoStreamAsync(stream).Result;
var result = StreamToString(returnStream);
// *** VALIDATE *** \\
Assert.Equal(testString, result);
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
[ConditionalFact(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed))]
[OuterLoop]
#if !FEATURE_NETNATIVE
[ActiveIssue(851, PlatformID.AnyUnix)] // NegotiateStream works on Windows but limitations related to credentials means automated tests can't work on Unix at this point.
#else
[ActiveIssue(832)] // Windows Stream Security is not supported in NET Native
#endif
public static void NetTcp_TransportSecurity_Streamed_RoundTrips_String_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => StreamingTests.NetTcp_TransportSecurity_Streamed_RoundTrips_String(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: NetTcp_TransportSecurity_String_Streamed_RoundTrips_WithSingleThreadedSyncContext timed-out.");
}
[ConditionalFact(nameof(Root_Certificate_Installed), nameof(Client_Certificate_Installed))]
[OuterLoop]
#if !FEATURE_NETNATIVE
[ActiveIssue(851, PlatformID.AnyUnix)] // NegotiateStream works on Windows but limitations related to credentials means automated tests can't work on Unix at this point.
#else
[ActiveIssue(832)] // Windows Stream Security is not supported in NET Native
#endif
public static void NetTcp_TransportSecurity_Streamed_Async_RoundTrips_String_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => StreamingTests.NetTcp_TransportSecurity_Streamed_Async_RoundTrips_String(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: NetTcp_TransportSecurity_Streamed_Async_RoundTrips_String_WithSingleThreadedSyncContext timed-out.");
}
private static void PrintInnerExceptionsHresult(Exception e, StringBuilder errorBuilder)
{
if (e.InnerException != null)
{
errorBuilder.AppendLine(string.Format("\r\n InnerException type: '{0}', Hresult:'{1}'", e.InnerException, e.InnerException.HResult));
PrintInnerExceptionsHresult(e.InnerException, errorBuilder);
}
}
private static string StreamToString(Stream stream)
{
var reader = new StreamReader(stream, Encoding.UTF8);
return reader.ReadToEnd();
}
private static Stream StringToStream(string str)
{
var ms = new MemoryStream();
var sw = new StreamWriter(ms, Encoding.UTF8);
sw.Write(str);
sw.Flush();
ms.Position = 0;
return ms;
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Source groups.
//-----------------------------------------------------------------------------
singleton SFXDescription( AudioMaster );
singleton SFXSource( AudioChannelMaster )
{
description = AudioMaster;
};
singleton SFXDescription( AudioChannel )
{
sourceGroup = AudioChannelMaster;
};
singleton SFXSource( AudioChannelDefault )
{
description = AudioChannel;
};
singleton SFXSource( AudioChannelGui )
{
description = AudioChannel;
};
singleton SFXSource( AudioChannelEffects )
{
description = AudioChannel;
};
singleton SFXSource( AudioChannelMessages )
{
description = AudioChannel;
};
singleton SFXSource( AudioChannelMusic )
{
description = AudioChannel;
};
// Set default playback states of the channels.
AudioChannelMaster.play();
AudioChannelDefault.play();
AudioChannelGui.play();
AudioChannelMusic.play();
AudioChannelMessages.play();
// Stop in-game effects channels.
AudioChannelEffects.stop();
//-----------------------------------------------------------------------------
// Master SFXDescriptions.
//-----------------------------------------------------------------------------
// Master description for interface audio.
singleton SFXDescription( AudioGui )
{
volume = 1.0;
sourceGroup = AudioChannelGui;
};
// Master description for game effects audio.
singleton SFXDescription( AudioEffect )
{
volume = 1.0;
sourceGroup = AudioChannelEffects;
};
// Master description for audio in notifications.
singleton SFXDescription( AudioMessage )
{
volume = 1.0;
sourceGroup = AudioChannelMessages;
};
// Master description for music.
singleton SFXDescription( AudioMusic )
{
volume = 1.0;
sourceGroup = AudioChannelMusic;
};
//-----------------------------------------------------------------------------
// SFX Functions.
//-----------------------------------------------------------------------------
/// This initializes the sound system device from
/// the defaults in the $pref::SFX:: globals.
function sfxStartup()
{
// The console builds should re-detect, by default, so that it plays nicely
// along side a PC build in the same script directory.
if( $platform $= "xenon" )
{
if( $pref::SFX::provider $= "DirectSound" ||
$pref::SFX::provider $= "OpenAL" )
{
$pref::SFX::provider = "";
}
if( $pref::SFX::provider $= "" )
{
$pref::SFX::autoDetect = 1;
warn( "Xbox360 is auto-detecting available sound providers..." );
warn( " - You may wish to alter this functionality before release (core/scripts/client/audio.cs)" );
}
}
echo( "sfxStartup..." );
// If we have a provider set, try initialize a device now.
if( $pref::SFX::provider !$= "" )
{
if( sfxInit() )
return;
else
{
// Force auto-detection.
$pref::SFX::autoDetect = true;
}
}
// If enabled autodetect a safe device.
if( ( !isDefined( "$pref::SFX::autoDetect" ) || $pref::SFX::autoDetect ) &&
sfxAutodetect() )
return;
// Failure.
error( " Failed to initialize device!\n\n" );
$pref::SFX::provider = "";
$pref::SFX::device = "";
return;
}
/// This initializes the sound system device from
/// the defaults in the $pref::SFX:: globals.
function sfxInit()
{
// If already initialized, shut down the current device first.
if( sfxGetDeviceInfo() !$= "" )
sfxShutdown();
// Start it up!
%maxBuffers = $pref::SFX::useHardware ? -1 : $pref::SFX::maxSoftwareBuffers;
if ( !sfxCreateDevice( $pref::SFX::provider, $pref::SFX::device, $pref::SFX::useHardware, %maxBuffers ) )
return false;
// This returns a tab seperated string with
// the initialized system info.
%info = sfxGetDeviceInfo();
$pref::SFX::provider = getField( %info, 0 );
$pref::SFX::device = getField( %info, 1 );
$pref::SFX::useHardware = getField( %info, 2 );
%useHardware = $pref::SFX::useHardware ? "Yes" : "No";
%maxBuffers = getField( %info, 3 );
echo( " Provider: " @ $pref::SFX::provider );
echo( " Device: " @ $pref::SFX::device );
echo( " Hardware: " @ %useHardware );
echo( " Buffers: " @ %maxBuffers );
if( isDefined( "$pref::SFX::distanceModel" ) )
sfxSetDistanceModel( $pref::SFX::distanceModel );
if( isDefined( "$pref::SFX::dopplerFactor" ) )
sfxSetDopplerFactor( $pref::SFX::dopplerFactor );
if( isDefined( "$pref::SFX::rolloffFactor" ) )
sfxSetRolloffFactor( $pref::SFX::rolloffFactor );
// Restore master volume.
sfxSetMasterVolume( $pref::SFX::masterVolume );
// Restore channel volumes.
for( %channel = 0; %channel <= 8; %channel ++ )
sfxSetChannelVolume( %channel, $pref::SFX::channelVolume[ %channel ] );
return true;
}
/// Destroys the current sound system device.
function sfxShutdown()
{
// Store volume prefs.
$pref::SFX::masterVolume = sfxGetMasterVolume();
for( %channel = 0; %channel <= 8; %channel ++ )
$pref::SFX::channelVolume[ %channel ] = sfxGetChannelVolume( %channel );
// We're assuming here that a null info
// string means that no device is loaded.
if( sfxGetDeviceInfo() $= "" )
return;
sfxDeleteDevice();
}
/// Determines which of the two SFX providers is preferable.
function sfxCompareProvider( %providerA, %providerB )
{
if( %providerA $= %providerB )
return 0;
switch$( %providerA )
{
// Always prefer FMOD over anything else.
case "FMOD":
return 1;
// Prefer OpenAL over anything but FMOD.
case "OpenAL":
if( %providerB $= "FMOD" )
return -1;
else
return 1;
// choose XAudio over DirectSound
case "XAudio":
if( %providerB $= "FMOD" || %providerB $= "OpenAL" )
return -1;
else
return 0;
case "DirectSound":
if( %providerB !$= "FMOD" && %providerB !$= "OpenAL" && %providerB !$= "XAudio" )
return 1;
else
return -1;
default:
return -1;
}
}
/// Try to detect and initalize the best SFX device available.
function sfxAutodetect()
{
// Get all the available devices.
%devices = sfxGetAvailableDevices();
// Collect and sort the devices by preferentiality.
%deviceTrySequence = new ArrayObject();
%bestMatch = -1;
%count = getRecordCount( %devices );
for( %i = 0; %i < %count; %i ++ )
{
%info = getRecord( %devices, %i );
%provider = getField( %info, 0 );
%deviceTrySequence.push_back( %provider, %info );
}
%deviceTrySequence.sortfkd( "sfxCompareProvider" );
// Try the devices in order.
%count = %deviceTrySequence.count();
for( %i = 0; %i < %count; %i ++ )
{
%provider = %deviceTrySequence.getKey( %i );
%info = %deviceTrySequence.getValue( %i );
$pref::SFX::provider = %provider;
$pref::SFX::device = getField( %info, 1 );
$pref::SFX::useHardware = getField( %info, 2 );
// By default we've decided to avoid hardware devices as
// they are buggy and prone to problems.
$pref::SFX::useHardware = false;
if( sfxInit() )
{
$pref::SFX::autoDetect = false;
%deviceTrySequence.delete();
return true;
}
}
// Found no suitable device.
error( "sfxAutodetect - Could not initialize a valid SFX device." );
$pref::SFX::provider = "";
$pref::SFX::device = "";
$pref::SFX::useHardware = "";
%deviceTrySequence.delete();
return false;
}
//-----------------------------------------------------------------------------
// Backwards-compatibility with old channel system.
//-----------------------------------------------------------------------------
// Volume channel IDs for backwards-compatibility.
$GuiAudioType = 1; // Interface.
$SimAudioType = 2; // Game.
$MessageAudioType = 3; // Notifications.
$MusicAudioType = 4; // Music.
$AudioChannels[ 0 ] = AudioChannelDefault;
$AudioChannels[ $GuiAudioType ] = AudioChannelGui;
$AudioChannels[ $SimAudioType ] = AudioChannelEffects;
$AudioChannels[ $MessageAudioType ] = AudioChannelMessages;
$AudioChannels[ $MusicAudioType ] = AudioChannelMusic;
function sfxOldChannelToGroup( %channel )
{
return $AudioChannels[ %channel ];
}
function sfxGroupToOldChannel( %group )
{
%id = %group.getId();
for( %i = 0;; %i ++ )
if( !isObject( $AudioChannels[ %i ] ) )
return -1;
else if( $AudioChannels[ %i ].getId() == %id )
return %i;
return -1;
}
function sfxSetMasterVolume( %volume )
{
AudioChannelMaster.setVolume( %volume );
}
function sfxGetMasterVolume( %volume )
{
return AudioChannelMaster.getVolume();
}
function sfxStopAll( %channel )
{
// Don't stop channel itself since that isn't quite what the function
// here intends.
%channel = sfxOldChannelToGroup( %channel );
if (isObject(%channel))
{
foreach( %source in %channel )
%source.stop();
}
}
function sfxGetChannelVolume( %channel )
{
%obj = sfxOldChannelToGroup( %channel );
if( isObject( %obj ) )
return %obj.getVolume();
}
function sfxSetChannelVolume( %channel, %volume )
{
%obj = sfxOldChannelToGroup( %channel );
if( isObject( %obj ) )
%obj.setVolume( %volume );
}
singleton SimSet( SFXPausedSet );
/// Pauses the playback of active sound sources.
///
/// @param %channels An optional word list of channel indices or an empty
/// string to pause sources on all channels.
/// @param %pauseSet An optional SimSet which is filled with the paused
/// sources. If not specified the global SfxSourceGroup
/// is used.
///
/// @deprecated
///
function sfxPause( %channels, %pauseSet )
{
// Did we get a set to populate?
if ( !isObject( %pauseSet ) )
%pauseSet = SFXPausedSet;
%count = SFXSourceSet.getCount();
for ( %i = 0; %i < %count; %i++ )
{
%source = SFXSourceSet.getObject( %i );
%channel = sfxGroupToOldChannel( %source.getGroup() );
if( %channels $= "" || findWord( %channels, %channel ) != -1 )
{
%source.pause();
%pauseSet.add( %source );
}
}
}
/// Resumes the playback of paused sound sources.
///
/// @param %pauseSet An optional SimSet which contains the paused sound
/// sources to be resumed. If not specified the global
/// SfxSourceGroup is used.
/// @deprecated
///
function sfxResume( %pauseSet )
{
if ( !isObject( %pauseSet ) )
%pauseSet = SFXPausedSet;
%count = %pauseSet.getCount();
for ( %i = 0; %i < %count; %i++ )
{
%source = %pauseSet.getObject( %i );
%source.play();
}
// Clear our pause set... the caller is left
// to clear his own if he passed one.
%pauseSet.clear();
}
| |
// Python Tools for Visual Studio
// 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.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security;
using Microsoft.PythonTools.Interpreter;
using Microsoft.Win32;
namespace CanopyInterpreter {
/// <summary>
/// Provides interpreter factory objects for Canopy.
///
/// The factory provider is responsible for detecting installations of
/// Canopy and managing IPythonInterpreterFactory objects for each item to
/// display to the user.
///
/// For Canopy, we create two IPythonInterpreterFactory objects, but only
/// return one to the user. The CanopyInterpreterFactory object represents
/// the User directory, and contains a default factory representing App.
/// </summary>
[InterpreterFactoryId("Canopy")]
[Export(typeof(IPythonInterpreterFactoryProvider))]
[PartCreationPolicy(CreationPolicy.Shared)]
class CanopyInterpreterFactoryProvider : IPythonInterpreterFactoryProvider {
private readonly List<IPythonInterpreterFactory> _interpreters;
const string CanopyCorePath = @"Software\Enthought\Canopy";
const string InstallPath = "InstalledPath";
const string CanopyVersionKey = "Version";
public CanopyInterpreterFactoryProvider() {
_interpreters = new List<IPythonInterpreterFactory>();
DiscoverInterpreterFactories();
try {
// Watch for changes in the Canopy core registry key
RegistryWatcher.Instance.Add(
RegistryHive.CurrentUser,
RegistryView.Default,
CanopyCorePath,
Registry_Changed,
recursive: true,
notifyValueChange: true,
notifyKeyChange: true
);
} catch (ArgumentException) {
// Watch HKCU\Software for the Canopy key to be created
RegistryWatcher.Instance.Add(
RegistryHive.CurrentUser,
RegistryView.Default,
"Software",
Registry_Software_Changed,
recursive: false,
notifyValueChange: false,
notifyKeyChange: true
);
}
}
private void Registry_Changed(object sender, RegistryChangedEventArgs e) {
DiscoverInterpreterFactories();
}
private void Registry_Software_Changed(object sender, RegistryChangedEventArgs e) {
using (var root = RegistryKey.OpenBaseKey(e.Hive, e.View))
using (var key = root.OpenSubKey(CanopyCorePath)) {
if (key != null) {
Registry_Changed(sender, e);
e.CancelWatcher = true;
RegistryWatcher.Instance.Add(e.Hive, e.View, CanopyCorePath, Registry_Changed,
recursive: true, notifyValueChange: true, notifyKeyChange: true);
}
}
}
/// <summary>
/// Reads the details of Canopy from the registry and adds any new
/// interpreters to <see cref="_interpreters"/>.
/// </summary>
/// <param name="canopyKey">The base Canopy registry key.</param>
/// <returns>
/// True if an interpreter was added; otherwise, false.
/// </returns>
private bool ReadInterpreterFactory(RegistryKey canopyKey) {
var installPath = canopyKey.GetValue(InstallPath) as string;
if (!Directory.Exists(installPath)) {
// Canopy is not installed
return false;
}
// TODO: Read the User path from the registry.
var userPath = Path.Combine(installPath, @"Canopy\User");
if (!Directory.Exists(userPath)) {
// TODO: Bootstrap Canopy's virtual environment
// Bear in mind that this function is called close to VS startup
// and the user may not be interested in creating the
// environment now.
// This function is also called when the Canopy registry key
// changes, so setting the User path key after bootstrapping
// will cause the interpreter to be discovered.
return false;
}
string basePath, versionStr;
ReadPyVEnvCfg(userPath, out basePath, out versionStr);
if (!Directory.Exists(basePath)) {
// User path has an invalid home path set.
return false;
}
Version version;
if (Version.TryParse(versionStr, out version)) {
version = new Version(version.Major, version.Minor);
} else {
version = new Version(2, 7);
}
var canopyVersion = canopyKey.GetValue(CanopyVersionKey) as string;
try {
var baseFactory = CanopyInterpreterFactory.CreateBase(basePath, canopyVersion, version);
var factory = CanopyInterpreterFactory.Create(baseFactory, userPath, canopyVersion);
if (!_interpreters.Any(f => f.Configuration.Id == factory.Configuration.Id)) {
_interpreters.Add(factory);
return true;
}
} catch (Exception) {
// TODO: Report failure to create factory
}
return false;
}
/// <summary>
/// Reads a pyvenv.cfg file at <paramref name="prefixPath"/> and returns
/// the values specified for 'home' and 'version'.
/// </summary>
/// <param name="prefixPath">
/// A path containing a pyvenv.cfg file.
/// </param>
/// <param name="home">
/// On return, contains the value for 'home' or null.
/// </param>
/// <param name="version">
/// On return, contains the value for 'version' or null.
/// </param>
private static void ReadPyVEnvCfg(string prefixPath, out string home, out string version) {
home = null;
version = null;
try {
foreach (var line in File.ReadLines(Path.Combine(prefixPath, "pyvenv.cfg"))) {
int equal = line.IndexOf('=');
if (equal < 0) {
continue;
}
var name = line.Substring(0, equal).Trim();
var value = line.Substring(equal + 1).Trim();
if (name == "home") {
home = value;
} else if (name == "version") {
version = value;
}
}
} catch (IOException) {
} catch (UnauthorizedAccessException) {
} catch (SecurityException) {
}
}
/// <summary>
/// Called on initialize and on registry change events to discover new
/// interpreters.
/// </summary>
/// <remarks>
/// This function does not remove interpreters from PTVS when they are
/// uninstalled. PTVS should be closed before uninstalling interpreters
/// to ensure that files are no longer in use.
/// </remarks>
private void DiscoverInterpreterFactories() {
bool anyAdded = false;
var arch = Environment.Is64BitOperatingSystem ? null : (ProcessorArchitecture?)ProcessorArchitecture.X86;
using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default))
using (var canopyKey = baseKey.OpenSubKey(CanopyCorePath)) {
if (canopyKey != null) {
anyAdded = ReadInterpreterFactory(canopyKey);
}
}
if (anyAdded) {
OnInterpreterFactoriesChanged();
}
}
#region IPythonInterpreterProvider Members
public IEnumerable<IPythonInterpreterFactory> GetInterpreterFactories() {
return _interpreters;
}
public IEnumerable<InterpreterConfiguration> GetInterpreterConfigurations() {
return GetInterpreterFactories().Select(x => x.Configuration);
}
public IPythonInterpreterFactory GetInterpreterFactory(string id) {
return GetInterpreterFactories()
.Where(x => x.Configuration.Id == id)
.FirstOrDefault();
}
public object GetProperty(string id, string propName) => null;
public event EventHandler InterpreterFactoriesChanged;
private void OnInterpreterFactoriesChanged() {
var evt = InterpreterFactoriesChanged;
if (evt != null) {
evt(this, EventArgs.Empty);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Property4U.Areas.HelpPage.ModelDescriptions;
using Property4U.Areas.HelpPage.Models;
namespace Property4U.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//
// DefaultColumnController.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2007-2008 Novell, 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 Mono.Unix;
using Hyena.Query;
using Hyena.Gui;
using Hyena.Gui.Theming;
using Hyena.Gui.Theatrics;
using Hyena.Data.Gui;
using Banshee.Gui;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
using Banshee.Collection;
using Banshee.Query;
using Banshee.Sources;
namespace Banshee.Collection.Gui
{
public class DefaultColumnController : PersistentColumnController
{
public DefaultColumnController () : this (true)
{
}
public DefaultColumnController (bool loadDefault) : base (String.Format ("{0}.{1}",
Application.ActiveClient.ClientId, "track_view_columns"))
{
CreateDefaultColumns ();
if (loadDefault) {
AddDefaultColumns ();
DefaultSortColumn = TrackColumn;
Load ();
}
}
public void AddDefaultColumns ()
{
AddRange (
IndicatorColumn,
TrackColumn,
TitleColumn,
ArtistColumn,
AlbumColumn,
CommentColumn,
RatingColumn,
ScoreColumn,
DurationColumn,
GenreColumn,
YearColumn,
FileSizeColumn,
ComposerColumn,
PlayCountColumn,
SkipCountColumn,
LastPlayedColumn,
LastSkippedColumn,
DateAddedColumn,
UriColumn,
MimeTypeColumn,
LicenseUriColumn,
AlbumArtistColumn,
TrackNumberAndCountColumn,
DiscNumberAndCountColumn,
BpmColumn,
BitRateColumn,
SampleRateColumn,
BitsPerSampleColumn,
ConductorColumn,
GroupingColumn
);
}
private void CreateDefaultColumns ()
{
indicator_column = new Column (null, "indicator", new ColumnCellStatusIndicator (null), 0.05, true, 30, 30);
indicator_column.Title = String.Empty;
// Visible-by-default column
track_column = Create (BansheeQuery.TrackNumberField, 0.10, true, new ColumnCellTrackNumber (null, true));
track_column.Title = String.Empty; // don't show any text in the header for this column, so it can be smaller
title_column = CreateText (BansheeQuery.TitleField, 0.25, true);
artist_column = CreateText (BansheeQuery.ArtistField, 0.225, true);
album_column = CreateText (BansheeQuery.AlbumField, 0.225, true);
// Others
album_artist_column = CreateText (BansheeQuery.AlbumArtistField, 0.225);
genre_column = CreateText (BansheeQuery.GenreField, 0.25);
duration_column = Create (BansheeQuery.DurationField, 0.10, true, new ColumnCellDuration (null, true));
year_column = Create (BansheeQuery.YearField, 0.15, false, new ColumnCellPositiveInt (null, true, 4, 4) { CultureFormatted = false });
file_size_column = Create (BansheeQuery.FileSizeField, 0.15, false, new ColumnCellFileSize (null, true));
bpm_column = Create (BansheeQuery.BpmField, 0.10, false, new ColumnCellPositiveInt (null, true, 3, 3));
// Set the property to null on these so that the object passed in is the actual bound TrackInfo
track_combined_column = Create (BansheeQuery.TrackNumberField, 0.10, false, new ColumnCellTrackAndCount (null, true));
track_combined_column.Property = null;
track_combined_column.Id = "track_and_count";
track_combined_column.Title = Catalog.GetString ("Track #");
track_combined_column.LongTitle = Catalog.GetString ("Track & Count");
disc_combined_column = Create (BansheeQuery.DiscNumberField, 0.10, false, new ColumnCellDiscAndCount (null, true));
disc_combined_column.Property = null;
disc_combined_column.Title = Catalog.GetString ("Disc #");
disc_combined_column.LongTitle = Catalog.GetString ("Disc & Count");
ColumnCellPositiveInt br_cell = new ColumnCellPositiveInt (null, true, 3, 4);
br_cell.TextFormat = Catalog.GetString ("{0} kbps");
bitrate_column = Create (BansheeQuery.BitRateField, 0.10, false, br_cell);
ColumnCellPositiveInt sr_cell = new ColumnCellPositiveInt (null, true, 5, 6);
sr_cell.TextFormat = Catalog.GetString ("{0} Hz");
samplerate_column = Create (BansheeQuery.SampleRateField, 0.10, false, sr_cell);
ColumnCellPositiveInt bps_cell = new ColumnCellPositiveInt (null, true, 2, 2);
bps_cell.TextFormat = Catalog.GetString ("{0} bits");
bitspersample_column= Create (BansheeQuery.BitsPerSampleField, 0.10, false, bps_cell);
column_cell_rating = new ColumnCellRating (null, true);
rating_column = Create (BansheeQuery.RatingField, 0.15, false, column_cell_rating);
score_column = Create (BansheeQuery.ScoreField, 0.15, false, new ColumnCellPositiveInt (null, true, 2, 5));
composer_column = CreateText (BansheeQuery.ComposerField, 0.25);
conductor_column = CreateText (BansheeQuery.ConductorField, 0.25);
grouping_column = CreateText (BansheeQuery.GroupingField, 0.25);
comment_column = CreateText (BansheeQuery.CommentField, 0.25);
play_count_column = Create (BansheeQuery.PlayCountField, 0.15, false, new ColumnCellPositiveInt (null, true, 2, 5));
skip_count_column = Create (BansheeQuery.SkipCountField, 0.15, false, new ColumnCellPositiveInt (null, true, 2, 5));
// Construct the URI column specially b/c we want to ellipsize in the middle of the text
ColumnCellText uri_cell = new ColumnCellLocation (BansheeQuery.UriField.PropertyName, true);
uri_cell.EllipsizeMode = Pango.EllipsizeMode.Start;
uri_column = Create (BansheeQuery.UriField, 0.15, false, uri_cell);
mime_type_column = CreateText (BansheeQuery.MimeTypeField, 0.15);
license_uri_column = Create (BansheeQuery.LicenseUriField, 0.15, false, new ColumnCellCreativeCommons (null, true));
last_played_column = Create (BansheeQuery.LastPlayedField, 0.15, false, new ColumnCellDateTime (null, true));
last_skipped_column = Create (BansheeQuery.LastSkippedField, 0.15, false, new ColumnCellDateTime (null, true));
date_added_column = Create (BansheeQuery.DateAddedField, 0.15, false, new ColumnCellDateTime (null, true));
ServiceStack.ServiceManager.SourceManager.ActiveSourceChanged += HandleActiveSourceChanged;
}
void HandleActiveSourceChanged (SourceEventArgs args)
{
column_cell_rating.ReadOnly = !args.Source.HasEditableTrackProperties;
}
private SortableColumn CreateText (QueryField field, double width)
{
return CreateText (field, width, false);
}
private SortableColumn CreateText (QueryField field, double width, bool visible)
{
return Create (field, width, visible, new ColumnCellText (field.PropertyName, true));
}
public static SortableColumn Create (QueryField field, double width, bool visible, ColumnCell cell)
{
cell.Property = field.PropertyName;
SortableColumn col = new SortableColumn (
field.ShortLabel,
cell,
width, field.Name, visible
);
col.LongTitle = field.Label;
col.Field = field;
return col;
}
private ColumnCellRating column_cell_rating;
#region Column Properties
private Column indicator_column;
public Column IndicatorColumn {
get { return indicator_column; }
}
private SortableColumn track_column;
public SortableColumn TrackColumn {
get { return track_column; }
}
private SortableColumn title_column;
public SortableColumn TitleColumn {
get { return title_column; }
}
private SortableColumn artist_column;
public SortableColumn ArtistColumn {
get { return artist_column; }
}
private SortableColumn album_column;
public SortableColumn AlbumColumn {
get { return album_column; }
}
private SortableColumn duration_column;
public SortableColumn DurationColumn {
get { return duration_column; }
}
private SortableColumn genre_column;
public SortableColumn GenreColumn {
get { return genre_column; }
}
private SortableColumn year_column;
public SortableColumn YearColumn {
get { return year_column; }
}
private SortableColumn file_size_column;
public SortableColumn FileSizeColumn {
get { return file_size_column; }
}
private SortableColumn composer_column;
public SortableColumn ComposerColumn {
get { return composer_column; }
}
private SortableColumn comment_column;
public SortableColumn CommentColumn {
get { return comment_column; }
}
private SortableColumn play_count_column;
public SortableColumn PlayCountColumn {
get { return play_count_column; }
}
private SortableColumn skip_count_column;
public SortableColumn SkipCountColumn {
get { return skip_count_column; }
}
private SortableColumn disc_combined_column;
public SortableColumn DiscNumberAndCountColumn {
get { return disc_combined_column; }
}
private SortableColumn rating_column;
public SortableColumn RatingColumn {
get { return rating_column; }
}
private SortableColumn score_column;
public SortableColumn ScoreColumn {
get { return score_column; }
}
private SortableColumn last_played_column;
public SortableColumn LastPlayedColumn {
get { return last_played_column; }
}
private SortableColumn last_skipped_column;
public SortableColumn LastSkippedColumn {
get { return last_skipped_column; }
}
private SortableColumn date_added_column;
public SortableColumn DateAddedColumn {
get { return date_added_column; }
}
private SortableColumn uri_column;
public SortableColumn UriColumn {
get { return uri_column; }
}
private SortableColumn album_artist_column;
public SortableColumn AlbumArtistColumn {
get { return album_artist_column; }
}
private SortableColumn track_combined_column;
public SortableColumn TrackNumberAndCountColumn {
get { return track_combined_column; }
}
private SortableColumn bpm_column;
public SortableColumn BpmColumn {
get { return bpm_column; }
}
private SortableColumn bitrate_column;
public SortableColumn BitRateColumn {
get { return bitrate_column; }
}
private SortableColumn samplerate_column;
public SortableColumn SampleRateColumn {
get { return samplerate_column; }
}
private SortableColumn bitspersample_column;
public SortableColumn BitsPerSampleColumn {
get { return bitspersample_column; }
}
private SortableColumn conductor_column;
public SortableColumn ConductorColumn {
get { return conductor_column; }
}
private SortableColumn grouping_column;
public SortableColumn GroupingColumn {
get { return grouping_column; }
}
private SortableColumn mime_type_column;
public SortableColumn MimeTypeColumn {
get { return mime_type_column; }
}
private SortableColumn license_uri_column;
public SortableColumn LicenseUriColumn {
get { return license_uri_column; }
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Nop.Core.Domain.Discounts;
using Nop.Core.Domain.Localization;
using Nop.Core.Domain.Security;
using Nop.Core.Domain.Seo;
using Nop.Core.Domain.Stores;
namespace Nop.Core.Domain.Catalog
{
/// <summary>
/// Represents a product
/// </summary>
public partial class Product : BaseEntity, ILocalizedEntity, ISlugSupported, IAclSupported, IStoreMappingSupported
{
private ICollection<ProductCategory> _productCategories;
private ICollection<ProductManufacturer> _productManufacturers;
private ICollection<ProductPicture> _productPictures;
private ICollection<ProductReview> _productReviews;
private ICollection<ProductSpecificationAttribute> _productSpecificationAttributes;
private ICollection<ProductTag> _productTags;
private ICollection<ProductAttributeMapping> _productAttributeMappings;
private ICollection<ProductAttributeCombination> _productAttributeCombinations;
private ICollection<TierPrice> _tierPrices;
private ICollection<Discount> _appliedDiscounts;
private ICollection<ProductWarehouseInventory> _productWarehouseInventory;
/// <summary>
/// Gets or sets the product type identifier
/// </summary>
public int ProductTypeId { get; set; }
/// <summary>
/// Gets or sets the parent product identifier. It's used to identify associated products (only with "grouped" products)
/// </summary>
public int ParentGroupedProductId { get; set; }
/// <summary>
/// Gets or sets the values indicating whether this product is visible in catalog or search results.
/// It's used when this product is associated to some "grouped" one
/// This way associated products could be accessed/added/etc only from a grouped product details page
/// </summary>
public bool VisibleIndividually { get; set; }
/// <summary>
/// Gets or sets the name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the short description
/// </summary>
public string ShortDescription { get; set; }
/// <summary>
/// Gets or sets the full description
/// </summary>
public string FullDescription { get; set; }
/// <summary>
/// Gets or sets the admin comment
/// </summary>
public string AdminComment { get; set; }
/// <summary>
/// Gets or sets a value of used product template identifier
/// </summary>
public int ProductTemplateId { get; set; }
/// <summary>
/// Gets or sets a vendor identifier
/// </summary>
public int VendorId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to show the product on home page
/// </summary>
public bool ShowOnHomePage { get; set; }
/// <summary>
/// Gets or sets the meta keywords
/// </summary>
public string MetaKeywords { get; set; }
/// <summary>
/// Gets or sets the meta description
/// </summary>
public string MetaDescription { get; set; }
/// <summary>
/// Gets or sets the meta title
/// </summary>
public string MetaTitle { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product allows customer reviews
/// </summary>
public bool AllowCustomerReviews { get; set; }
/// <summary>
/// Gets or sets the rating sum (approved reviews)
/// </summary>
public int ApprovedRatingSum { get; set; }
/// <summary>
/// Gets or sets the rating sum (not approved reviews)
/// </summary>
public int NotApprovedRatingSum { get; set; }
/// <summary>
/// Gets or sets the total rating votes (approved reviews)
/// </summary>
public int ApprovedTotalReviews { get; set; }
/// <summary>
/// Gets or sets the total rating votes (not approved reviews)
/// </summary>
public int NotApprovedTotalReviews { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity is subject to ACL
/// </summary>
public bool SubjectToAcl { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity is limited/restricted to certain stores
/// </summary>
public bool LimitedToStores { get; set; }
/// <summary>
/// Gets or sets the SKU
/// </summary>
public string Sku { get; set; }
/// <summary>
/// Gets or sets the manufacturer part number
/// </summary>
public string ManufacturerPartNumber { get; set; }
/// <summary>
/// Gets or sets the Global Trade Item Number (GTIN). These identifiers include UPC (in North America), EAN (in Europe), JAN (in Japan), and ISBN (for books).
/// </summary>
public string Gtin { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product is gift card
/// </summary>
public bool IsGiftCard { get; set; }
/// <summary>
/// Gets or sets the gift card type identifier
/// </summary>
public int GiftCardTypeId { get; set; }
/// <summary>
/// Gets or sets gift card amount that can be used after purchase. If not specified, then product price will be used.
/// </summary>
public decimal? OverriddenGiftCardAmount { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product requires that other products are added to the cart (Product X requires Product Y)
/// </summary>
public bool RequireOtherProducts { get; set; }
/// <summary>
/// Gets or sets a required product identifiers (comma separated)
/// </summary>
public string RequiredProductIds { get; set; }
/// <summary>
/// Gets or sets a value indicating whether required products are automatically added to the cart
/// </summary>
public bool AutomaticallyAddRequiredProducts { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product is download
/// </summary>
public bool IsDownload { get; set; }
/// <summary>
/// Gets or sets the download identifier
/// </summary>
public int DownloadId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this downloadable product can be downloaded unlimited number of times
/// </summary>
public bool UnlimitedDownloads { get; set; }
/// <summary>
/// Gets or sets the maximum number of downloads
/// </summary>
public int MaxNumberOfDownloads { get; set; }
/// <summary>
/// Gets or sets the number of days during customers keeps access to the file.
/// </summary>
public int? DownloadExpirationDays { get; set; }
/// <summary>
/// Gets or sets the download activation type
/// </summary>
public int DownloadActivationTypeId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product has a sample download file
/// </summary>
public bool HasSampleDownload { get; set; }
/// <summary>
/// Gets or sets the sample download identifier
/// </summary>
public int SampleDownloadId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product has user agreement
/// </summary>
public bool HasUserAgreement { get; set; }
/// <summary>
/// Gets or sets the text of license agreement
/// </summary>
public string UserAgreementText { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product is recurring
/// </summary>
public bool IsRecurring { get; set; }
/// <summary>
/// Gets or sets the cycle length
/// </summary>
public int RecurringCycleLength { get; set; }
/// <summary>
/// Gets or sets the cycle period
/// </summary>
public int RecurringCyclePeriodId { get; set; }
/// <summary>
/// Gets or sets the total cycles
/// </summary>
public int RecurringTotalCycles { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product is rental
/// </summary>
public bool IsRental { get; set; }
/// <summary>
/// Gets or sets the rental length for some period (price for this period)
/// </summary>
public int RentalPriceLength { get; set; }
/// <summary>
/// Gets or sets the rental period (price for this period)
/// </summary>
public int RentalPricePeriodId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity is ship enabled
/// </summary>
public bool IsShipEnabled { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity is free shipping
/// </summary>
public bool IsFreeShipping { get; set; }
/// <summary>
/// Gets or sets a value this product should be shipped separately (each item)
/// </summary>
public bool ShipSeparately { get; set; }
/// <summary>
/// Gets or sets the additional shipping charge
/// </summary>
public decimal AdditionalShippingCharge { get; set; }
/// <summary>
/// Gets or sets a delivery date identifier
/// </summary>
public int DeliveryDateId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product is marked as tax exempt
/// </summary>
public bool IsTaxExempt { get; set; }
/// <summary>
/// Gets or sets the tax category identifier
/// </summary>
public int TaxCategoryId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product is telecommunications or broadcasting or electronic services
/// </summary>
public bool IsTelecommunicationsOrBroadcastingOrElectronicServices { get; set; }
/// <summary>
/// Gets or sets a value indicating how to manage inventory
/// </summary>
public int ManageInventoryMethodId { get; set; }
/// <summary>
/// Gets or sets a product availability range identifier
/// </summary>
public int ProductAvailabilityRangeId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether multiple warehouses are used for this product
/// </summary>
public bool UseMultipleWarehouses { get; set; }
/// <summary>
/// Gets or sets a warehouse identifier
/// </summary>
public int WarehouseId { get; set; }
/// <summary>
/// Gets or sets the stock quantity
/// </summary>
public int StockQuantity { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to display stock availability
/// </summary>
public bool DisplayStockAvailability { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to display stock quantity
/// </summary>
public bool DisplayStockQuantity { get; set; }
/// <summary>
/// Gets or sets the minimum stock quantity
/// </summary>
public int MinStockQuantity { get; set; }
/// <summary>
/// Gets or sets the low stock activity identifier
/// </summary>
public int LowStockActivityId { get; set; }
/// <summary>
/// Gets or sets the quantity when admin should be notified
/// </summary>
public int NotifyAdminForQuantityBelow { get; set; }
/// <summary>
/// Gets or sets a value backorder mode identifier
/// </summary>
public int BackorderModeId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to back in stock subscriptions are allowed
/// </summary>
public bool AllowBackInStockSubscriptions { get; set; }
/// <summary>
/// Gets or sets the order minimum quantity
/// </summary>
public int OrderMinimumQuantity { get; set; }
/// <summary>
/// Gets or sets the order maximum quantity
/// </summary>
public int OrderMaximumQuantity { get; set; }
/// <summary>
/// Gets or sets the comma seperated list of allowed quantities. null or empty if any quantity is allowed
/// </summary>
public string AllowedQuantities { get; set; }
/// <summary>
/// Gets or sets a value indicating whether we allow adding to the cart/wishlist only attribute combinations that exist and have stock greater than zero.
/// This option is used only when we have "manage inventory" set to "track inventory by product attributes"
/// </summary>
public bool AllowAddingOnlyExistingAttributeCombinations { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this product is returnable (a customer is allowed to submit return request with this product)
/// </summary>
public bool NotReturnable { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to disable buy (Add to cart) button
/// </summary>
public bool DisableBuyButton { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to disable "Add to wishlist" button
/// </summary>
public bool DisableWishlistButton { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this item is available for Pre-Order
/// </summary>
public bool AvailableForPreOrder { get; set; }
/// <summary>
/// Gets or sets the start date and time of the product availability (for pre-order products)
/// </summary>
public DateTime? PreOrderAvailabilityStartDateTimeUtc { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to show "Call for Pricing" or "Call for quote" instead of price
/// </summary>
public bool CallForPrice { get; set; }
/// <summary>
/// Gets or sets the price
/// </summary>
public decimal Price { get; set; }
/// <summary>
/// Gets or sets the old price
/// </summary>
public decimal OldPrice { get; set; }
/// <summary>
/// Gets or sets the product cost
/// </summary>
public decimal ProductCost { get; set; }
/// <summary>
/// Gets or sets a value indicating whether a customer enters price
/// </summary>
public bool CustomerEntersPrice { get; set; }
/// <summary>
/// Gets or sets the minimum price entered by a customer
/// </summary>
public decimal MinimumCustomerEnteredPrice { get; set; }
/// <summary>
/// Gets or sets the maximum price entered by a customer
/// </summary>
public decimal MaximumCustomerEnteredPrice { get; set; }
/// <summary>
/// Gets or sets a value indicating whether base price (PAngV) is enabled. Used by German users.
/// </summary>
public bool BasepriceEnabled { get; set; }
/// <summary>
/// Gets or sets an amount in product for PAngV
/// </summary>
public decimal BasepriceAmount { get; set; }
/// <summary>
/// Gets or sets a unit of product for PAngV (MeasureWeight entity)
/// </summary>
public int BasepriceUnitId { get; set; }
/// <summary>
/// Gets or sets a reference amount for PAngV
/// </summary>
public decimal BasepriceBaseAmount { get; set; }
/// <summary>
/// Gets or sets a reference unit for PAngV (MeasureWeight entity)
/// </summary>
public int BasepriceBaseUnitId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this product is marked as new
/// </summary>
public bool MarkAsNew { get; set; }
/// <summary>
/// Gets or sets the start date and time of the new product (set product as "New" from date). Leave empty to ignore this property
/// </summary>
public DateTime? MarkAsNewStartDateTimeUtc { get; set; }
/// <summary>
/// Gets or sets the end date and time of the new product (set product as "New" to date). Leave empty to ignore this property
/// </summary>
public DateTime? MarkAsNewEndDateTimeUtc { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this product has tier prices configured
/// <remarks>The same as if we run this.TierPrices.Count > 0
/// We use this property for performance optimization:
/// if this property is set to false, then we do not need to load tier prices navigation property
/// </remarks>
/// </summary>
public bool HasTierPrices { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this product has discounts applied
/// <remarks>The same as if we run this.AppliedDiscounts.Count > 0
/// We use this property for performance optimization:
/// if this property is set to false, then we do not need to load Applied Discounts navigation property
/// </remarks>
/// </summary>
public bool HasDiscountsApplied { get; set; }
/// <summary>
/// Gets or sets the weight
/// </summary>
public decimal Weight { get; set; }
/// <summary>
/// Gets or sets the length
/// </summary>
public decimal Length { get; set; }
/// <summary>
/// Gets or sets the width
/// </summary>
public decimal Width { get; set; }
/// <summary>
/// Gets or sets the height
/// </summary>
public decimal Height { get; set; }
/// <summary>
/// Gets or sets the available start date and time
/// </summary>
public DateTime? AvailableStartDateTimeUtc { get; set; }
/// <summary>
/// Gets or sets the available end date and time
/// </summary>
public DateTime? AvailableEndDateTimeUtc { get; set; }
/// <summary>
/// Gets or sets a display order.
/// This value is used when sorting associated products (used with "grouped" products)
/// This value is used when sorting home page products
/// </summary>
public int DisplayOrder { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity is published
/// </summary>
public bool Published { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the entity has been deleted
/// </summary>
public bool Deleted { get; set; }
/// <summary>
/// Gets or sets the date and time of product creation
/// </summary>
public DateTime CreatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the date and time of product update
/// </summary>
public DateTime UpdatedOnUtc { get; set; }
/// <summary>
/// Gets or sets the product type
/// </summary>
public ProductType ProductType
{
get
{
return (ProductType)this.ProductTypeId;
}
set
{
this.ProductTypeId = (int)value;
}
}
/// <summary>
/// Gets or sets the backorder mode
/// </summary>
public BackorderMode BackorderMode
{
get
{
return (BackorderMode)this.BackorderModeId;
}
set
{
this.BackorderModeId = (int)value;
}
}
/// <summary>
/// Gets or sets the download activation type
/// </summary>
public DownloadActivationType DownloadActivationType
{
get
{
return (DownloadActivationType)this.DownloadActivationTypeId;
}
set
{
this.DownloadActivationTypeId = (int)value;
}
}
/// <summary>
/// Gets or sets the gift card type
/// </summary>
public GiftCardType GiftCardType
{
get
{
return (GiftCardType)this.GiftCardTypeId;
}
set
{
this.GiftCardTypeId = (int)value;
}
}
/// <summary>
/// Gets or sets the low stock activity
/// </summary>
public LowStockActivity LowStockActivity
{
get
{
return (LowStockActivity)this.LowStockActivityId;
}
set
{
this.LowStockActivityId = (int)value;
}
}
/// <summary>
/// Gets or sets the value indicating how to manage inventory
/// </summary>
public ManageInventoryMethod ManageInventoryMethod
{
get
{
return (ManageInventoryMethod)this.ManageInventoryMethodId;
}
set
{
this.ManageInventoryMethodId = (int)value;
}
}
/// <summary>
/// Gets or sets the cycle period for recurring products
/// </summary>
public RecurringProductCyclePeriod RecurringCyclePeriod
{
get
{
return (RecurringProductCyclePeriod)this.RecurringCyclePeriodId;
}
set
{
this.RecurringCyclePeriodId = (int)value;
}
}
/// <summary>
/// Gets or sets the period for rental products
/// </summary>
public RentalPricePeriod RentalPricePeriod
{
get
{
return (RentalPricePeriod)this.RentalPricePeriodId;
}
set
{
this.RentalPricePeriodId = (int)value;
}
}
/// <summary>
/// Gets or sets the collection of ProductCategory
/// </summary>
public virtual ICollection<ProductCategory> ProductCategories
{
get { return _productCategories ?? (_productCategories = new List<ProductCategory>()); }
protected set { _productCategories = value; }
}
/// <summary>
/// Gets or sets the collection of ProductManufacturer
/// </summary>
public virtual ICollection<ProductManufacturer> ProductManufacturers
{
get { return _productManufacturers ?? (_productManufacturers = new List<ProductManufacturer>()); }
protected set { _productManufacturers = value; }
}
/// <summary>
/// Gets or sets the collection of ProductPicture
/// </summary>
public virtual ICollection<ProductPicture> ProductPictures
{
get { return _productPictures ?? (_productPictures = new List<ProductPicture>()); }
protected set { _productPictures = value; }
}
/// <summary>
/// Gets or sets the collection of product reviews
/// </summary>
public virtual ICollection<ProductReview> ProductReviews
{
get { return _productReviews ?? (_productReviews = new List<ProductReview>()); }
protected set { _productReviews = value; }
}
/// <summary>
/// Gets or sets the product specification attribute
/// </summary>
public virtual ICollection<ProductSpecificationAttribute> ProductSpecificationAttributes
{
get { return _productSpecificationAttributes ?? (_productSpecificationAttributes = new List<ProductSpecificationAttribute>()); }
protected set { _productSpecificationAttributes = value; }
}
/// <summary>
/// Gets or sets the product tags
/// </summary>
public virtual ICollection<ProductTag> ProductTags
{
get { return _productTags ?? (_productTags = new List<ProductTag>()); }
protected set { _productTags = value; }
}
/// <summary>
/// Gets or sets the product attribute mappings
/// </summary>
public virtual ICollection<ProductAttributeMapping> ProductAttributeMappings
{
get { return _productAttributeMappings ?? (_productAttributeMappings = new List<ProductAttributeMapping>()); }
protected set { _productAttributeMappings = value; }
}
/// <summary>
/// Gets or sets the product attribute combinations
/// </summary>
public virtual ICollection<ProductAttributeCombination> ProductAttributeCombinations
{
get { return _productAttributeCombinations ?? (_productAttributeCombinations = new List<ProductAttributeCombination>()); }
protected set { _productAttributeCombinations = value; }
}
/// <summary>
/// Gets or sets the tier prices
/// </summary>
public virtual ICollection<TierPrice> TierPrices
{
get { return _tierPrices ?? (_tierPrices = new List<TierPrice>()); }
protected set { _tierPrices = value; }
}
/// <summary>
/// Gets or sets the collection of applied discounts
/// </summary>
public virtual ICollection<Discount> AppliedDiscounts
{
get { return _appliedDiscounts ?? (_appliedDiscounts = new List<Discount>()); }
protected set { _appliedDiscounts = value; }
}
/// <summary>
/// Gets or sets the collection of "ProductWarehouseInventory" records. We use it only when "UseMultipleWarehouses" is set to "true" and ManageInventoryMethod" to "ManageStock"
/// </summary>
public virtual ICollection<ProductWarehouseInventory> ProductWarehouseInventory
{
get { return _productWarehouseInventory ?? (_productWarehouseInventory = new List<ProductWarehouseInventory>()); }
protected set { _productWarehouseInventory = value; }
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using log4net;
namespace OpenSim.Region.Physics.Manager
{
/// <summary>
/// Description of MyClass.
/// </summary>
public class PhysicsPluginManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<string, IPhysicsPlugin> _PhysPlugins = new Dictionary<string, IPhysicsPlugin>();
private Dictionary<string, IMeshingPlugin> _MeshPlugins = new Dictionary<string, IMeshingPlugin>();
/// <summary>
/// Constructor.
/// </summary>
public PhysicsPluginManager()
{
// Load "plugins", that are hard coded and not existing in form of an external lib, and hence always
// available
IMeshingPlugin plugHard;
plugHard = new ZeroMesherPlugin();
_MeshPlugins.Add(plugHard.GetName(), plugHard);
m_log.Info("[PHYSICS]: Added meshing engine: " + plugHard.GetName());
}
/// <summary>
/// Get a physics scene for the given physics engine and mesher.
/// </summary>
/// <param name="physEngineName"></param>
/// <param name="meshEngineName"></param>
/// <param name="config"></param>
/// <returns></returns>
public PhysicsScene GetPhysicsScene(string physEngineName, string meshEngineName, IConfigSource config, string regionName,
OpenMetaverse.UUID regionId)
{
if (String.IsNullOrEmpty(physEngineName))
{
return PhysicsScene.Null;
}
if (String.IsNullOrEmpty(meshEngineName))
{
return PhysicsScene.Null;
}
IMesher meshEngine = null;
if (_MeshPlugins.ContainsKey(meshEngineName))
{
m_log.Info("[PHYSICS]: creating meshing engine " + meshEngineName);
meshEngine = _MeshPlugins[meshEngineName].GetMesher();
}
else
{
m_log.WarnFormat("[PHYSICS]: couldn't find meshingEngine: {0}", meshEngineName);
throw new ArgumentException(String.Format("couldn't find meshingEngine: {0}", meshEngineName));
}
if (_PhysPlugins.ContainsKey(physEngineName))
{
m_log.Info("[PHYSICS]: creating " + physEngineName);
PhysicsScene result = _PhysPlugins[physEngineName].GetScene(regionName);
result.Initialize(meshEngine, config, regionId);
return result;
}
else
{
m_log.WarnFormat("[PHYSICS]: couldn't find physicsEngine: {0}", physEngineName);
throw new ArgumentException(String.Format("couldn't find physicsEngine: {0}", physEngineName));
}
}
/// <summary>
/// Load all plugins in assemblies at the given path
/// </summary>
/// <param name="pluginsPath"></param>
public void LoadPluginsFromAssemblies(string assembliesPath)
{
// Walk all assemblies (DLLs effectively) and see if they are home
// of a plugin that is of interest for us
string[] pluginFiles = Directory.GetFiles(assembliesPath, "*.dll");
for (int i = 0; i < pluginFiles.Length; i++)
{
LoadPluginsFromAssembly(pluginFiles[i]);
}
}
/// <summary>
/// Load plugins from an assembly at the given path
/// </summary>
/// <param name="assemblyPath"></param>
public void LoadPluginsFromAssembly(string assemblyPath)
{
// TODO / NOTE
// The assembly named 'OpenSim.Region.Physics.BasicPhysicsPlugin' was loaded from
// 'file:///C:/OpenSim/trunk2/bin/Physics/OpenSim.Region.Physics.BasicPhysicsPlugin.dll'
// using the LoadFrom context. The use of this context can result in unexpected behavior
// for serialization, casting and dependency resolution. In almost all cases, it is recommended
// that the LoadFrom context be avoided. This can be done by installing assemblies in the
// Global Assembly Cache or in the ApplicationBase directory and using Assembly.
// Load when explicitly loading assemblies.
Assembly pluginAssembly = null;
Type[] types = null;
try
{
pluginAssembly = Assembly.LoadFrom(assemblyPath);
}
catch (Exception ex)
{
m_log.Error("[PHYSICS]: Failed to load plugin from " + assemblyPath, ex);
}
if (pluginAssembly != null)
{
try
{
types = pluginAssembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
m_log.Error("[PHYSICS]: Failed to enumerate types in plugin from " + assemblyPath + ": " +
ex.LoaderExceptions[0].Message, ex);
}
catch (Exception ex)
{
m_log.Error("[PHYSICS]: Failed to enumerate types in plugin from " + assemblyPath, ex);
}
if (types != null)
{
foreach (Type pluginType in types)
{
if (pluginType.IsPublic)
{
if (!pluginType.IsAbstract)
{
Type physTypeInterface = pluginType.GetInterface("IPhysicsPlugin", true);
if (physTypeInterface != null)
{
IPhysicsPlugin plug =
(IPhysicsPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
plug.Init();
if (!_PhysPlugins.ContainsKey(plug.GetName()))
{
_PhysPlugins.Add(plug.GetName(), plug);
m_log.Info("[PHYSICS]: Added physics engine: " + plug.GetName());
}
}
Type meshTypeInterface = pluginType.GetInterface("IMeshingPlugin", true);
if (meshTypeInterface != null)
{
IMeshingPlugin plug =
(IMeshingPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
if (!_MeshPlugins.ContainsKey(plug.GetName()))
{
_MeshPlugins.Add(plug.GetName(), plug);
m_log.Info("[PHYSICS]: Added meshing engine: " + plug.GetName());
}
}
physTypeInterface = null;
meshTypeInterface = null;
}
}
}
}
}
pluginAssembly = null;
}
//---
public static void PhysicsPluginMessage(string message, bool isWarning)
{
if (isWarning)
{
m_log.Warn("[PHYSICS]: " + message);
}
else
{
m_log.Info("[PHYSICS]: " + message);
}
}
//---
}
public interface IPhysicsPlugin
{
bool Init();
PhysicsScene GetScene(String sceneIdentifier);
string GetName();
void Dispose();
}
public interface IMeshingPlugin
{
string GetName();
IMesher GetMesher();
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
#if FRB_XNA || WINDOWS_PHONE || SILVERLIGHT || MONODROID
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
#elif FRB_MDX
using System.Drawing;
using Microsoft.DirectX;
#endif
namespace FlatRedBall.Gui
{
public class ColorDisplay : Window
{
#region Fields
TextDisplay mADisplay;
TextDisplay mRDisplay;
TextDisplay mGDisplay;
TextDisplay mBDisplay;
TimeLine mASlider;
TimeLine mRSlider;
TimeLine mGSlider;
TimeLine mBSlider;
TextBox mATextBox;
TextBox mRTextBox;
TextBox mGTextBox;
TextBox mBTextBox;
#endregion
#region Properties
public Color BeforeChangeColorValue
{
get
{
#if FRB_XNA || SILVERLIGHT
return new Color(
new Vector4(
(float)mRSlider.BeforeChangeValue,
(float)mGSlider.BeforeChangeValue,
(float)mBSlider.BeforeChangeValue,
(float)mASlider.BeforeChangeValue)
);
#elif FRB_MDX
return Color.FromArgb(
(int)mASlider.BeforeChangeValue,
(int)mRSlider.BeforeChangeValue,
(int)mGSlider.BeforeChangeValue,
(int)mBSlider.BeforeChangeValue
);
#endif
}
}
public Color ColorValue
{
get
{
#if FRB_XNA || SILVERLIGHT
return new Color(
new Vector4(
(float)mRSlider.CurrentValue,
(float)mGSlider.CurrentValue,
(float)mBSlider.CurrentValue,
(float)mASlider.CurrentValue)
);
#elif FRB_MDX
return Color.FromArgb(
(int)mASlider.CurrentValue,
(int)mRSlider.CurrentValue,
(int)mGSlider.CurrentValue,
(int)mBSlider.CurrentValue);
#endif
}
set
{
#if FRB_XNA
mASlider.CurrentValue = value.A / 255.0f;
mRSlider.CurrentValue = value.R / 255.0f;
mGSlider.CurrentValue = value.G / 255.0f;
mBSlider.CurrentValue = value.B / 255.0f;
#elif FRB_MDX
mASlider.CurrentValue = value.A;
mRSlider.CurrentValue = value.R;
mGSlider.CurrentValue = value.G;
mBSlider.CurrentValue = value.B;
#endif
SetTextValuesToSliders();
}
}
#endregion
#region Events
public event GuiMessage ValueChanged;
#endregion
#region Event and Delegate Methods
void OnTextBoxValueChange(Window callingWindow)
{
#if FRB_MDX
ColorValue = Color.FromArgb(
(int)mASlider.BeforeChangeValue,
(int)mRSlider.BeforeChangeValue,
(int)mGSlider.BeforeChangeValue,
(int)mBSlider.BeforeChangeValue
);
#else
ColorValue = new Color(
new Vector4(
float.Parse(mRTextBox.Text),
float.Parse(mGTextBox.Text),
float.Parse(mBTextBox.Text),
float.Parse(mATextBox.Text))
);
#endif
if (ValueChanged != null)
{
ValueChanged(this);
}
}
private void OnSliderValueChanged(Window callingWindow)
{
if (ValueChanged != null)
{
ValueChanged(this);
}
SetTextValuesToSliders();
}
#endregion
#region Methods
public ColorDisplay(Cursor cursor)
: base(cursor)
{
float border = .5f;
this.ScaleX = 7f;
this.ScaleY = 6f;
float spaceForDisplay = 1;
#region Create the sliders
mASlider = new TimeLine(cursor);
mRSlider = new TimeLine(cursor);
mGSlider = new TimeLine(cursor);
mBSlider = new TimeLine(cursor);
AddWindow(mASlider);
AddWindow(mRSlider);
AddWindow(mGSlider);
AddWindow(mBSlider);
mASlider.Y = border + 3.2f;
mRSlider.Y = border + 5.5f;
mGSlider.Y = border + 7.8f;
mBSlider.Y = border + 10.1f;
mASlider.GuiChange += OnSliderValueChanged;
mRSlider.GuiChange += OnSliderValueChanged;
mGSlider.GuiChange += OnSliderValueChanged;
mBSlider.GuiChange += OnSliderValueChanged;
// Since the ranges are identical don't show them for
// all sliders, just the top.
mASlider.ShowValues = true;
mRSlider.ShowValues = false;
mGSlider.ShowValues = false;
mBSlider.ShowValues = false;
mASlider.VerticalBarIncrement = .5f * FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
mRSlider.VerticalBarIncrement = .5f * FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
mGSlider.VerticalBarIncrement = .5f * FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
mBSlider.VerticalBarIncrement = .5f * FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
mASlider.SmallVerticalBarIncrement = mASlider.VerticalBarIncrement / 2.0f;
mRSlider.SmallVerticalBarIncrement = mRSlider.VerticalBarIncrement / 2.0f;
mGSlider.SmallVerticalBarIncrement = mGSlider.VerticalBarIncrement / 2.0f;
mBSlider.SmallVerticalBarIncrement = mBSlider.VerticalBarIncrement / 2.0f;
mASlider.ValueWidth = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
mRSlider.ValueWidth = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
mGSlider.ValueWidth = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
mBSlider.ValueWidth = FlatRedBall.Graphics.GraphicalEnumerations.MaxColorComponentValue;
mASlider.ScaleX = this.ScaleX - border - spaceForDisplay;
mRSlider.ScaleX = this.ScaleX - border - spaceForDisplay;
mGSlider.ScaleX = this.ScaleX - border - spaceForDisplay;
mBSlider.ScaleX = this.ScaleX - border - spaceForDisplay;
mASlider.X = border + spaceForDisplay * 2 + mASlider.ScaleX;
mRSlider.X = border + spaceForDisplay * 2 + mRSlider.ScaleX;
mGSlider.X = border + spaceForDisplay * 2 + mGSlider.ScaleX;
mBSlider.X = border + spaceForDisplay * 2 + mBSlider.ScaleX;
#endregion
#region Create the TextDisplays
mADisplay = new TextDisplay(mCursor);
AddWindow(mADisplay);
mRDisplay = new TextDisplay(mCursor);
AddWindow(mRDisplay);
mGDisplay = new TextDisplay(mCursor);
AddWindow(mGDisplay);
mBDisplay = new TextDisplay(mCursor);
AddWindow(mBDisplay);
mADisplay.X = .2f;
mRDisplay.X = .2f;
mGDisplay.X = .2f;
mBDisplay.X = .2f;
mADisplay.Text = "A";
mRDisplay.Text = "R";
mGDisplay.Text = "G";
mBDisplay.Text = "B";
mADisplay.Y = mASlider.Y;
mRDisplay.Y = mRSlider.Y;
mGDisplay.Y = mGSlider.Y;
mBDisplay.Y = mBSlider.Y;
#endregion
}
public void CreateTextBoxes()
{
this.SetScaleTL(10.5f, 6);
mATextBox = new TextBox(mCursor);
AddWindow(mATextBox);
mRTextBox = new TextBox(mCursor);
AddWindow(mRTextBox);
mGTextBox = new TextBox(mCursor);
AddWindow(mGTextBox);
mBTextBox = new TextBox(mCursor);
AddWindow(mBTextBox);
mATextBox.Format = TextBox.FormatTypes.Decimal;
mRTextBox.Format = TextBox.FormatTypes.Decimal;
mGTextBox.Format = TextBox.FormatTypes.Decimal;
mBTextBox.Format = TextBox.FormatTypes.Decimal;
mATextBox.LosingFocus += new GuiMessage(OnTextBoxValueChange);
mRTextBox.LosingFocus += new GuiMessage(OnTextBoxValueChange);
mGTextBox.LosingFocus += new GuiMessage(OnTextBoxValueChange);
mBTextBox.LosingFocus += new GuiMessage(OnTextBoxValueChange);
float textBoxX = 17f;
mATextBox.X = textBoxX;
mRTextBox.X = textBoxX;
mGTextBox.X = textBoxX;
mBTextBox.X = textBoxX;
float textBoxScaleX = 3;
mATextBox.ScaleX = textBoxScaleX;
mRTextBox.ScaleX = textBoxScaleX;
mGTextBox.ScaleX = textBoxScaleX;
mBTextBox.ScaleX = textBoxScaleX;
mATextBox.Y = mASlider.Y;
mRTextBox.Y = mRSlider.Y;
mGTextBox.Y = mGSlider.Y;
mBTextBox.Y = mBSlider.Y;
}
private void SetTextValuesToSliders()
{
if (mATextBox != null)
{
mATextBox.SetCompleteText(mASlider.CurrentValue.ToString(), false);
mRTextBox.SetCompleteText(mRSlider.CurrentValue.ToString(), false);
mGTextBox.SetCompleteText(mGSlider.CurrentValue.ToString(), false);
mBTextBox.SetCompleteText(mBSlider.CurrentValue.ToString(), false);
}
}
#endregion
}
}
| |
/* ====================================================================
Licensed To the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file To You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed To in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
namespace NPOI.HPSF
{
using System;
using System.IO;
using System.Text;
using System.Collections;
using NPOI.Util;
using NPOI.HPSF.Wellknown;
using System.Globalization;
/// <summary>
/// Adds writing capability To the {@link Section} class.
/// Please be aware that this class' functionality will be merged into the
/// {@link Section} class at a later time, so the API will Change.
/// @since 2002-02-20
/// </summary>
public class MutableSection : Section
{
/**
* If the "dirty" flag is true, the section's size must be
* (re-)calculated before the section is written.
*/
private bool dirty = true;
/**
* List To assemble the properties. Unfortunately a wrong
* decision has been taken when specifying the "properties" field
* as an Property[]. It should have been a {@link java.util.List}.
*/
private ArrayList preprops;
/**
* Contains the bytes making out the section. This byte array is
* established when the section's size is calculated and can be reused
* later. It is valid only if the "dirty" flag is false.
*/
private byte[] sectionBytes;
/// <summary>
/// Initializes a new instance of the <see cref="MutableSection"/> class.
/// </summary>
public MutableSection()
{
dirty = true;
formatID = null;
offset = -1;
preprops = new ArrayList();
}
/// <summary>
/// Constructs a <c>MutableSection</c> by doing a deep copy of an
/// existing <c>Section</c>. All nested <c>Property</c>
/// instances, will be their mutable counterparts in the new
/// <c>MutableSection</c>.
/// </summary>
/// <param name="s">The section Set To copy</param>
public MutableSection(Section s)
{
SetFormatID(s.FormatID);
Property[] pa = s.Properties;
MutableProperty[] mpa = new MutableProperty[pa.Length];
for (int i = 0; i < pa.Length; i++)
mpa[i] = new MutableProperty(pa[i]);
SetProperties(mpa);
this.Dictionary=(s.Dictionary);
}
/// <summary>
/// Sets the section's format ID.
/// </summary>
/// <param name="formatID">The section's format ID</param>
public void SetFormatID(ClassID formatID)
{
this.formatID = formatID;
}
/// <summary>
/// Sets the section's format ID.
/// </summary>
/// <param name="formatID">The section's format ID as a byte array. It components
/// are in big-endian format.</param>
public void SetFormatID(byte[] formatID)
{
ClassID fid = this.FormatID;
if (fid == null)
{
fid = new ClassID();
SetFormatID(fid);
}
fid.Bytes=formatID;
}
/// <summary>
/// Sets this section's properties. Any former values are overwritten.
/// </summary>
/// <param name="properties">This section's new properties.</param>
public void SetProperties(Property[] properties)
{
this.properties = properties;
preprops = new ArrayList();
for (int i = 0; i < properties.Length; i++)
preprops.Add(properties[i]);
dirty = true;
}
/// <summary>
/// Sets the string value of the property with the specified ID.
/// </summary>
/// <param name="id">The property's ID</param>
/// <param name="value">The property's value. It will be written as a Unicode
/// string.</param>
public void SetProperty(int id, String value)
{
SetProperty(id, Variant.VT_LPWSTR, value);
dirty = true;
}
/// <summary>
/// Sets the int value of the property with the specified ID.
/// </summary>
/// <param name="id">The property's ID</param>
/// <param name="value">The property's value.</param>
public void SetProperty(int id, int value)
{
SetProperty(id, Variant.VT_I4, value);
dirty = true;
}
/// <summary>
/// Sets the long value of the property with the specified ID.
/// </summary>
/// <param name="id">The property's ID</param>
/// <param name="value">The property's value.</param>
public void SetProperty(int id, long value)
{
SetProperty(id, Variant.VT_I8, value);
dirty = true;
}
/// <summary>
/// Sets the bool value of the property with the specified ID.
/// </summary>
/// <param name="id">The property's ID</param>
/// <param name="value">The property's value.</param>
public void SetProperty(int id, bool value)
{
SetProperty(id, Variant.VT_BOOL, value);
dirty = true;
}
/// <summary>
/// Sets the value and the variant type of the property with the
/// specified ID. If a property with this ID is not yet present in
/// the section, it will be Added. An alReady present property with
/// the specified ID will be overwritten. A default mapping will be
/// used To choose the property's type.
/// </summary>
/// <param name="id">The property's ID.</param>
/// <param name="variantType">The property's variant type.</param>
/// <param name="value">The property's value.</param>
public void SetProperty(int id, long variantType,
Object value)
{
MutableProperty p = new MutableProperty();
p.ID=id;
p.Type=variantType;
p.Value=value;
SetProperty(p);
dirty = true;
}
/// <summary>
/// Sets the property.
/// </summary>
/// <param name="p">The property To be Set.</param>
public void SetProperty(Property p)
{
long id = p.ID;
RemoveProperty(id);
preprops.Add(p);
dirty = true;
}
/// <summary>
/// Removes the property.
/// </summary>
/// <param name="id">The ID of the property To be Removed</param>
public void RemoveProperty(long id)
{
for (IEnumerator i = preprops.GetEnumerator(); i.MoveNext(); )
if (((Property)i.Current).ID == id)
{
preprops.Remove(i.Current);
break;
}
dirty = true;
}
/// <summary>
/// Sets the value of the bool property with the specified
/// ID.
/// </summary>
/// <param name="id">The property's ID</param>
/// <param name="value">The property's value</param>
protected void SetPropertyBooleanValue(int id, bool value)
{
SetProperty(id, Variant.VT_BOOL, value);
}
/// <summary>
/// Returns the section's size in bytes.
/// </summary>
/// <value>The section's size in bytes.</value>
public override int Size
{
get
{
if (dirty)
{
try
{
size = CalcSize();
dirty = false;
}
catch (Exception)
{
throw;
}
}
return size;
}
}
/// <summary>
/// Calculates the section's size. It is the sum of the Lengths of the
/// section's header (8), the properties list (16 times the number of
/// properties) and the properties themselves.
/// </summary>
/// <returns>the section's Length in bytes.</returns>
private int CalcSize()
{
using (MemoryStream out1 = new MemoryStream())
{
Write(out1);
/* Pad To multiple of 4 bytes so that even the Windows shell (explorer)
* shows custom properties. */
sectionBytes = Util.Pad4(out1.ToArray());
return sectionBytes.Length;
}
}
private class PropertyComparer : IComparer
{
#region IComparer Members
int IComparer.Compare(object o1, object o2)
{
Property p1 = (Property)o1;
Property p2 = (Property)o2;
if (p1.ID < p2.ID)
return -1;
else if (p1.ID == p2.ID)
return 0;
else
return 1;
}
#endregion
}
/// <summary>
/// Writes this section into an output stream.
/// Internally this is done by writing into three byte array output
/// streams: one for the properties, one for the property list and one for
/// the section as such. The two former are Appended To the latter when they
/// have received all their data.
/// </summary>
/// <param name="out1">The stream To Write into.</param>
/// <returns>The number of bytes written, i.e. the section's size.</returns>
public int Write(Stream out1)
{
/* Check whether we have alReady generated the bytes making out the
* section. */
if (!dirty && sectionBytes != null)
{
out1.Write(sectionBytes,0,sectionBytes.Length);
return sectionBytes.Length;
}
/* The properties are written To this stream. */
using (MemoryStream propertyStream =
new MemoryStream())
{
/* The property list is established here. After each property that has
* been written To "propertyStream", a property list entry is written To
* "propertyListStream". */
using (MemoryStream propertyListStream =
new MemoryStream())
{
/* Maintain the current position in the list. */
int position = 0;
/* Increase the position variable by the size of the property list so
* that it points behind the property list and To the beginning of the
* properties themselves. */
position += 2 * LittleEndianConsts.INT_SIZE +
PropertyCount * 2 * LittleEndianConsts.INT_SIZE;
/* Writing the section's dictionary it tricky. If there is a dictionary
* (property 0) the codepage property (property 1) must be Set, Too. */
int codepage = -1;
if (GetProperty(PropertyIDMap.PID_DICTIONARY) != null)
{
Object p1 = GetProperty(PropertyIDMap.PID_CODEPAGE);
if (p1 != null)
{
if (!(p1 is int))
throw new IllegalPropertySetDataException
("The codepage property (ID = 1) must be an " +
"Integer object.");
}
else
/* Warning: The codepage property is not Set although a
* dictionary is present. In order To cope with this problem we
* Add the codepage property and Set it To Unicode. */
SetProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
CodePageUtil.CP_UNICODE);
codepage = Codepage;
}
/* Sort the property list by their property IDs: */
preprops.Sort(new PropertyComparer());
/* Write the properties and the property list into their respective
* streams: */
for (int i = 0; i < preprops.Count; i++)
{
MutableProperty p = (MutableProperty)preprops[i];
long id = p.ID;
/* Write the property list entry. */
TypeWriter.WriteUIntToStream(propertyListStream, (uint)p.ID);
TypeWriter.WriteUIntToStream(propertyListStream, (uint)position);
/* If the property ID is not equal 0 we Write the property and all
* is fine. However, if it Equals 0 we have To Write the section's
* dictionary which has an implicit type only and an explicit
* value. */
if (id != 0)
{
/* Write the property and update the position To the next
* property. */
position += p.Write(propertyStream, Codepage);
}
else
{
if (codepage == -1)
throw new IllegalPropertySetDataException
("Codepage (property 1) is undefined.");
position += WriteDictionary(propertyStream, dictionary,
codepage);
}
}
propertyStream.Flush();
propertyListStream.Flush();
/* Write the section: */
byte[] pb1 = propertyListStream.ToArray();
byte[] pb2 = propertyStream.ToArray();
/* Write the section's Length: */
TypeWriter.WriteToStream(out1, LittleEndianConsts.INT_SIZE * 2 +
pb1.Length + pb2.Length);
/* Write the section's number of properties: */
TypeWriter.WriteToStream(out1, PropertyCount);
/* Write the property list: */
out1.Write(pb1, 0, pb1.Length);
/* Write the properties: */
out1.Write(pb2, 0, pb2.Length);
int streamLength = LittleEndianConsts.INT_SIZE * 2 + pb1.Length + pb2.Length;
return streamLength;
}
}
}
/// <summary>
/// Writes the section's dictionary
/// </summary>
/// <param name="out1">The output stream To Write To.</param>
/// <param name="dictionary">The dictionary.</param>
/// <param name="codepage">The codepage to be used to Write the dictionary items.</param>
/// <returns>The number of bytes written</returns>
/// <remarks>
/// see MSDN KB: http://msdn.microsoft.com/en-us/library/aa380065(VS.85).aspx
/// </remarks>
private static int WriteDictionary(Stream out1,
IDictionary dictionary, int codepage)
{
int length = TypeWriter.WriteUIntToStream(out1, (uint)dictionary.Count);
for (IEnumerator i = dictionary.Keys.GetEnumerator(); i.MoveNext(); )
{
long key = Convert.ToInt64(i.Current, CultureInfo.InvariantCulture);
String value = (String)dictionary[key];
//tony qu added: some key is int32 instead of int64
if(value==null)
value = (String)dictionary[(int)key];
if (codepage == CodePageUtil.CP_UNICODE)
{
/* Write the dictionary item in Unicode. */
int sLength = value.Length + 1;
if ((sLength & 1) == 1)
sLength++;
length += TypeWriter.WriteUIntToStream(out1, (uint)key);
length += TypeWriter.WriteUIntToStream(out1, (uint)sLength);
byte[] ca =
Encoding.GetEncoding(codepage).GetBytes(value);
for (int j =0; j < ca.Length; j++)
{
out1.WriteByte(ca[j]);
length ++;
}
sLength -= value.Length;
while (sLength > 0)
{
out1.WriteByte(0x00);
out1.WriteByte(0x00);
length += 2;
sLength--;
}
}
else
{
/* Write the dictionary item in another codepage than
* Unicode. */
length += TypeWriter.WriteUIntToStream(out1, (uint)key);
length += TypeWriter.WriteUIntToStream(out1, (uint)value.Length + 1);
try
{
byte[] ba =
Encoding.GetEncoding(codepage).GetBytes(value);
for (int j = 0; j < ba.Length; j++)
{
out1.WriteByte(ba[j]);
length++;
}
}
catch (Exception ex)
{
throw new IllegalPropertySetDataException(ex);
}
out1.WriteByte(0x00);
length++;
}
}
return length;
}
/// <summary>
/// OverWrites the base class' method To cope with a redundancy:
/// the property count is maintained in a separate member variable, but
/// shouldn't.
/// </summary>
/// <value>The number of properties in this section.</value>
public override int PropertyCount
{
get { return preprops.Count; }
}
/// <summary>
/// Returns this section's properties.
/// </summary>
/// <value>This section's properties.</value>
public override Property[] Properties
{
get
{
EnsureProperties();
return properties;
}
}
/// <summary>
/// Ensures the properties.
/// </summary>
public void EnsureProperties()
{
properties = (Property[])preprops.ToArray(typeof(Property));
}
/// <summary>
/// Gets a property.
/// </summary>
/// <param name="id">The ID of the property To Get</param>
/// <returns>The property or null if there is no such property</returns>
public override Object GetProperty(long id)
{
/* Calling Properties ensures that properties and preprops are in
* sync. */
EnsureProperties();
return base.GetProperty(id);
}
/// <summary>
/// Sets the section's dictionary. All keys in the dictionary must be
/// {@link java.lang.long} instances, all values must be
/// {@link java.lang.String}s. This method overWrites the properties with IDs
/// 0 and 1 since they are reserved for the dictionary and the dictionary's
/// codepage. Setting these properties explicitly might have surprising
/// effects. An application should never do this but always use this
/// method.
/// </summary>
/// <value>
/// the dictionary
/// </value>
public override IDictionary Dictionary
{
get {
return this.dictionary;
}
set
{
if (value != null)
{
for (IEnumerator i = value.Keys.GetEnumerator();
i.MoveNext(); )
if (!(i.Current is Int64 || i.Current is Int32))
throw new IllegalPropertySetDataException
("Dictionary keys must be of type long. but it's " + i.Current + ","+i.Current.GetType().Name+" now");
this.dictionary = value;
/* Set the dictionary property (ID 0). Please note that the second
* parameter in the method call below is unused because dictionaries
* don't have a type. */
SetProperty(PropertyIDMap.PID_DICTIONARY, -1, value);
/* If the codepage property (ID 1) for the strings (keys and
* values) used in the dictionary is not yet defined, Set it To
* Unicode. */
if (GetProperty(PropertyIDMap.PID_CODEPAGE) == null)
{
SetProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
CodePageUtil.CP_UNICODE);
}
}
else
{
/* Setting the dictionary To null means To Remove property 0.
* However, it does not mean To Remove property 1 (codepage). */
RemoveProperty(PropertyIDMap.PID_DICTIONARY);
}
}
}
/// <summary>
/// Sets the property.
/// </summary>
/// <param name="id">The property ID.</param>
/// <param name="value">The property's value. The value's class must be one of those
/// supported by HPSF.</param>
public void SetProperty(int id, Object value)
{
if (value is String)
SetProperty(id, (String)value);
else if (value is long)
SetProperty(id, ((long)value));
else if (value is int)
SetProperty(id, value);
else if (value is short)
SetProperty(id, (short)value);
else if (value is bool)
SetProperty(id, (bool)value);
else if (value is DateTime)
SetProperty(id, Variant.VT_FILETIME, value);
else
throw new HPSFRuntimeException(
"HPSF does not support properties of type " +
value.GetType().Name + ".");
}
/// <summary>
/// Removes all properties from the section including 0 (dictionary) and
/// 1 (codepage).
/// </summary>
public void Clear()
{
Property[] properties = Properties;
for (int i = 0; i < properties.Length; i++)
{
Property p = properties[i];
RemoveProperty(p.ID);
}
}
/// <summary>
/// Gets the section's codepage, if any.
/// </summary>
/// <value>The section's codepage if one is defined, else -1.</value>
public new int Codepage
{
get { return base.Codepage; }
set
{
SetProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
value);
}
}
}
}
| |
namespace XenAdmin.SettingsPanels
{
partial class WlbThresholdsPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(WlbThresholdsPage));
this.labelBlurb = new System.Windows.Forms.Label();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.decentGroupBox1 = new XenAdmin.Controls.DecentGroupBox();
this.label1DiskWrite = new System.Windows.Forms.Label();
this.labelDiskRead = new System.Windows.Forms.Label();
//CA-134554 - Hide Disk Read/Write until the backend server side is ready
this.label1DiskWrite.Visible = false;
this.labelDiskRead.Visible = false;
this.labelNetworkWrite = new System.Windows.Forms.Label();
this.labelNetworkRead = new System.Windows.Forms.Label();
this.labelFreeMemory = new System.Windows.Forms.Label();
this.labelCPU = new System.Windows.Forms.Label();
this.updownDiskWriteCriticalPoint = new System.Windows.Forms.NumericUpDown();
this.labelNetworkReadUnits = new System.Windows.Forms.Label();
this.updownDiskReadCriticalPoint = new System.Windows.Forms.NumericUpDown();
this.labelFreeMemoryUnits = new System.Windows.Forms.Label();
this.updownNetworkWriteCriticalPoint = new System.Windows.Forms.NumericUpDown();
this.labelCPUUnits = new System.Windows.Forms.Label();
this.updownNetworkReadCriticalPoint = new System.Windows.Forms.NumericUpDown();
this.labelNetworkWriteUnits = new System.Windows.Forms.Label();
this.updownMemoryCriticalPoint = new System.Windows.Forms.NumericUpDown();
this.labelDiskReadUnits = new System.Windows.Forms.Label();
this.updownCPUCriticalPoint = new System.Windows.Forms.NumericUpDown();
this.labelDiskWriteUnits = new System.Windows.Forms.Label();
this.tableLayoutPanel1.SuspendLayout();
this.decentGroupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.updownDiskWriteCriticalPoint)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.updownDiskReadCriticalPoint)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.updownNetworkWriteCriticalPoint)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.updownNetworkReadCriticalPoint)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.updownMemoryCriticalPoint)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.updownCPUCriticalPoint)).BeginInit();
this.SuspendLayout();
//
// labelBlurb
//
resources.ApplyResources(this.labelBlurb, "labelBlurb");
this.labelBlurb.Name = "labelBlurb";
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.decentGroupBox1, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.labelBlurb, 0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// decentGroupBox1
//
resources.ApplyResources(this.decentGroupBox1, "decentGroupBox1");
this.decentGroupBox1.Controls.Add(this.label1DiskWrite);
this.decentGroupBox1.Controls.Add(this.labelDiskRead);
this.decentGroupBox1.Controls.Add(this.labelNetworkWrite);
this.decentGroupBox1.Controls.Add(this.labelNetworkRead);
this.decentGroupBox1.Controls.Add(this.labelFreeMemory);
this.decentGroupBox1.Controls.Add(this.labelCPU);
this.decentGroupBox1.Controls.Add(this.updownDiskWriteCriticalPoint);
this.decentGroupBox1.Controls.Add(this.labelNetworkReadUnits);
this.decentGroupBox1.Controls.Add(this.updownDiskReadCriticalPoint);
this.decentGroupBox1.Controls.Add(this.labelFreeMemoryUnits);
this.decentGroupBox1.Controls.Add(this.updownNetworkWriteCriticalPoint);
this.decentGroupBox1.Controls.Add(this.labelCPUUnits);
this.decentGroupBox1.Controls.Add(this.updownNetworkReadCriticalPoint);
this.decentGroupBox1.Controls.Add(this.labelNetworkWriteUnits);
this.decentGroupBox1.Controls.Add(this.updownMemoryCriticalPoint);
this.decentGroupBox1.Controls.Add(this.labelDiskReadUnits);
this.decentGroupBox1.Controls.Add(this.updownCPUCriticalPoint);
this.decentGroupBox1.Controls.Add(this.labelDiskWriteUnits);
this.decentGroupBox1.Name = "decentGroupBox1";
this.decentGroupBox1.TabStop = false;
//
// label1DiskWrite
//
resources.ApplyResources(this.label1DiskWrite, "label1DiskWrite");
this.label1DiskWrite.ForeColor = System.Drawing.SystemColors.ControlText;
this.label1DiskWrite.Name = "label1DiskWrite";
//
// labelDiskRead
//
resources.ApplyResources(this.labelDiskRead, "labelDiskRead");
this.labelDiskRead.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelDiskRead.Name = "labelDiskRead";
//
// labelNetworkWrite
//
resources.ApplyResources(this.labelNetworkWrite, "labelNetworkWrite");
this.labelNetworkWrite.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelNetworkWrite.Name = "labelNetworkWrite";
//
// labelNetworkRead
//
resources.ApplyResources(this.labelNetworkRead, "labelNetworkRead");
this.labelNetworkRead.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelNetworkRead.Name = "labelNetworkRead";
//
// labelFreeMemory
//
resources.ApplyResources(this.labelFreeMemory, "labelFreeMemory");
this.labelFreeMemory.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelFreeMemory.Name = "labelFreeMemory";
//
// labelCPU
//
resources.ApplyResources(this.labelCPU, "labelCPU");
this.labelCPU.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelCPU.Name = "labelCPU";
//
// updownDiskWriteCriticalPoint
//
this.updownDiskWriteCriticalPoint.Increment = new decimal(new int[] {
10,
0,
0,
0});
resources.ApplyResources(this.updownDiskWriteCriticalPoint, "updownDiskWriteCriticalPoint");
this.updownDiskWriteCriticalPoint.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.updownDiskWriteCriticalPoint.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.updownDiskWriteCriticalPoint.Name = "updownDiskWriteCriticalPoint";
this.updownDiskWriteCriticalPoint.Value = new decimal(new int[] {
1,
0,
0,
0});
this.updownDiskWriteCriticalPoint.ValueChanged += new System.EventHandler(this.updown_ValueChanged);
this.updownDiskWriteCriticalPoint.KeyUp += new System.Windows.Forms.KeyEventHandler(this.updown_KeyUp);
//
// labelNetworkReadUnits
//
resources.ApplyResources(this.labelNetworkReadUnits, "labelNetworkReadUnits");
this.labelNetworkReadUnits.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelNetworkReadUnits.Name = "labelNetworkReadUnits";
//
// updownDiskReadCriticalPoint
//
this.updownDiskReadCriticalPoint.Increment = new decimal(new int[] {
10,
0,
0,
0});
resources.ApplyResources(this.updownDiskReadCriticalPoint, "updownDiskReadCriticalPoint");
this.updownDiskReadCriticalPoint.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.updownDiskReadCriticalPoint.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.updownDiskReadCriticalPoint.Name = "updownDiskReadCriticalPoint";
this.updownDiskReadCriticalPoint.Value = new decimal(new int[] {
1,
0,
0,
0});
this.updownDiskReadCriticalPoint.ValueChanged += new System.EventHandler(this.updown_ValueChanged);
this.updownDiskReadCriticalPoint.KeyUp += new System.Windows.Forms.KeyEventHandler(this.updown_KeyUp);
//
// labelFreeMemoryUnits
//
resources.ApplyResources(this.labelFreeMemoryUnits, "labelFreeMemoryUnits");
this.labelFreeMemoryUnits.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelFreeMemoryUnits.Name = "labelFreeMemoryUnits";
//
// updownNetworkWriteCriticalPoint
//
this.updownNetworkWriteCriticalPoint.Increment = new decimal(new int[] {
10,
0,
0,
0});
resources.ApplyResources(this.updownNetworkWriteCriticalPoint, "updownNetworkWriteCriticalPoint");
this.updownNetworkWriteCriticalPoint.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.updownNetworkWriteCriticalPoint.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.updownNetworkWriteCriticalPoint.Name = "updownNetworkWriteCriticalPoint";
this.updownNetworkWriteCriticalPoint.Value = new decimal(new int[] {
1,
0,
0,
0});
this.updownNetworkWriteCriticalPoint.ValueChanged += new System.EventHandler(this.updown_ValueChanged);
this.updownNetworkWriteCriticalPoint.KeyUp += new System.Windows.Forms.KeyEventHandler(this.updown_KeyUp);
//
// labelCPUUnits
//
resources.ApplyResources(this.labelCPUUnits, "labelCPUUnits");
this.labelCPUUnits.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelCPUUnits.Name = "labelCPUUnits";
//
// updownNetworkReadCriticalPoint
//
this.updownNetworkReadCriticalPoint.Increment = new decimal(new int[] {
10,
0,
0,
0});
resources.ApplyResources(this.updownNetworkReadCriticalPoint, "updownNetworkReadCriticalPoint");
this.updownNetworkReadCriticalPoint.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.updownNetworkReadCriticalPoint.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.updownNetworkReadCriticalPoint.Name = "updownNetworkReadCriticalPoint";
this.updownNetworkReadCriticalPoint.Value = new decimal(new int[] {
1,
0,
0,
0});
this.updownNetworkReadCriticalPoint.ValueChanged += new System.EventHandler(this.updown_ValueChanged);
this.updownNetworkReadCriticalPoint.KeyUp += new System.Windows.Forms.KeyEventHandler(this.updown_KeyUp);
//
// labelNetworkWriteUnits
//
resources.ApplyResources(this.labelNetworkWriteUnits, "labelNetworkWriteUnits");
this.labelNetworkWriteUnits.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelNetworkWriteUnits.Name = "labelNetworkWriteUnits";
//
// updownMemoryCriticalPoint
//
this.updownMemoryCriticalPoint.Increment = new decimal(new int[] {
50,
0,
0,
0});
resources.ApplyResources(this.updownMemoryCriticalPoint, "updownMemoryCriticalPoint");
this.updownMemoryCriticalPoint.Maximum = new decimal(new int[] {
32000,
0,
0,
0});
this.updownMemoryCriticalPoint.Name = "updownMemoryCriticalPoint";
this.updownMemoryCriticalPoint.ValueChanged += new System.EventHandler(this.updown_ValueChanged);
this.updownMemoryCriticalPoint.KeyUp += new System.Windows.Forms.KeyEventHandler(this.updown_KeyUp);
//
// labelDiskReadUnits
//
resources.ApplyResources(this.labelDiskReadUnits, "labelDiskReadUnits");
this.labelDiskReadUnits.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelDiskReadUnits.Name = "labelDiskReadUnits";
//
// updownCPUCriticalPoint
//
resources.ApplyResources(this.updownCPUCriticalPoint, "updownCPUCriticalPoint");
this.updownCPUCriticalPoint.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.updownCPUCriticalPoint.Name = "updownCPUCriticalPoint";
this.updownCPUCriticalPoint.Value = new decimal(new int[] {
1,
0,
0,
0});
this.updownCPUCriticalPoint.ValueChanged += new System.EventHandler(this.updown_ValueChanged);
this.updownCPUCriticalPoint.KeyUp += new System.Windows.Forms.KeyEventHandler(this.updown_KeyUp);
//
// labelDiskWriteUnits
//
resources.ApplyResources(this.labelDiskWriteUnits, "labelDiskWriteUnits");
this.labelDiskWriteUnits.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelDiskWriteUnits.Name = "labelDiskWriteUnits";
//
// WlbThresholdsPage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.SystemColors.Window;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "WlbThresholdsPage";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.decentGroupBox1.ResumeLayout(false);
this.decentGroupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.updownDiskWriteCriticalPoint)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.updownDiskReadCriticalPoint)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.updownNetworkWriteCriticalPoint)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.updownNetworkReadCriticalPoint)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.updownMemoryCriticalPoint)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.updownCPUCriticalPoint)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label labelBlurb;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private XenAdmin.Controls.DecentGroupBox decentGroupBox1;
private System.Windows.Forms.Label label1DiskWrite;
private System.Windows.Forms.Label labelDiskRead;
private System.Windows.Forms.Label labelNetworkWrite;
private System.Windows.Forms.Label labelNetworkRead;
private System.Windows.Forms.Label labelFreeMemory;
private System.Windows.Forms.Label labelCPU;
private System.Windows.Forms.NumericUpDown updownDiskWriteCriticalPoint;
private System.Windows.Forms.Label labelNetworkReadUnits;
private System.Windows.Forms.NumericUpDown updownDiskReadCriticalPoint;
private System.Windows.Forms.Label labelFreeMemoryUnits;
private System.Windows.Forms.NumericUpDown updownNetworkWriteCriticalPoint;
private System.Windows.Forms.Label labelCPUUnits;
private System.Windows.Forms.NumericUpDown updownNetworkReadCriticalPoint;
private System.Windows.Forms.Label labelNetworkWriteUnits;
private System.Windows.Forms.NumericUpDown updownMemoryCriticalPoint;
private System.Windows.Forms.Label labelDiskReadUnits;
private System.Windows.Forms.NumericUpDown updownCPUCriticalPoint;
private System.Windows.Forms.Label labelDiskWriteUnits;
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using WOSI.IVR.IML.Classes;
using WOSI.IVR.IML.Classes.ScriptActions;
using WOSI.IVR.IML.Classes.ScriptEvents;
using System.Globalization;
using System.Text.RegularExpressions;
using CallButler.Service.ScriptProcessing.ScriptCompilers;
using CallButler.Service.Services;
//using T2.Kinesis.Gidgets;
namespace CallButler.Service.ScriptProcessing
{
class ExtensionScriptProcessor : ScriptProcessorBase
{
private enum ExtensionExternalCommands
{
CALLBUTLERINTERNAL_GetNextNumber,
CALLBUTLERINTERNAL_SendToVoicemail,
CALLBUTLERINTERNAL_ConnectCalls,
CALLBUTLERINTERNAL_ConfirmingTransfer,
CALLBUTLERINTERNAL_ForwardCall
}
public enum ExtensionExternalEvents
{
CALLBUTLERINTERNAL_NoMoreNumbers,
CALLBUTLERINTERNAL_OtherCallerHungUp,
CALLBUTLERINTERNAL_SkipConfirmation,
CALLBUTLERINTERNAL_GetNextNumber,
CALLBUTLERINTERNAL_SendToVoicemail,
CALLBUTLERINTERNAL_ForwardCall
}
private enum VoicemailExternalCommands
{
CALLBUTLERINTERNAL_EndExtensionFinder
}
public enum VoicemailExternalEvents
{
CALLBUTLERINTERNAL_ExtensionNotAvailable,
CALLBUTLERINTERNAL_CallForwarded
}
private WOSI.CallButler.Data.CallButlerDataset.ExtensionsRow extension;
private WOSI.CallButler.Data.CallButlerDataset.ExtensionsRow parentExtension = null;
private TelecomScriptInterface tsInterface = null;
private TelecomScriptInterface onholdTsInterface;
private VoicemailMailerService vmMailerService;
private PBXRegistrarService registrarService;
private int extensionNumberIndex = -1;
private int parentExtensionIndex = -1;
private bool disableCallScreening = false;
private bool autoConnect = true;
private bool autoAnswer = false;
ScriptService scriptService;
//ExtensionStateService extStateService;
Call callScriptElement;
public ExtensionScriptProcessor(ScriptService scriptService, TelecomScriptInterface onholdTsInterface, WOSI.CallButler.Data.CallButlerDataset.ExtensionsRow extension, VoicemailMailerService vmMailerService, PBXRegistrarService registrarService/*, ExtensionStateService extStateService*/, bool disableCallScreening, bool autoConnect, bool autoAnswer)
{
this.autoAnswer = autoAnswer;
this.scriptService = scriptService;
this.registrarService = registrarService;
this.onholdTsInterface = onholdTsInterface;
this.extension = extension;
this.vmMailerService = vmMailerService;
//this.extStateService = extStateService;
this.disableCallScreening = disableCallScreening;
this.autoConnect = autoConnect;
}
public WOSI.CallButler.Data.CallButlerDataset.ExtensionsRow Extension
{
get
{
return this.extension;
}
}
protected override void OnStartProcessing(TelecomScriptInterface tsInterface, CallButler.Telecom.TelecomProviderBase telecomProvider, WOSI.CallButler.Data.DataProviders.CallButlerDataProviderBase dataProvider)
{
tsInterface.IMLInterpreter.DefaultSpeechVoice = Properties.Settings.Default.DefaultTTSVoice;
// Set our volumes
telecomProvider.SetRecordVolume(tsInterface.LineNumber, Properties.Settings.Default.RecordVolume);
telecomProvider.SetSoundVolume(tsInterface.LineNumber, Properties.Settings.Default.SoundVolume);
telecomProvider.SetSpeechVolume(tsInterface.LineNumber, Properties.Settings.Default.SpeechVolume);
string extensionFinderScriptLocation = WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.SystemScriptsRootDirectory) + "\\Extension Finder.xml";
if (File.Exists(extensionFinderScriptLocation))
{
onholdTsInterface.IMLInterpreter.SyncExternalAction += new EventHandler<WOSI.IVR.IML.SyncExternalActionEventArgs>(IMLInterpreter_SyncExternalAction);
IMLScript imlScript = IMLScript.OpenScript(extensionFinderScriptLocation);
// Get our call script element
ScriptElement[] callElements = imlScript.GetAllElementsOfType(typeof(Call));
if (callElements != null && callElements.Length > 0)
{
callScriptElement = (Call)callElements[0];
}
extensionNumberIndex = -1;
this.tsInterface = tsInterface;
// Copy our variables
tsInterface.IMLInterpreter.MergeLocalVariables(onholdTsInterface.IMLInterpreter);
tsInterface.IMLInterpreter.SetLocalVariable("ExtensionTimeout", "20");
tsInterface.IMLInterpreter.StartScript(imlScript, WOSI.Utilities.FileUtils.GetApplicationRelativePath(Properties.Settings.Default.SystemScriptsRootDirectory));
// Tell our extension that they have an incoming call
//CallInfo callInfo = new CallInfo(tsInterface.CurrentCallID, tsInterface.LineNumber, CallStatus.Incoming, onholdTsInterface.IMLInterpreter.CallerDisplayName, onholdTsInterface.IMLInterpreter.CallerUsername);
//extStateService.UpdateCallState(extension.ExtensionID, callInfo);
}
}
void IMLInterpreter_SyncExternalAction(object sender, WOSI.IVR.IML.SyncExternalActionEventArgs e)
{
// Parse out our external event action
if (Enum.IsDefined(typeof(VoicemailExternalCommands), e.Action))
{
VoicemailExternalCommands externalCommand = WOSI.Utilities.EnumUtils<VoicemailExternalCommands>.Parse(e.Action);
switch (externalCommand)
{
case VoicemailExternalCommands.CALLBUTLERINTERNAL_EndExtensionFinder:
{
// Allow this line to answer calls again
tsInterface.Locked = false;
tsInterface.IMLInterpreter.SignalExternalEvent(ExtensionExternalEvents.CALLBUTLERINTERNAL_OtherCallerHungUp.ToString());
// Don't subscribe to this event anymore after the call has ended
((WOSI.IVR.IML.IMLInterpreter)sender).SyncExternalAction -= IMLInterpreter_SyncExternalAction;
break;
}
}
((WOSI.IVR.IML.IMLInterpreter)sender).SignalEventCallback(e.EventToken);
}
}
private void TryContactNumber(TelecomScriptInterface tsInterface, string numberToCall, string fromCallerID, string fromCallerNumber, string callProfile, string timeout, string eventToken)
{
// If we get here, try the number
tsInterface.IMLInterpreter.SetLocalVariable("NumberToCall", numberToCall);
if (Properties.Settings.Default.CustomIncomingCallerID != null && Properties.Settings.Default.CustomIncomingCallerID.Length > 0)
{
tsInterface.IMLInterpreter.SetLocalVariable("FromCallerID", Properties.Settings.Default.CustomIncomingCallerID);
}
else
{
tsInterface.IMLInterpreter.SetLocalVariable("FromCallerID", fromCallerID);
}
if (Properties.Settings.Default.CustomIncomingCallerNumber != null && Properties.Settings.Default.CustomIncomingCallerNumber.Length > 0)
{
tsInterface.IMLInterpreter.SetLocalVariable("FromNumber", Properties.Settings.Default.CustomIncomingCallerNumber);
}
else
{
tsInterface.IMLInterpreter.SetLocalVariable("FromNumber", fromCallerNumber);
}
tsInterface.IMLInterpreter.SetLocalVariable("CallProfile", callProfile);
SetupScriptForCall(tsInterface, timeout);
tsInterface.IMLInterpreter.SignalEventCallback(eventToken);
}
private void TryCallBlast(CallButler.Telecom.TelecomProviderBase telecomProvider, TelecomScriptInterface tsInterface, string[] numbersToCall, string[] profileNames, string fromCallerID, string fromCallerNumber, string timeout)
{
List<WOSI.CallButler.Data.CallButlerDataset.ProvidersRow> providers = new List<WOSI.CallButler.Data.CallButlerDataset.ProvidersRow>();
foreach (string profileName in profileNames)
{
providers.Add(tsInterface.FindProvider(profileName));
}
if (Properties.Settings.Default.CustomIncomingCallerID != null && Properties.Settings.Default.CustomIncomingCallerID.Length > 0)
{
fromCallerID = Properties.Settings.Default.CustomIncomingCallerID;
}
if (Properties.Settings.Default.CustomIncomingCallerNumber != null && Properties.Settings.Default.CustomIncomingCallerNumber.Length > 0)
{
fromCallerNumber = Properties.Settings.Default.CustomIncomingCallerNumber;
}
telecomProvider.CallBlast(tsInterface.LineNumber, numbersToCall, fromCallerID, fromCallerNumber, providers.ToArray());
SetupScriptForCall(tsInterface, timeout);
}
private void SetupScriptForCall(TelecomScriptInterface tsInterface, string timeout)
{
string callFrom = "";
if (Properties.Settings.Default.CustomCallScreeningPrompt != null && Properties.Settings.Default.CustomCallScreeningPrompt.Length > 0)
{
callFrom = Properties.Settings.Default.CustomCallScreeningPrompt;
}
else
{
if (onholdTsInterface.IMLInterpreter.CallerDisplayName.Length > 0)
callFrom = WOSI.Utilities.StringUtils.FormatPhoneNumber(onholdTsInterface.IMLInterpreter.CallerDisplayName);
else if (onholdTsInterface.IMLInterpreter.CallerUsername.Length > 0)
callFrom = WOSI.Utilities.StringUtils.FormatPhoneNumber(onholdTsInterface.IMLInterpreter.CallerUsername);
else
callFrom = "An Unknown Caller.";
}
tsInterface.IMLInterpreter.SetLocalVariable("CallFrom", callFrom);
tsInterface.IMLInterpreter.SetLocalVariable("ExtensionTimeout", timeout);
// Set our call element to autodial or not
if (callScriptElement != null)
{
callScriptElement.RequestAutoAnswer = autoAnswer;
}
}
public override void OnCallTemporarilyMoved(CallButler.Telecom.TelecomProviderBase telcomProvider, CallButler.Telecom.CallEventArgs e)
{
onholdTsInterface.IMLInterpreter.SetLocalVariable("TransferNumber", e.CallingToNumber);
onholdTsInterface.IMLInterpreter.SignalExternalEvent(VoicemailExternalEvents.CALLBUTLERINTERNAL_CallForwarded.ToString());
}
protected override void OnExternalCommand(string command, string commandData, string eventToken, TelecomScriptInterface tsInterface, CallButler.Telecom.TelecomProviderBase telecomProvider, WOSI.CallButler.Data.DataProviders.CallButlerDataProviderBase dataProvider)
{
// Parse out our external event action
if (Enum.IsDefined(typeof(ExtensionExternalCommands), command))
{
ExtensionExternalCommands externalCommand = WOSI.Utilities.EnumUtils<ExtensionExternalCommands>.Parse(command);
switch (externalCommand)
{
case ExtensionExternalCommands.CALLBUTLERINTERNAL_ForwardCall:
{
onholdTsInterface.IMLInterpreter.SetLocalVariable("TransferNumber", commandData);
onholdTsInterface.IMLInterpreter.SignalExternalEvent(VoicemailExternalEvents.CALLBUTLERINTERNAL_CallForwarded.ToString());
break;
}
case ExtensionExternalCommands.CALLBUTLERINTERNAL_ConfirmingTransfer:
{
if (disableCallScreening || !extension.EnableCallScreening)
{
tsInterface.IMLInterpreter.SignalExternalEvent(ExtensionExternalEvents.CALLBUTLERINTERNAL_SkipConfirmation.ToString());
}
else
{
tsInterface.IMLInterpreter.SignalEventCallback(eventToken);
}
break;
}
case ExtensionExternalCommands.CALLBUTLERINTERNAL_GetNextNumber:
{
string callerID = onholdTsInterface.IMLInterpreter.CallerDisplayName;
string callerNumber = onholdTsInterface.IMLInterpreter.CallerUsername;
if (callerID == null || callerID.Length == 0)
callerID = "Unknown Caller";
if (callerNumber == null || callerNumber.Length == 0)
callerNumber = "";
// If we have a previous call, end it
if (telecomProvider.IsLineInUse(tsInterface.LineNumber))
{
telecomProvider.EndCall(tsInterface.LineNumber);
}
else
{
// Get our extension contact numbers
List<WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow> contactNumbers = new List<WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow>((WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow[])dataProvider.GetExtensionContactNumbers(extension.ExtensionID).Select("", "Priority ASC"));
if (extensionNumberIndex + 1 >= contactNumbers.Count && parentExtension != null)
{
extensionNumberIndex = parentExtensionIndex;
parentExtensionIndex = -1;
extension = parentExtension;
parentExtension = null;
contactNumbers.Clear();
contactNumbers.AddRange((WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow[])dataProvider.GetExtensionContactNumbers(extension.ExtensionID).Select("", "Priority ASC"));
}
extensionNumberIndex++;
List<string> callBlastNumbers = new List<string>();
List<string> callBlastProfiles = new List<string>();
int callBlastTimeout = Properties.Settings.Default.CallBlastTimeout;
while (extensionNumberIndex < contactNumbers.Count)
{
WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow contactNumber = contactNumbers[extensionNumberIndex];
// Is the number online?
if (contactNumber.Online)
{
// Does the number have hours?
TimeSpan utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
if (!contactNumber.IsHoursOfOperationUTCOffsetNull())
utcOffset = contactNumber.HoursOfOperationUTCOffset;
if (!contactNumber.HasHoursOfOperation || (contactNumber.HasHoursOfOperation && ScriptUtils.IsInHoursOfOperation(contactNumber.HoursOfOperation, utcOffset)))
{
// Check to see if this number is a PBX IP line
if ((contactNumber.CallPBXPhone || (WOSI.CallButler.Data.ExtensionContactNumberType)contactNumber.Type == WOSI.CallButler.Data.ExtensionContactNumberType.IPPhone) && registrarService != null)
{
int extNumber = extension.ExtensionNumber;
// If this was filled in from another extension, we'll need to check the status of that extension
if (contactNumber.ExtensionID != extension.ExtensionID)
{
WOSI.CallButler.Data.CallButlerDataset.ExtensionsRow tmpExtension = dataProvider.GetExtension(Properties.Settings.Default.CustomerID, contactNumber.ExtensionID);
if (tmpExtension != null)
extNumber = tmpExtension.ExtensionNumber;
}
// Check to see if this pbx phone is online
PBXPresenceInfo[] presInfos = registrarService.GetPresenceInfoForExtension(extNumber);
if (presInfos != null && presInfos.Length > 0)
{
foreach (PBXPresenceInfo presInfo in presInfos)
{
if (presInfo.Status == PBXPresenceStatus.Online)
{
if (presInfos.Length > 1 || extension.UseCallBlast)
{
if (contactNumbers.Count == 1)
callBlastTimeout = contactNumber.Timeout;
string callBlastNumber = string.Format("sip:{0}@{1}:{2}", presInfo.ExtensionNumber, presInfo.RemoteAddress, presInfo.RemotePort);
if (!callBlastNumbers.Contains(callBlastNumber))
{
callBlastNumbers.Add(callBlastNumber);
callBlastProfiles.Add(TelecomScriptInterface.InternalProviderProfileName);
}
}
else
{
TryContactNumber(tsInterface, string.Format("sip:{0}@{1}:{2}", presInfo.ExtensionNumber, presInfo.RemoteAddress, presInfo.RemotePort), callerID, callerNumber, TelecomScriptInterface.InternalProviderProfileName, contactNumber.Timeout.ToString(), eventToken);
return;
}
}
}
if (!extension.UseCallBlast && callBlastNumbers.Count > 0)
break;
}
}
else if ((WOSI.CallButler.Data.ExtensionContactNumberType)contactNumber.Type == WOSI.CallButler.Data.ExtensionContactNumberType.TelephoneNumber)
{
if (extension.UseCallBlast)
{
if (!callBlastNumbers.Contains(contactNumber.ContactNumber))
{
callBlastNumbers.Add(contactNumber.ContactNumber);
callBlastProfiles.Add("");
}
}
else
{
TryContactNumber(tsInterface, contactNumber.ContactNumber, callerID, callerNumber, "", contactNumber.Timeout.ToString(), eventToken);
return;
}
}
else if ((WOSI.CallButler.Data.ExtensionContactNumberType)contactNumber.Type == WOSI.CallButler.Data.ExtensionContactNumberType.Extension && parentExtension == null)
{
try
{
// Get our new extension
WOSI.CallButler.Data.CallButlerDataset.ExtensionsRow newExtension = dataProvider.GetExtension(Properties.Settings.Default.CustomerID, new Guid(contactNumber.ContactNumber));
if (newExtension != null)
{
if (extension.UseCallBlast)
{
WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow[] newContacts = (WOSI.CallButler.Data.CallButlerDataset.ExtensionContactNumbersRow[])dataProvider.GetExtensionContactNumbers(newExtension.ExtensionID).Select("Type <> " + (int)WOSI.CallButler.Data.ExtensionContactNumberType.Extension, "Priority ASC");
contactNumbers.AddRange(newContacts);
}
else
{
parentExtension = extension;
parentExtensionIndex = extensionNumberIndex;
extensionNumberIndex = -1;
extension = newExtension;
tsInterface.IMLInterpreter.SignalExternalEvent(ExtensionExternalEvents.CALLBUTLERINTERNAL_GetNextNumber.ToString());
return;
}
}
}
catch
{
}
}
}
}
extensionNumberIndex++;
}
if (callBlastNumbers.Count > 0)
{
TryCallBlast(telecomProvider, tsInterface, callBlastNumbers.ToArray(), callBlastProfiles.ToArray(), callerID, callerNumber, callBlastTimeout.ToString());
return;
}
else
{
tsInterface.IMLInterpreter.SignalExternalEvent(ExtensionExternalEvents.CALLBUTLERINTERNAL_NoMoreNumbers.ToString());
}
}
break;
}
case ExtensionExternalCommands.CALLBUTLERINTERNAL_SendToVoicemail:
{
onholdTsInterface.IMLInterpreter.SyncExternalAction -= IMLInterpreter_SyncExternalAction;
// Allow this line to answer calls again
tsInterface.Locked = false;
if (telecomProvider.IsLineInUse(onholdTsInterface.LineNumber))
{
telecomProvider.SendingToVoicemail(onholdTsInterface.LineNumber);
}
onholdTsInterface.IMLInterpreter.SignalExternalEvent(VoicemailExternalEvents.CALLBUTLERINTERNAL_ExtensionNotAvailable.ToString());
tsInterface.IMLInterpreter.SignalEventCallback(eventToken);
break;
}
case ExtensionExternalCommands.CALLBUTLERINTERNAL_ConnectCalls:
{
onholdTsInterface.IMLInterpreter.SyncExternalAction -= IMLInterpreter_SyncExternalAction;
onholdTsInterface.IMLInterpreter.SignalExternalEvent(ExtensionExternalCommands.CALLBUTLERINTERNAL_ConnectCalls.ToString());
// Allow this line to answer calls again
tsInterface.Locked = false;
if (autoConnect)
{
if (telecomProvider.IsLineInUse(tsInterface.LineNumber) && telecomProvider.IsLineInUse(onholdTsInterface.LineNumber))
{
if (extension.IsUseConferenceTransferNull() || !extension.UseConferenceTransfer /*|| !Licensing.Management.AppPermissions.StatIsPermitted("Handoff")*/)
{
telecomProvider.TransferCallAttended(onholdTsInterface.LineNumber, tsInterface.LineNumber, Properties.Settings.Default.UseBridgedTransfers);
tsInterface.IMLInterpreter.SignalEventCallback(eventToken);
}
else
{
telecomProvider.StopSound(tsInterface.LineNumber);
telecomProvider.StopSound(onholdTsInterface.LineNumber);
int conferenceID = telecomProvider.ConferenceLines(tsInterface.LineNumber, onholdTsInterface.LineNumber);
// Check to see if the person calling is an internal extension
if (onholdTsInterface.Extension != null)
{
onholdTsInterface.ScriptProcessor = new TransferConferenceScriptProcessor(conferenceID, scriptService, tsInterface, registrarService, extension, vmMailerService);
}
else
{
onholdTsInterface.ScriptProcessor = new TransferConferenceParticipantScriptProcessor(conferenceID, tsInterface, extension, vmMailerService);
}
tsInterface.ScriptProcessor = new TransferConferenceScriptProcessor(conferenceID, scriptService, onholdTsInterface, registrarService, extension, vmMailerService);
onholdTsInterface.ScriptProcessor.StartProcessing(onholdTsInterface, telecomProvider, dataProvider);
tsInterface.ScriptProcessor.StartProcessing(tsInterface, telecomProvider, dataProvider);
}
}
else
{
tsInterface.IMLInterpreter.SignalEventCallback(eventToken);
}
}
break;
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using SimpleContainer.Helpers;
using SimpleContainer.Infection;
using SimpleContainer.Interface;
namespace SimpleContainer.Configuration
{
public abstract class AbstractConfigurationBuilder<TSelf>
where TSelf : AbstractConfigurationBuilder<TSelf>
{
internal ConfigurationRegistry.Builder RegistryBuilder { get; private set; }
protected readonly List<string> contracts;
internal AbstractConfigurationBuilder(ConfigurationRegistry.Builder registryBuilder, List<string> contracts)
{
RegistryBuilder = registryBuilder;
this.contracts = contracts;
}
public TSelf Bind<TInterface, TImplementation>(bool clearOld = false)
where TImplementation : TInterface
{
GetServiceBuilder(typeof (TInterface)).Bind(typeof (TInterface), typeof (TImplementation), clearOld);
return Self;
}
public TSelf Bind(Type interfaceType, Type implementationType, bool clearOld)
{
GetServiceBuilder(interfaceType).Bind(interfaceType, implementationType, clearOld);
return Self;
}
public TSelf Bind(Type interfaceType, Type implementationType)
{
GetServiceBuilder(interfaceType).Bind(interfaceType, implementationType, false);
return Self;
}
public TSelf Bind<T>(T value, bool containerOwnsInstance = true)
{
GetServiceBuilder(typeof (T)).Bind(typeof (T), value, containerOwnsInstance);
return Self;
}
public TSelf Bind(Type interfaceType, object value, bool containerOwnsInstance = true)
{
GetServiceBuilder(interfaceType).Bind(interfaceType, value, containerOwnsInstance);
return Self;
}
public TSelf WithInstanceFilter<T>(Func<T, bool> filter)
{
GetServiceBuilder(typeof (T)).WithInstanceFilter(filter);
return Self;
}
public TSelf WithImplicitDependency<T>(ServiceName name)
{
GetServiceBuilder(typeof(T)).WithImplicitDependency(name);
return Self;
}
public TSelf WithComment<T>(string comment)
{
GetServiceBuilder(typeof(T)).SetComment(comment);
return Self;
}
public TSelf Bind<T>(Func<IContainer, T> creator, bool containerOwnsInstance = true)
{
GetServiceBuilder(typeof (T)).Bind(c => creator(c), containerOwnsInstance);
return Self;
}
public TSelf Bind(Type type, Func<IContainer, object> creator, bool containerOwnsInstance = true)
{
GetServiceBuilder(type).Bind(creator, containerOwnsInstance);
return Self;
}
public TSelf Bind<T>(Func<IContainer, Type, T> creator, bool containerOwnsInstance = true)
{
GetServiceBuilder(typeof (T)).Bind((c, t) => creator(c, t), containerOwnsInstance);
return Self;
}
public TSelf Bind(Type type, Func<IContainer, Type, object> creator, bool containerOwnsInstance = true)
{
GetServiceBuilder(type).Bind(creator, containerOwnsInstance);
return Self;
}
public TSelf BindDependency<T>(string dependencyName, object value)
{
GetServiceBuilder(typeof (T)).BindDependency(dependencyName, value);
return Self;
}
public TSelf BindDependency(Type type, string dependencyName, object value)
{
GetServiceBuilder(type).BindDependency(dependencyName, value);
return Self;
}
public TSelf BindDependency<T, TDependency>(TDependency value)
{
GetServiceBuilder(typeof (T)).BindDependency(value);
return Self;
}
public TSelf BindDependency<T, TDependency, TDependencyValue>()
where TDependencyValue : TDependency
{
GetServiceBuilder(typeof (T)).BindDependency<TDependency, TDependencyValue>();
return Self;
}
public TSelf BindDependency(Type type, Type dependencyType, Func<IContainer, object> creator)
{
GetServiceBuilder(type).BindDependency(dependencyType, creator);
return Self;
}
public TSelf BindDependencyFactory<T>(string dependencyName, Func<IContainer, object> creator)
{
GetServiceBuilder(typeof (T)).BindDependencyFactory(dependencyName, creator);
return Self;
}
public TSelf BindDependencyImplementation<T, TDependencyImplementation>(string dependencyName)
{
GetServiceBuilder(typeof (T)).BindDependencyImplementation<TDependencyImplementation>(dependencyName);
return Self;
}
public TSelf BindDependencyImplementation<T, TDependencyInterface, TDependencyImplementation>()
{
GetServiceBuilder(typeof (T)).BindDependencyImplementation<TDependencyInterface, TDependencyImplementation>();
return Self;
}
public TSelf BindDependencies<T>(object dependencies)
{
GetServiceBuilder(typeof (T)).BindDependencies(dependencies);
return Self;
}
public TSelf BindDependencies<T>(IParametersSource parameters)
{
GetServiceBuilder(typeof (T)).BindDependencies(parameters);
return Self;
}
public TSelf BindDependencyValue(Type type, Type dependencyType, object value)
{
GetServiceBuilder(type).BindDependencyValue(dependencyType, value);
return Self;
}
public TSelf DontUse(Type t)
{
GetServiceBuilder(t).DontUse();
return Self;
}
public TSelf DontUse<T>()
{
GetServiceBuilder(typeof (T)).DontUse();
return Self;
}
public TSelf IgnoreImplementation(Type t)
{
GetServiceBuilder(t).IgnoreImplementation();
return Self;
}
public TSelf IgnoreImplementation<T>()
{
GetServiceBuilder(typeof (T)).IgnoreImplementation();
return Self;
}
private ServiceConfiguration.Builder GetServiceBuilder(Type type)
{
return RegistryBuilder.GetConfigurationSet(type).GetBuilder(contracts);
}
private TSelf Self
{
get { return (TSelf) this; }
}
public ContractConfigurationBuilder Contract(params string[] newContracts)
{
return new ContractConfigurationBuilder(RegistryBuilder, contracts.Concat(newContracts.ToList()));
}
public ContractConfigurationBuilder Contract<T>()
where T : RequireContractAttribute, new()
{
return Contract(InternalHelpers.NameOf<T>());
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Studio.V2
{
/// <summary>
/// Create a Flow.
/// </summary>
public class CreateFlowOptions : IOptions<FlowResource>
{
/// <summary>
/// The string that you assigned to describe the Flow
/// </summary>
public string FriendlyName { get; }
/// <summary>
/// The status of the Flow
/// </summary>
public FlowResource.StatusEnum Status { get; }
/// <summary>
/// JSON representation of flow definition
/// </summary>
public object Definition { get; }
/// <summary>
/// Description of change made in the revision
/// </summary>
public string CommitMessage { get; set; }
/// <summary>
/// Construct a new CreateFlowOptions
/// </summary>
/// <param name="friendlyName"> The string that you assigned to describe the Flow </param>
/// <param name="status"> The status of the Flow </param>
/// <param name="definition"> JSON representation of flow definition </param>
public CreateFlowOptions(string friendlyName, FlowResource.StatusEnum status, object definition)
{
FriendlyName = friendlyName;
Status = status;
Definition = definition;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (Status != null)
{
p.Add(new KeyValuePair<string, string>("Status", Status.ToString()));
}
if (Definition != null)
{
p.Add(new KeyValuePair<string, string>("Definition", Serializers.JsonObject(Definition)));
}
if (CommitMessage != null)
{
p.Add(new KeyValuePair<string, string>("CommitMessage", CommitMessage));
}
return p;
}
}
/// <summary>
/// Update a Flow.
/// </summary>
public class UpdateFlowOptions : IOptions<FlowResource>
{
/// <summary>
/// The SID that identifies the resource to fetch
/// </summary>
public string PathSid { get; }
/// <summary>
/// The status of the Flow
/// </summary>
public FlowResource.StatusEnum Status { get; }
/// <summary>
/// The string that you assigned to describe the Flow
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// JSON representation of flow definition
/// </summary>
public object Definition { get; set; }
/// <summary>
/// Description of change made in the revision
/// </summary>
public string CommitMessage { get; set; }
/// <summary>
/// Construct a new UpdateFlowOptions
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="status"> The status of the Flow </param>
public UpdateFlowOptions(string pathSid, FlowResource.StatusEnum status)
{
PathSid = pathSid;
Status = status;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Status != null)
{
p.Add(new KeyValuePair<string, string>("Status", Status.ToString()));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (Definition != null)
{
p.Add(new KeyValuePair<string, string>("Definition", Serializers.JsonObject(Definition)));
}
if (CommitMessage != null)
{
p.Add(new KeyValuePair<string, string>("CommitMessage", CommitMessage));
}
return p;
}
}
/// <summary>
/// Retrieve a list of all Flows.
/// </summary>
public class ReadFlowOptions : ReadOptions<FlowResource>
{
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// Retrieve a specific Flow.
/// </summary>
public class FetchFlowOptions : IOptions<FlowResource>
{
/// <summary>
/// The SID that identifies the resource to fetch
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchFlowOptions
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
public FetchFlowOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Delete a specific Flow.
/// </summary>
public class DeleteFlowOptions : IOptions<FlowResource>
{
/// <summary>
/// The SID that identifies the resource to delete
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteFlowOptions
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to delete </param>
public DeleteFlowOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
}
| |
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 IWorkOrderOriginalData : ISchemaBaseOriginalData
{
int OrderQty { get; }
int StockedQty { get; }
int ScrappedQty { get; }
System.DateTime StartDate { get; }
System.DateTime? EndDate { get; }
System.DateTime DueDate { get; }
ScrapReason ScrapReason { get; }
Product Product { get; }
}
public partial class WorkOrder : OGM<WorkOrder, WorkOrder.WorkOrderData, System.String>, ISchemaBase, INeo4jBase, IWorkOrderOriginalData
{
#region Initialize
static WorkOrder()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, WorkOrder> 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.WorkOrderAlias, IWhereQuery> query)
{
q.WorkOrderAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.WorkOrder.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"WorkOrder => OrderQty : {this.OrderQty}, StockedQty : {this.StockedQty}, ScrappedQty : {this.ScrappedQty}, StartDate : {this.StartDate}, EndDate : {this.EndDate?.ToString() ?? "null"}, DueDate : {this.DueDate}, 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 WorkOrderData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.OrderQty == null)
throw new PersistenceException(string.Format("Cannot save WorkOrder with key '{0}' because the OrderQty cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.StockedQty == null)
throw new PersistenceException(string.Format("Cannot save WorkOrder with key '{0}' because the StockedQty cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ScrappedQty == null)
throw new PersistenceException(string.Format("Cannot save WorkOrder with key '{0}' because the ScrappedQty cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.StartDate == null)
throw new PersistenceException(string.Format("Cannot save WorkOrder with key '{0}' because the StartDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.DueDate == null)
throw new PersistenceException(string.Format("Cannot save WorkOrder with key '{0}' because the DueDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save WorkOrder 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 WorkOrderData : Data<System.String>
{
public WorkOrderData()
{
}
public WorkOrderData(WorkOrderData data)
{
OrderQty = data.OrderQty;
StockedQty = data.StockedQty;
ScrappedQty = data.ScrappedQty;
StartDate = data.StartDate;
EndDate = data.EndDate;
DueDate = data.DueDate;
ScrapReason = data.ScrapReason;
Product = data.Product;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "WorkOrder";
ScrapReason = new EntityCollection<ScrapReason>(Wrapper, Members.ScrapReason);
Product = new EntityCollection<Product>(Wrapper, Members.Product);
}
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("OrderQty", Conversion<int, long>.Convert(OrderQty));
dictionary.Add("StockedQty", Conversion<int, long>.Convert(StockedQty));
dictionary.Add("ScrappedQty", Conversion<int, long>.Convert(ScrappedQty));
dictionary.Add("StartDate", Conversion<System.DateTime, long>.Convert(StartDate));
dictionary.Add("EndDate", Conversion<System.DateTime?, long?>.Convert(EndDate));
dictionary.Add("DueDate", Conversion<System.DateTime, long>.Convert(DueDate));
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("OrderQty", out value))
OrderQty = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("StockedQty", out value))
StockedQty = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("ScrappedQty", out value))
ScrappedQty = Conversion<long, int>.Convert((long)value);
if (properties.TryGetValue("StartDate", out value))
StartDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("EndDate", out value))
EndDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("DueDate", out value))
DueDate = Conversion<long, System.DateTime>.Convert((long)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 IWorkOrder
public int OrderQty { get; set; }
public int StockedQty { get; set; }
public int ScrappedQty { get; set; }
public System.DateTime StartDate { get; set; }
public System.DateTime? EndDate { get; set; }
public System.DateTime DueDate { get; set; }
public EntityCollection<ScrapReason> ScrapReason { get; private set; }
public EntityCollection<Product> Product { get; private 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 IWorkOrder
public int OrderQty { get { LazyGet(); return InnerData.OrderQty; } set { if (LazySet(Members.OrderQty, InnerData.OrderQty, value)) InnerData.OrderQty = value; } }
public int StockedQty { get { LazyGet(); return InnerData.StockedQty; } set { if (LazySet(Members.StockedQty, InnerData.StockedQty, value)) InnerData.StockedQty = value; } }
public int ScrappedQty { get { LazyGet(); return InnerData.ScrappedQty; } set { if (LazySet(Members.ScrappedQty, InnerData.ScrappedQty, value)) InnerData.ScrappedQty = value; } }
public System.DateTime StartDate { get { LazyGet(); return InnerData.StartDate; } set { if (LazySet(Members.StartDate, InnerData.StartDate, value)) InnerData.StartDate = value; } }
public System.DateTime? EndDate { get { LazyGet(); return InnerData.EndDate; } set { if (LazySet(Members.EndDate, InnerData.EndDate, value)) InnerData.EndDate = value; } }
public System.DateTime DueDate { get { LazyGet(); return InnerData.DueDate; } set { if (LazySet(Members.DueDate, InnerData.DueDate, value)) InnerData.DueDate = value; } }
public ScrapReason ScrapReason
{
get { return ((ILookupHelper<ScrapReason>)InnerData.ScrapReason).GetItem(null); }
set
{
if (LazySet(Members.ScrapReason, ((ILookupHelper<ScrapReason>)InnerData.ScrapReason).GetItem(null), value))
((ILookupHelper<ScrapReason>)InnerData.ScrapReason).SetItem(value, null);
}
}
public Product Product
{
get { return ((ILookupHelper<Product>)InnerData.Product).GetItem(null); }
set
{
if (LazySet(Members.Product, ((ILookupHelper<Product>)InnerData.Product).GetItem(null), value))
((ILookupHelper<Product>)InnerData.Product).SetItem(value, null);
}
}
#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 WorkOrderMembers members = null;
public static WorkOrderMembers Members
{
get
{
if (members == null)
{
lock (typeof(WorkOrder))
{
if (members == null)
members = new WorkOrderMembers();
}
}
return members;
}
}
public class WorkOrderMembers
{
internal WorkOrderMembers() { }
#region Members for interface IWorkOrder
public Property OrderQty { get; } = Datastore.AdventureWorks.Model.Entities["WorkOrder"].Properties["OrderQty"];
public Property StockedQty { get; } = Datastore.AdventureWorks.Model.Entities["WorkOrder"].Properties["StockedQty"];
public Property ScrappedQty { get; } = Datastore.AdventureWorks.Model.Entities["WorkOrder"].Properties["ScrappedQty"];
public Property StartDate { get; } = Datastore.AdventureWorks.Model.Entities["WorkOrder"].Properties["StartDate"];
public Property EndDate { get; } = Datastore.AdventureWorks.Model.Entities["WorkOrder"].Properties["EndDate"];
public Property DueDate { get; } = Datastore.AdventureWorks.Model.Entities["WorkOrder"].Properties["DueDate"];
public Property ScrapReason { get; } = Datastore.AdventureWorks.Model.Entities["WorkOrder"].Properties["ScrapReason"];
public Property Product { get; } = Datastore.AdventureWorks.Model.Entities["WorkOrder"].Properties["Product"];
#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 WorkOrderFullTextMembers fullTextMembers = null;
public static WorkOrderFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(WorkOrder))
{
if (fullTextMembers == null)
fullTextMembers = new WorkOrderFullTextMembers();
}
}
return fullTextMembers;
}
}
public class WorkOrderFullTextMembers
{
internal WorkOrderFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(WorkOrder))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["WorkOrder"];
}
}
return entity;
}
private static WorkOrderEvents events = null;
public static WorkOrderEvents Events
{
get
{
if (events == null)
{
lock (typeof(WorkOrder))
{
if (events == null)
events = new WorkOrderEvents();
}
}
return events;
}
}
public class WorkOrderEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<WorkOrder, EntityEventArgs> onNew;
public event EventHandler<WorkOrder, 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<WorkOrder, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<WorkOrder, EntityEventArgs> onDelete;
public event EventHandler<WorkOrder, 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<WorkOrder, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<WorkOrder, EntityEventArgs> onSave;
public event EventHandler<WorkOrder, 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<WorkOrder, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnOrderQty
private static bool onOrderQtyIsRegistered = false;
private static EventHandler<WorkOrder, PropertyEventArgs> onOrderQty;
public static event EventHandler<WorkOrder, PropertyEventArgs> OnOrderQty
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onOrderQtyIsRegistered)
{
Members.OrderQty.Events.OnChange -= onOrderQtyProxy;
Members.OrderQty.Events.OnChange += onOrderQtyProxy;
onOrderQtyIsRegistered = true;
}
onOrderQty += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onOrderQty -= value;
if (onOrderQty == null && onOrderQtyIsRegistered)
{
Members.OrderQty.Events.OnChange -= onOrderQtyProxy;
onOrderQtyIsRegistered = false;
}
}
}
}
private static void onOrderQtyProxy(object sender, PropertyEventArgs args)
{
EventHandler<WorkOrder, PropertyEventArgs> handler = onOrderQty;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
#region OnStockedQty
private static bool onStockedQtyIsRegistered = false;
private static EventHandler<WorkOrder, PropertyEventArgs> onStockedQty;
public static event EventHandler<WorkOrder, PropertyEventArgs> OnStockedQty
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onStockedQtyIsRegistered)
{
Members.StockedQty.Events.OnChange -= onStockedQtyProxy;
Members.StockedQty.Events.OnChange += onStockedQtyProxy;
onStockedQtyIsRegistered = true;
}
onStockedQty += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onStockedQty -= value;
if (onStockedQty == null && onStockedQtyIsRegistered)
{
Members.StockedQty.Events.OnChange -= onStockedQtyProxy;
onStockedQtyIsRegistered = false;
}
}
}
}
private static void onStockedQtyProxy(object sender, PropertyEventArgs args)
{
EventHandler<WorkOrder, PropertyEventArgs> handler = onStockedQty;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
#region OnScrappedQty
private static bool onScrappedQtyIsRegistered = false;
private static EventHandler<WorkOrder, PropertyEventArgs> onScrappedQty;
public static event EventHandler<WorkOrder, PropertyEventArgs> OnScrappedQty
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onScrappedQtyIsRegistered)
{
Members.ScrappedQty.Events.OnChange -= onScrappedQtyProxy;
Members.ScrappedQty.Events.OnChange += onScrappedQtyProxy;
onScrappedQtyIsRegistered = true;
}
onScrappedQty += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onScrappedQty -= value;
if (onScrappedQty == null && onScrappedQtyIsRegistered)
{
Members.ScrappedQty.Events.OnChange -= onScrappedQtyProxy;
onScrappedQtyIsRegistered = false;
}
}
}
}
private static void onScrappedQtyProxy(object sender, PropertyEventArgs args)
{
EventHandler<WorkOrder, PropertyEventArgs> handler = onScrappedQty;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
#region OnStartDate
private static bool onStartDateIsRegistered = false;
private static EventHandler<WorkOrder, PropertyEventArgs> onStartDate;
public static event EventHandler<WorkOrder, PropertyEventArgs> OnStartDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onStartDateIsRegistered)
{
Members.StartDate.Events.OnChange -= onStartDateProxy;
Members.StartDate.Events.OnChange += onStartDateProxy;
onStartDateIsRegistered = true;
}
onStartDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onStartDate -= value;
if (onStartDate == null && onStartDateIsRegistered)
{
Members.StartDate.Events.OnChange -= onStartDateProxy;
onStartDateIsRegistered = false;
}
}
}
}
private static void onStartDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<WorkOrder, PropertyEventArgs> handler = onStartDate;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
#region OnEndDate
private static bool onEndDateIsRegistered = false;
private static EventHandler<WorkOrder, PropertyEventArgs> onEndDate;
public static event EventHandler<WorkOrder, PropertyEventArgs> OnEndDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onEndDateIsRegistered)
{
Members.EndDate.Events.OnChange -= onEndDateProxy;
Members.EndDate.Events.OnChange += onEndDateProxy;
onEndDateIsRegistered = true;
}
onEndDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onEndDate -= value;
if (onEndDate == null && onEndDateIsRegistered)
{
Members.EndDate.Events.OnChange -= onEndDateProxy;
onEndDateIsRegistered = false;
}
}
}
}
private static void onEndDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<WorkOrder, PropertyEventArgs> handler = onEndDate;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
#region OnDueDate
private static bool onDueDateIsRegistered = false;
private static EventHandler<WorkOrder, PropertyEventArgs> onDueDate;
public static event EventHandler<WorkOrder, PropertyEventArgs> OnDueDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onDueDateIsRegistered)
{
Members.DueDate.Events.OnChange -= onDueDateProxy;
Members.DueDate.Events.OnChange += onDueDateProxy;
onDueDateIsRegistered = true;
}
onDueDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onDueDate -= value;
if (onDueDate == null && onDueDateIsRegistered)
{
Members.DueDate.Events.OnChange -= onDueDateProxy;
onDueDateIsRegistered = false;
}
}
}
}
private static void onDueDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<WorkOrder, PropertyEventArgs> handler = onDueDate;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
#region OnScrapReason
private static bool onScrapReasonIsRegistered = false;
private static EventHandler<WorkOrder, PropertyEventArgs> onScrapReason;
public static event EventHandler<WorkOrder, PropertyEventArgs> OnScrapReason
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onScrapReasonIsRegistered)
{
Members.ScrapReason.Events.OnChange -= onScrapReasonProxy;
Members.ScrapReason.Events.OnChange += onScrapReasonProxy;
onScrapReasonIsRegistered = true;
}
onScrapReason += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onScrapReason -= value;
if (onScrapReason == null && onScrapReasonIsRegistered)
{
Members.ScrapReason.Events.OnChange -= onScrapReasonProxy;
onScrapReasonIsRegistered = false;
}
}
}
}
private static void onScrapReasonProxy(object sender, PropertyEventArgs args)
{
EventHandler<WorkOrder, PropertyEventArgs> handler = onScrapReason;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
#region OnProduct
private static bool onProductIsRegistered = false;
private static EventHandler<WorkOrder, PropertyEventArgs> onProduct;
public static event EventHandler<WorkOrder, PropertyEventArgs> OnProduct
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onProductIsRegistered)
{
Members.Product.Events.OnChange -= onProductProxy;
Members.Product.Events.OnChange += onProductProxy;
onProductIsRegistered = true;
}
onProduct += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onProduct -= value;
if (onProduct == null && onProductIsRegistered)
{
Members.Product.Events.OnChange -= onProductProxy;
onProductIsRegistered = false;
}
}
}
}
private static void onProductProxy(object sender, PropertyEventArgs args)
{
EventHandler<WorkOrder, PropertyEventArgs> handler = onProduct;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<WorkOrder, PropertyEventArgs> onModifiedDate;
public static event EventHandler<WorkOrder, 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<WorkOrder, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<WorkOrder, PropertyEventArgs> onUid;
public static event EventHandler<WorkOrder, 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<WorkOrder, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((WorkOrder)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region IWorkOrderOriginalData
public IWorkOrderOriginalData OriginalVersion { get { return this; } }
#region Members for interface IWorkOrder
int IWorkOrderOriginalData.OrderQty { get { return OriginalData.OrderQty; } }
int IWorkOrderOriginalData.StockedQty { get { return OriginalData.StockedQty; } }
int IWorkOrderOriginalData.ScrappedQty { get { return OriginalData.ScrappedQty; } }
System.DateTime IWorkOrderOriginalData.StartDate { get { return OriginalData.StartDate; } }
System.DateTime? IWorkOrderOriginalData.EndDate { get { return OriginalData.EndDate; } }
System.DateTime IWorkOrderOriginalData.DueDate { get { return OriginalData.DueDate; } }
ScrapReason IWorkOrderOriginalData.ScrapReason { get { return ((ILookupHelper<ScrapReason>)OriginalData.ScrapReason).GetOriginalItem(null); } }
Product IWorkOrderOriginalData.Product { get { return ((ILookupHelper<Product>)OriginalData.Product).GetOriginalItem(null); } }
#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
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
using NDesk.Options;
namespace SteamBot
{
public class Program
{
private static OptionSet opts = new OptionSet()
{
{"bot=", "launch a configured bot given that bots index in the configuration array.",
b => botIndex = Convert.ToInt32(b) } ,
{ "help", "shows this help text", p => showHelp = (p != null) }
};
private static bool showHelp;
private static int botIndex = -1;
private static BotManager manager;
private static bool isclosing = false;
[STAThread]
public static void Main(string[] args)
{
opts.Parse(args);
if (showHelp)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("If no options are given SteamBot defaults to Bot Manager mode.");
opts.WriteOptionDescriptions(Console.Out);
Console.Write("Press Enter to exit...");
Console.ReadLine();
return;
}
if (args.Length == 0)
{
BotManagerMode();
}
else if (botIndex > -1)
{
BotMode(botIndex);
}
}
#region SteamBot Operational Modes
// This mode is to run a single Bot until it's terminated.
private static void BotMode(int botIndex)
{
if (!File.Exists("settings.json"))
{
Console.WriteLine("No settings.json file found.");
return;
}
Configuration configObject;
try
{
configObject = Configuration.LoadConfiguration("settings.json");
}
catch (Newtonsoft.Json.JsonReaderException)
{
// handle basic json formatting screwups
Console.WriteLine("settings.json file is corrupt or improperly formatted.");
return;
}
if (botIndex >= configObject.Bots.Length)
{
Console.WriteLine("Invalid bot index.");
return;
}
Bot b = new Bot(configObject.Bots[botIndex], configObject.ApiKey, BotManager.UserHandlerCreator, true, true);
Console.Title = "Bot Manager";
b.StartBot();
string AuthSet = "auth";
string ExecCommand = "exec";
// this loop is needed to keep the botmode console alive.
// instead of just sleeping, this loop will handle console input
while (true)
{
string inputText = Console.ReadLine();
if (String.IsNullOrEmpty(inputText))
continue;
// Small parse for console input
var c = inputText.Trim();
var cs = c.Split(' ');
if (cs.Length > 1)
{
if (cs[0].Equals(AuthSet, StringComparison.CurrentCultureIgnoreCase))
{
b.AuthCode = cs[1].Trim();
}
else if (cs[0].Equals(ExecCommand, StringComparison.CurrentCultureIgnoreCase))
{
b.HandleBotCommand(c.Remove(0, cs[0].Length + 1));
}
}
}
}
// This mode is to manage child bot processes and take use command line inputs
private static void BotManagerMode()
{
Console.Title = "Bot Manager";
manager = new BotManager();
var loadedOk = manager.LoadConfiguration("settings.json");
if (!loadedOk)
{
Console.WriteLine(
"Configuration file Does not exist or is corrupt. Please rename 'settings-template.json' to 'settings.json' and modify the settings to match your environment");
Console.Write("Press Enter to exit...");
Console.ReadLine();
}
else
{
if (manager.ConfigObject.UseSeparateProcesses)
SetConsoleCtrlHandler(ConsoleCtrlCheck, true);
if (manager.ConfigObject.AutoStartAllBots)
{
var startedOk = manager.StartBots();
if (!startedOk)
{
Console.WriteLine(
"Error starting the bots because either the configuration was bad or because the log file was not opened.");
Console.Write("Press Enter to exit...");
Console.ReadLine();
}
}
else
{
foreach (var botInfo in manager.ConfigObject.Bots)
{
if (botInfo.AutoStart)
{
// auto start this particual bot...
manager.StartBot(botInfo.Username);
}
}
}
Console.WriteLine("Type help for bot manager commands. ");
Console.Write("botmgr > ");
var bmi = new BotManagerInterpreter(manager);
// command interpreter loop.
do
{
string inputText = Console.ReadLine();
if (String.IsNullOrEmpty(inputText))
continue;
bmi.CommandInterpreter(inputText);
Console.Write("botmgr > ");
} while (!isclosing);
}
}
#endregion Bot Modes
private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
// Put your own handler here
switch (ctrlType)
{
case CtrlTypes.CTRL_C_EVENT:
case CtrlTypes.CTRL_BREAK_EVENT:
case CtrlTypes.CTRL_CLOSE_EVENT:
case CtrlTypes.CTRL_LOGOFF_EVENT:
case CtrlTypes.CTRL_SHUTDOWN_EVENT:
if (manager != null)
{
manager.StopBots();
}
isclosing = true;
break;
}
return true;
}
#region Console Control Handler Imports
// Declare the SetConsoleCtrlHandler function
// as external and receiving a delegate.
[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
// A delegate type to be used as the handler routine
// for SetConsoleCtrlHandler.
public delegate bool HandlerRoutine(CtrlTypes CtrlType);
// An enumerated type for the control messages
// sent to the handler routine.
public enum CtrlTypes
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
#endregion
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using ESRI.ArcLogistics.Services;
using ESRI.ArcLogistics.Services.Serialization;
namespace ESRI.ArcLogistics.Routing
{
/// <summary>
/// U-Turn policy enumeration.
/// Indicates how the U-turns at junctions that could occur during network traversal between
/// stops are being handled by the solver.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public enum UTurnPolicy
{
/// <summary>
/// U-turns are prohibited at all junctions. Note, however, that U-turns are still permitted
/// at network locations even when this setting is chosen; however, you can set the
/// individual network locations' CurbApproach property to prohibit U-turns.
/// </summary>
Nowhere = 1,
/// <summary>
/// U-turns are prohibited at all junctions, except those that have only one adjacent edge
/// (a dead end).
/// </summary>
AtDeadEnds = 2,
/// <summary>
/// U-turns are prohibited at junctions where exactly two adjacent edges meet but are
/// permitted at intersections (any junction with three or more adjacent edges) or dead
/// ends (junctions with exactly one adjacent edge).
/// </summary>
AtDeadEndsAndIntersections = 3,
}
/// <summary>
/// Restriction class.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public class Restriction : INotifyPropertyChanged
{
#region constants
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public const string PROP_NAME_IsEnabled = "IsEnabled";
#endregion constants
#region INotifyPropertyChanged members
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public event PropertyChangedEventHandler PropertyChanged;
#endregion INotifyPropertyChanged members
#region constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
internal Restriction(string name, string description, bool editable,
bool enabled)
{
_name = name;
_description = description;
_editable = editable;
_enabled = enabled;
}
#endregion constructors
#region public properties
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public string NetworkAttributeName
{
get { return _name; }
}
public string Description
{
get { return _description; }
}
public bool IsEditable
{
get { return _editable; }
}
public bool IsEnabled
{
get { return _enabled; }
set
{
if (!_editable)
throw new InvalidOperationException(Properties.Messages.Error_RestrictionIsNotEditable);
if (value != _enabled)
{
_enabled = value;
_NotifyPropertyChanged(PROP_NAME_IsEnabled);
}
}
}
#endregion public properties
#region private methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private void _NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
#endregion private methods
#region private fields
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private string _name;
private string _description;
private bool _editable;
private bool _enabled;
#endregion private fields
}
/// <summary>
/// SolverSettings class.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public class SolverSettings
{
#region constants
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private const string LOG_UNKNOWN_RESTRICTION = "Restriction {0} does not exist in network description.";
private const string LOG_INVALID_NETWORK_ATTR = "Invalid network attribute: {0}, {1}";
#endregion constants
#region constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
internal SolverSettings(SolveInfoWrap settings,
NetworkDescription netDesc)
{
Debug.Assert(settings != null);
Debug.Assert(netDesc != null);
_settings = settings;
_netDesc = netDesc;
// Init restrictions.
if (_netDesc != null)
_InitRestrictions(settings, netDesc);
// parameters
_InitAttrParameters(settings);
// Initialize U-Turn and curb approach policies.
_InitUTurnPolicies(settings);
_InitCurbApproachPolicies(settings);
}
#endregion constructors
#region public properties
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public ICollection<Restriction> Restrictions
{
get { return _restrictions.AsReadOnly(); }
}
/// <summary>
/// UTurn at intersections.
/// </summary>
public bool UTurnAtIntersections
{
get
{
return _settings.UTurnAtIntersections;
}
set
{
_settings.UTurnAtIntersections = value;
}
}
/// <summary>
/// UTurn at dead ends.
/// </summary>
public bool UTurnAtDeadEnds
{
get
{
return _settings.UTurnAtDeadEnds;
}
set
{
_settings.UTurnAtDeadEnds = value;
}
}
/// <summary>
/// UTurn at stops.
/// </summary>
public bool UTurnAtStops
{
get
{
return _settings.UTurnAtStops;
}
set
{
_settings.UTurnAtStops = value;
}
}
/// <summary>
/// Stop on order side.
/// </summary>
public bool StopOnOrderSide
{
get
{
return _settings.StopOnOrderSide;
}
set
{
_settings.StopOnOrderSide = value;
}
}
/// <summary>
/// This property allows to override Driving Side rule for cases
/// when you are in running ArcLogistics in country with Left Side driving rules, but
/// generating routes for country with Right Side driving rules.
/// </summary>
public bool? DriveOnRightSideOfTheRoad
{
get
{
return _settings.DriveOnRightSideOfTheRoad;
}
set
{
_settings.DriveOnRightSideOfTheRoad = value;
}
}
public bool UseDynamicPoints
{
get { return _settings.UseDynamicPoints; }
//set { _settings.UseDynamicPoints = value; }
}
public string TWPreference
{
get { return _settings.TWPreference; }
//set { _settings.TWPreference = value; }
}
public bool SaveOutputLayer
{
get { return _settings.SaveOutputLayer; }
//set { _settings.SaveOutputLayer = value; }
}
public bool ExcludeRestrictedStreets
{
get { return _settings.ExcludeRestrictedStreets; }
//set { _settings.ExcludeRestrictedStreets = value; }
}
/// <summary>
/// Arrive and depart delay.
/// </summary>
public int ArriveDepartDelay
{
get { return _settings.ArriveDepartDelay; }
set { _settings.ArriveDepartDelay = value; }
}
#endregion public properties
#region public methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public bool GetNetworkAttributeParameterValue(string attrName,
string paramName,
out object paramValue)
{
Debug.Assert(attrName != null);
Debug.Assert(paramName != null);
paramValue = null;
bool res = false;
// find parameter in network description
NetworkAttributeParameter param = null;
if (_FindParamInNetworkDesc(attrName, paramName, out param))
{
// try to get value from attribute settings
RouteAttrInfo attrInfo = _settings.GetAttrParameter(attrName, paramName);
if (attrInfo != null)
{
if (_DeserializeParamValue(attrInfo.Value, param.Type, out paramValue))
res = true;
}
else
{
// get default value from network description
paramValue = param.DefaultValue;
res = true;
}
}
return res;
}
public void SetNetworkAttributeParameterValue(string attrName,
string paramName,
object paramValue)
{
Debug.Assert(attrName != null);
Debug.Assert(paramName != null);
// find parameter in network description
NetworkAttributeParameter param = null;
if (!_FindParamInNetworkDesc(attrName, paramName, out param))
{
// cannot find attribute
throw new ArgumentException(
Properties.Messages.Error_InvalidNetworkAttr);
}
string serializedValue = String.Empty;
if (paramValue != null)
{
// If new value is not empty string or if parameter doesnt accept empty string -
// try to serialize current value.
if (paramValue as string != string.Empty || !param.IsEmptyStringValid)
{
object convertedValue = paramValue;
// check if value type is correct
if (!param.Type.Equals(paramValue.GetType()))
{
if (!_ConvertParamValue(paramValue, param.Type, out convertedValue))
{
// provided value cannot be converted to required type
throw new ArgumentException(
Properties.Messages.Error_InvalidNetworkParamType);
}
}
// serialize value for storing
serializedValue = _SerializeParamValue(convertedValue);
}
}
// try to find attribute in settings
RouteAttrInfo attrInfo = _settings.GetUserAttrParameter(attrName, paramName);
if (attrInfo != null)
{
// update existing attribute entry
attrInfo.Value = serializedValue;
}
else
{
// add new attribute entry
attrInfo = new RouteAttrInfo();
attrInfo.AttrName = attrName;
attrInfo.ParamName = paramName;
attrInfo.Value = serializedValue;
_settings.AddAttrParameter(attrInfo);
}
}
/// <summary>
/// Method gets U-Turn policy for orders according to settings.
/// </summary>
/// <returns>U-Turn policy.</returns>
public UTurnPolicy GetUTurnPolicy()
{
UTurnPolicy policy = new UTurnPolicy();
if (UTurnAtDeadEnds && UTurnAtIntersections)
{
policy = UTurnPolicy.AtDeadEndsAndIntersections;
}
else if (!UTurnAtDeadEnds && !UTurnAtIntersections)
{
policy = UTurnPolicy.Nowhere;
}
else if (UTurnAtDeadEnds && !UTurnAtIntersections)
{
policy = UTurnPolicy.AtDeadEnds;
}
else
{
// Not supported. Set default one.
policy = UTurnPolicy.Nowhere;
}
return policy;
}
/// <summary>
/// Method gets Curb Approach for orders according to settings.
/// </summary>
/// <returns>Curb approach.</returns>
public CurbApproach GetOrderCurbApproach()
{
CurbApproach policy = new CurbApproach();
if (UTurnAtStops && StopOnOrderSide)
{
policy = CurbApproach.Both;
}
else if (!UTurnAtStops && !StopOnOrderSide)
{
policy = CurbApproach.NoUTurns;
}
else if (!UTurnAtStops && StopOnOrderSide)
{
// Set Left side or Right side Curb Approach
// depending on override setting or Country locale.
policy = _GetLeftOrRightSideCurbApproach();
}
else
{
// Not supported. Set default one.
policy = CurbApproach.Both;
}
return policy;
}
/// <summary>
/// Method gets Curb Approach for depots according to settings.
/// Depots doesn't support NoUTurns option as Orders.
/// </summary>
/// <returns>Curb approach.</returns>
public CurbApproach GetDepotCurbApproach()
{
CurbApproach policy = new CurbApproach();
if (UTurnAtStops && StopOnOrderSide)
{
policy = CurbApproach.Both;
}
else if (UTurnAtStops && !StopOnOrderSide)
{
policy = CurbApproach.Both;
}
else
{
// Set Left side or Right side Curb Approach
// depending on override setting or Country locale.
policy = _GetLeftOrRightSideCurbApproach();
}
return policy;
}
#endregion public methods
#region private methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private void _InitRestrictions(SolveInfoWrap settings,
NetworkDescription netDesc)
{
Debug.Assert(settings != null);
Debug.Assert(netDesc != null);
Dictionary<string, Restriction> restrictions = new Dictionary<
string, Restriction>();
// add all available restrictions with default data
foreach (NetworkAttribute attr in netDesc.NetworkAttributes)
{
if (attr.UsageType == NetworkAttributeUsageType.Restriction &&
!String.IsNullOrEmpty(attr.Name))
{
restrictions.Add(attr.Name.ToLower(), new Restriction(
attr.Name,
String.Empty, // description
true, // editable is true by default
_IsRestrictionEnabled(attr.Name,
netDesc.EnabledRestrictionNames)));
}
}
// override restrictions according to settings
foreach (string name in settings.RestrictionNames)
{
RestrictionInfo ri = settings.GetRestriction(name);
if (ri != null)
{
string key = name.ToLower();
Restriction rest = null;
if (restrictions.TryGetValue(key, out rest))
{
// override restriction
restrictions[key] = new Restriction(
rest.NetworkAttributeName, // NOTE: use name from server
ri.Description,
ri.IsEditable,
ri.IsTurnedOn);
}
else
Logger.Warning(String.Format(LOG_UNKNOWN_RESTRICTION, name));
}
}
// attach to events
foreach (Restriction rest in restrictions.Values)
rest.PropertyChanged += new PropertyChangedEventHandler(Restriction_PropertyChanged);
_restrictions.AddRange(restrictions.Values);
}
private void Restriction_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
Restriction rest = sender as Restriction;
Debug.Assert(rest != null);
RestrictionInfo info = _settings.GetUserRestriction(
rest.NetworkAttributeName);
if (info != null)
{
// currently only Enabled property can be modified
info.IsTurnedOn = rest.IsEnabled;
}
else
{
// add new restriction entry to config
info = new RestrictionInfo();
info.Name = rest.NetworkAttributeName;
info.Description = rest.Description;
info.IsEditable = rest.IsEditable;
info.IsTurnedOn = rest.IsEnabled;
_settings.AddRestriction(info);
}
}
private void _InitAttrParameters(SolveInfoWrap settings)
{
Debug.Assert(settings != null);
foreach (RouteAttrInfo attr in settings.AttrParameters)
{
bool isValid = false;
// check if attribute settings are valid
if (!String.IsNullOrEmpty(attr.AttrName) &&
!String.IsNullOrEmpty(attr.ParamName) &&
attr.Value != null)
{
// find parameter in network description
NetworkAttributeParameter param = null;
if (_FindParamInNetworkDesc(attr.AttrName, attr.ParamName, out param))
{
// check if parameter value is valid
if (_IsParamValueValid(attr.Value, param.Type))
isValid = true;
}
}
if (!isValid)
{
Logger.Warning(String.Format(LOG_INVALID_NETWORK_ATTR,
attr.AttrName,
attr.ParamName));
}
}
}
/// <summary>
/// Method provides initialization of U-Turn policies.
/// </summary>
/// <param name="settings">Settings.</param>
private void _InitUTurnPolicies(SolveInfoWrap settings)
{
// Validate settings for U-Turn policies.
if (settings.UTurnAtIntersections)
{
settings.UTurnAtDeadEnds = true;
}
}
/// <summary>
/// Method provides initialization of Curb approach policies.
/// </summary>
/// <param name="settings">Settings.</param>
private void _InitCurbApproachPolicies(SolveInfoWrap settings)
{
// Validate settings for Curb Approach policies.
if (settings.UTurnAtStops)
{
settings.StopOnOrderSide = true;
}
}
private bool _FindParamInNetworkDesc(string attrName, string paramName,
out NetworkAttributeParameter attrParameter)
{
Debug.Assert(attrName != null);
Debug.Assert(paramName != null);
attrParameter = null;
bool found = false;
foreach (NetworkAttribute attr in _netDesc.NetworkAttributes)
{
if (attr.Name.Equals(attrName, StringComparison.InvariantCultureIgnoreCase))
{
foreach (NetworkAttributeParameter param in attr.Parameters)
{
if (param.Name.Equals(paramName, StringComparison.InvariantCultureIgnoreCase))
{
attrParameter = param;
found = true;
break;
}
}
if (found)
break;
}
}
return found;
}
private static bool _IsParamValueValid(string value, Type type)
{
object obj;
return _DeserializeParamValue(value, type, out obj);
}
private static bool _IsRestrictionEnabled(string restrictionName,
string[] enabledRestrictionNames)
{
Debug.Assert(restrictionName != null);
Debug.Assert(enabledRestrictionNames != null);
bool enabled = false;
foreach (string name in enabledRestrictionNames)
{
if (name.Equals(restrictionName,
StringComparison.InvariantCultureIgnoreCase))
{
enabled = true;
break;
}
}
return enabled;
}
private static bool _ConvertParamValue(object value, Type conversionType,
out object convertedValue)
{
Debug.Assert(value != null);
Debug.Assert(conversionType != null);
convertedValue = null;
bool res = false;
try
{
// try to convert value to required type
convertedValue = Convert.ChangeType(value, conversionType,
fmtProvider);
res = true;
}
catch { }
return res;
}
private static bool _DeserializeParamValue(string valueStr, Type type,
out object valueObj)
{
Debug.Assert(type != null);
bool res = false;
if (String.IsNullOrEmpty(valueStr))
{
if (type == typeof(string))
valueObj = valueStr;
else
valueObj = null;
res = true;
}
else
res = _ConvertParamValue(valueStr, type, out valueObj);
return res;
}
private static string _SerializeParamValue(object value)
{
Debug.Assert(value != null);
return Convert.ToString(value, fmtProvider);
}
/// <summary>
/// Method set Left side or Right side Curb Approach
/// depending on override setting or Country locale.
/// </summary>
/// <returns>Left or Right Side Curb Approach.</returns>
private CurbApproach _GetLeftOrRightSideCurbApproach()
{
CurbApproach policy = CurbApproach.Right;
if (DriveOnRightSideOfTheRoad == null)
{
// No need to override settings,
// determine curb approach automatically.
if (_IsRuleToDriveOnRightSideOfTheRoad())
policy = CurbApproach.Right;
else
policy = CurbApproach.Left;
}
else if (DriveOnRightSideOfTheRoad == true)
{
policy = CurbApproach.Right;
}
else if (DriveOnRightSideOfTheRoad == false)
{
policy = CurbApproach.Left;
}
else
{
Debug.Assert(false);
}
return policy;
}
/// <summary>
/// Method determines if current region country has right side
/// driving rules or left side.
/// </summary>
/// <returns>True - if right side driving, otherwise False.</returns>
private bool _IsRuleToDriveOnRightSideOfTheRoad()
{
int majorVersion = System.Environment.OSVersion.Version.Major;
int minorVersion = System.Environment.OSVersion.Version.Minor;
bool result = true;
// Only for WindowsXP or later...
if ((majorVersion == WINDOWS_XP_MAJOR_VERSION &&
minorVersion >= WINDOWS_XP_MINOR_VERSION) ||
(majorVersion > WINDOWS_XP_MAJOR_VERSION))
{
// Get current Geo Id from region information.
RegionInfo ri = new RegionInfo(
System.Globalization.RegionInfo.CurrentRegion.TwoLetterISORegionName);
int geoId = ri.GeoId;
switch (geoId)
{
// Check countries which have left side driving rules.
case 0xA: // American Samoa
case 0x12C: // Anguilla
case 0x2: // Antigua and Barbuda
case 0xC: // Australia
case 0x16: // Bahamas, The
case 0x17: // Bangladesh
case 0x12: // Barbados
case 0x14: // Bermuda
case 0x22: // Bhutan
case 0x13: // Botswana
case 0x25: // Brunei
case 0x133: // Cayman Islands
case 0x135: // Christmas Island
case 0x137: // Cocos (Keeling) Islands
case 0x138: // Cook Islands
case 0x3B: // Cyprus
case 0x3F: // Dominica
case 0x6F60E7: // Timor-Leste
case 0x13B: // Falkland Islands (Islas Malvinas)
case 0x4E: // Fiji Islands
case 0x5B: // Grenada
case 0x144: // Guernsey
case 0x65: // Guyana
case 0x68: // Hong Kong S.A.R.
case 0x71: // India
case 0x6F: // Indonesia
case 0x44: // Ireland
case 0x3B16: // Isle of Man
case 0x7C: // Jamaica
case 0x7A: // Japan
case 0x148: // Jersey
case 0x81: // Kenya
case 0x85: // Kiribati
case 0x92: // Lesotho
case 0x97: // Macao S.A.R.
case 0x9C: // Malawi
case 0xA7: // Malaysia
case 0xA5: // Maldives
case 0xA3: // Malta
case 0xA0: // Mauritius
case 0x14C: // Montserrat
case 0xA8: // Mozambique
case 0xFE: // Namibia
case 0xB4: // Nauru
case 0xB2: // Nepal
case 0xB7: // New Zealand
case 0x14F: // Niue
case 0x150: // Norfolk Island
case 0xBE: // Pakistan
case 0xC2: // Papua New Guinea
case 0x153: // Pitcairn Islands
case 0x157: // St. Helena
case 0xCF: // St. Kitts and Nevis
case 0xDA: // St. Lucia
case 0xF8: // St. Vincent and the Grenadines
case 0xD0: // Seychelles
case 0xD7: // Singapore
case 0x1E: // Solomon Islands
case 0xD1: // South Africa
case 0x2A: // Sri Lanka
case 0xB5: // Suriname
case 0x104: // Swaziland
case 0xEF: // Tanzania
case 0xE3: // Thailand
case 0x15B: // Tokelau
case 0xE7: // Tonga
case 0xE1: // Trinidad and Tobago
case 0x15D: // Turks and Caicos Islands
case 0xEC: // Tuvalu
case 0xF0: // Uganda
case 0xF2: // United Kingdom
case 0x15F: // Virgin Islands, British
case 0xFC: // Virgin Islands
case 0x107: // Zambia
case 0x108: // Zimbabwe
{
result = false;
}
break;
default:
// All other countries have
// right side driving rules.
result = true;
break;
}
}
else
{
// Can't determine region information
// for Windows before Windows XP.
return result;
}
return result;
}
#endregion private methods
#region private constants
/// <summary>
/// Windows XP major version. It is used to determine if
/// we can get Region Information.
/// </summary>
private const int WINDOWS_XP_MAJOR_VERSION = 5;
/// <summary>
/// Windows XP minor version. It is used to determine if
/// we can get Region Information.
/// </summary>
private const int WINDOWS_XP_MINOR_VERSION = 1;
#endregion
#region private fields
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
// locale for conversions
private static readonly CultureInfo fmtProvider = new CultureInfo("en-US");
private List<Restriction> _restrictions = new List<Restriction>();
private SolveInfoWrap _settings;
private NetworkDescription _netDesc;
#endregion private fields
}
}
| |
// Copyright 2014 The Rector & Visitors of the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Newtonsoft.Json;
using Sensus.Shared.Exceptions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace Sensus.Shared.DataStores.Local
{
public class FileLocalDataStore : LocalDataStore
{
private const double REMOTE_COMMIT_TRIGGER_STORAGE_DIRECTORY_SIZE_MB = 10;
private const double MAX_FILE_SIZE_MB = 1;
private string _path;
private readonly object _storageDirectoryLocker = new object();
[JsonIgnore]
public string StorageDirectory
{
get
{
string directory = Path.Combine(Protocol.StorageDirectory, GetType().FullName);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
return directory;
}
}
[JsonIgnore]
public override string DisplayName
{
get { return "File"; }
}
[JsonIgnore]
public override bool Clearable
{
get { return true; }
}
[JsonIgnore]
public override string SizeDescription
{
get
{
string desc = null;
try
{
desc = Math.Round(SensusServiceHelper.GetDirectorySizeMB(StorageDirectory), 1) + " MB";
}
catch (Exception)
{
}
return desc;
}
}
public override void Start()
{
// file needs to be ready to accept data immediately, so set file path before calling base.Start
WriteToNewPath();
base.Start();
}
public override Task<List<Datum>> CommitAsync(IEnumerable<Datum> data, CancellationToken cancellationToken)
{
return Task.Run(() =>
{
List<Datum> committedData = new List<Datum>();
lock (_storageDirectoryLocker)
{
try
{
using (StreamWriter file = new StreamWriter(_path, true))
{
foreach (Datum datum in data)
{
if (cancellationToken.IsCancellationRequested)
break;
// get JSON for datum
string datumJSON = null;
try
{
datumJSON = datum.GetJSON(Protocol.JsonAnonymizer, false);
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Failed to get JSON for datum: " + ex.Message, LoggingLevel.Normal, GetType());
}
// write JSON to file
if (datumJSON != null)
{
try
{
file.WriteLine(datumJSON);
MostRecentSuccessfulCommitTime = DateTime.Now;
committedData.Add(datum);
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Failed to write datum JSON to local file: " + ex.Message, LoggingLevel.Normal, GetType());
// something went wrong with file write...switch to a new file in the hope that it will work better
try
{
WriteToNewPath();
SensusServiceHelper.Get().Logger.Log("Initialized new local file.", LoggingLevel.Normal, GetType());
}
catch (Exception ex2)
{
SensusServiceHelper.Get().Logger.Log("Failed to initialize new file after failing to write the old one: " + ex2.Message, LoggingLevel.Normal, GetType());
}
}
}
}
}
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Failed to write data: " + ex.Message, LoggingLevel.Normal, GetType());
// something went wrong with file write...switch to a new file in the hope that it will work better
try
{
WriteToNewPath();
SensusServiceHelper.Get().Logger.Log("Initialized new local file.", LoggingLevel.Normal, GetType());
}
catch (Exception ex2)
{
SensusServiceHelper.Get().Logger.Log("Failed to initialize new file after failing to write the old one: " + ex2.Message, LoggingLevel.Normal, GetType());
}
}
// switch to a new path if the current one has grown too large
if (SensusServiceHelper.GetFileSizeMB(_path) >= MAX_FILE_SIZE_MB)
WriteToNewPath();
}
CheckSizeAndCommitToRemote(cancellationToken);
return committedData;
});
}
public override void CommitDataToRemoteDataStore(CancellationToken cancellationToken)
{
lock (_storageDirectoryLocker)
{
string[] pathsToCommit = Directory.GetFiles(StorageDirectory);
// get path for uncommitted data
WriteToNewPath();
string uncommittedDataPath = _path;
// reset _path for standard commits
WriteToNewPath();
using (StreamWriter uncommittedDataFile = new StreamWriter(uncommittedDataPath))
{
foreach (string path in pathsToCommit)
{
if (cancellationToken.IsCancellationRequested)
break;
// wrap in try-catch to ensure that we process all files
try
{
using (StreamReader file = new StreamReader(path))
{
// commit data in small batches. all data will end up in the uncommitted file, in the batch object, or
// in the remote data store.
HashSet<Datum> batch = new HashSet<Datum>();
string datumJSON;
while ((datumJSON = file.ReadLine()) != null)
{
// if we have been canceled, dump the rest of the file into the uncommitted data file.
if (cancellationToken.IsCancellationRequested)
uncommittedDataFile.WriteLine(datumJSON);
else
{
// wrap in try-catch to ensure that we process all lines
try
{
batch.Add(Datum.FromJSON(datumJSON));
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Failed to add datum to batch from JSON: " + ex.Message, LoggingLevel.Normal, GetType());
}
if (batch.Count >= 50000)
CommitBatchToRemote(batch, cancellationToken, uncommittedDataFile);
}
}
// deal with any data that remain in an the batch object. they'll end up in the uncommitted file or
// in the remote data store. if the former, they'll be picked up next commit.
if (batch.Count > 0)
{
if (cancellationToken.IsCancellationRequested)
{
foreach (Datum datum in batch)
uncommittedDataFile.WriteLine(datum.GetJSON(Protocol.JsonAnonymizer, false));
}
else
CommitBatchToRemote(batch, cancellationToken, uncommittedDataFile);
}
}
// we've read all lines in the file and either committed them to the remote data store or written them
// to the uncommitted data file.
File.Delete(path);
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Failed to commit: " + ex.Message, LoggingLevel.Normal, GetType());
}
}
}
}
}
private void CommitBatchToRemote(HashSet<Datum> batch, CancellationToken cancellationToken, StreamWriter uncommittedDataFile)
{
CommitChunksAsync(batch, Protocol.RemoteDataStore, cancellationToken).Wait();
// any leftover data should be dumped to the uncommitted file to maintain memory limits. the data will be committed next time.
foreach (Datum datum in batch)
uncommittedDataFile.WriteLine(datum.GetJSON(Protocol.JsonAnonymizer, false));
// all data were either commmitted or dumped to the uncommitted file. clear the batch.
batch.Clear();
}
protected override bool TriggerRemoteCommit()
{
lock (_storageDirectoryLocker)
{
return SensusServiceHelper.GetDirectorySizeMB(StorageDirectory) >= REMOTE_COMMIT_TRIGGER_STORAGE_DIRECTORY_SIZE_MB;
}
}
protected override IEnumerable<Tuple<string, string>> GetDataLinesToWrite(CancellationToken cancellationToken, Action<string, double> progressCallback)
{
lock (_storageDirectoryLocker)
{
// "$type":"SensusService.Probes.Movement.AccelerometerDatum, SensusiOS"
Regex datumTypeRegex = new Regex(@"""\$type""\s*:\s*""(?<type>[^,]+),");
double storageDirectoryMbToRead = SensusServiceHelper.GetDirectorySizeMB(StorageDirectory);
double storageDirectoryMbRead = 0;
string[] localPaths = Directory.GetFiles(StorageDirectory);
for (int localPathNum = 0; localPathNum < localPaths.Length; ++localPathNum)
{
string localPath = localPaths[localPathNum];
using (StreamReader localFile = new StreamReader(localPath))
{
long localFilePosition = 0;
string line;
while ((line = localFile.ReadLine()) != null)
{
cancellationToken.ThrowIfCancellationRequested();
string type = datumTypeRegex.Match(line).Groups["type"].Value;
type = type.Substring(type.LastIndexOf('.') + 1);
yield return new Tuple<string, string>(type, line);
if (localFile.BaseStream.Position > localFilePosition)
{
int oldMbRead = (int)storageDirectoryMbRead;
storageDirectoryMbRead += (localFile.BaseStream.Position - localFilePosition) / (1024d * 1024d);
int newMbRead = (int)storageDirectoryMbRead;
if (newMbRead > oldMbRead && progressCallback != null && storageDirectoryMbToRead > 0)
progressCallback(null, storageDirectoryMbRead / storageDirectoryMbToRead);
localFilePosition = localFile.BaseStream.Position;
}
}
}
}
if (progressCallback != null)
progressCallback(null, 1);
}
}
private void WriteToNewPath()
{
lock (_storageDirectoryLocker)
{
_path = null;
int pathNumber = 0;
while (pathNumber++ < int.MaxValue && _path == null)
{
try
{
_path = Path.Combine(StorageDirectory, pathNumber.ToString());
}
catch (Exception ex)
{
throw new SensusException("Failed to get path to local file: " + ex.Message, ex);
}
// create an empty file at the path if one does not exist
if (File.Exists(_path))
_path = null;
else
File.Create(_path).Dispose();
}
if (_path == null)
throw new SensusException("Failed to find new path.");
}
}
public override void Clear()
{
base.Clear();
lock (_storageDirectoryLocker)
{
if (Protocol != null)
{
foreach (string path in Directory.GetFiles(StorageDirectory))
{
try
{
File.Delete(path);
}
catch (Exception ex)
{
SensusServiceHelper.Get().Logger.Log("Failed to delete local file \"" + path + "\": " + ex.Message, LoggingLevel.Normal, GetType());
}
}
}
}
}
public override void Reset()
{
base.Reset();
_path = null;
}
public override bool TestHealth(ref string error, ref string warning, ref string misc)
{
bool restart = base.TestHealth(ref error, ref warning, ref misc);
lock(_storageDirectoryLocker)
{
int fileCount = Directory.GetFiles(StorageDirectory).Length;
string name = GetType().Name;
misc += "Number of files (" + name + "): " + fileCount + Environment.NewLine +
"Average file size (MB) (" + name + "): " + Math.Round(SensusServiceHelper.GetDirectorySizeMB(StorageDirectory) / (float)fileCount, 2) + Environment.NewLine;
}
return restart;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public class HttpClient : HttpMessageInvoker
{
#region Fields
private static IWebProxy s_defaultProxy;
private static readonly TimeSpan s_defaultTimeout = TimeSpan.FromSeconds(100);
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private static readonly TimeSpan s_infiniteTimeout = Threading.Timeout.InfiniteTimeSpan;
private const HttpCompletionOption defaultCompletionOption = HttpCompletionOption.ResponseContentRead;
private volatile bool _operationStarted;
private volatile bool _disposed;
private CancellationTokenSource _pendingRequestsCts;
private HttpRequestHeaders _defaultRequestHeaders;
private Version _defaultRequestVersion = HttpUtilities.DefaultRequestVersion;
private Uri _baseAddress;
private TimeSpan _timeout;
private int _maxResponseContentBufferSize;
#endregion Fields
#region Properties
public static IWebProxy DefaultProxy
{
get => LazyInitializer.EnsureInitialized(ref s_defaultProxy, () => SystemProxyInfo.Proxy);
set
{
s_defaultProxy = value ?? throw new ArgumentNullException(nameof(value));
}
}
public HttpRequestHeaders DefaultRequestHeaders
{
get
{
if (_defaultRequestHeaders == null)
{
_defaultRequestHeaders = new HttpRequestHeaders();
}
return _defaultRequestHeaders;
}
}
public Version DefaultRequestVersion
{
get => _defaultRequestVersion;
set
{
CheckDisposedOrStarted();
_defaultRequestVersion = value ?? throw new ArgumentNullException(nameof(value));
}
}
public Uri BaseAddress
{
get { return _baseAddress; }
set
{
CheckBaseAddress(value, nameof(value));
CheckDisposedOrStarted();
if (NetEventSource.IsEnabled) NetEventSource.UriBaseAddress(this, value);
_baseAddress = value;
}
}
public TimeSpan Timeout
{
get { return _timeout; }
set
{
if (value != s_infiniteTimeout && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_timeout = value;
}
}
public long MaxResponseContentBufferSize
{
get { return _maxResponseContentBufferSize; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (value > HttpContent.MaxBufferSize)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
SR.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
}
CheckDisposedOrStarted();
Debug.Assert(HttpContent.MaxBufferSize <= int.MaxValue);
_maxResponseContentBufferSize = (int)value;
}
}
#endregion Properties
#region Constructors
public HttpClient()
: this(new HttpClientHandler())
{
}
public HttpClient(HttpMessageHandler handler)
: this(handler, true)
{
}
public HttpClient(HttpMessageHandler handler, bool disposeHandler)
: base(handler, disposeHandler)
{
_timeout = s_defaultTimeout;
_maxResponseContentBufferSize = HttpContent.MaxBufferSize;
_pendingRequestsCts = new CancellationTokenSource();
}
#endregion Constructors
#region Public Send
#region Simple Get Overloads
public Task<string> GetStringAsync(string requestUri) =>
GetStringAsync(CreateUri(requestUri));
public Task<string> GetStringAsync(Uri requestUri) =>
GetStringAsyncCore(GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead));
private async Task<string> GetStringAsyncCore(Task<HttpResponseMessage> getTask)
{
// Wait for the response message.
using (HttpResponseMessage responseMessage = await getTask.ConfigureAwait(false))
{
// Make sure it completed successfully.
responseMessage.EnsureSuccessStatusCode();
// Get the response content.
HttpContent c = responseMessage.Content;
if (c != null)
{
#if NET46
return await c.ReadAsStringAsync().ConfigureAwait(false);
#else
HttpContentHeaders headers = c.Headers;
// Since the underlying byte[] will never be exposed, we use an ArrayPool-backed
// stream to which we copy all of the data from the response.
using (Stream responseStream = c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false))
using (var buffer = new HttpContent.LimitArrayPoolWriteStream(_maxResponseContentBufferSize, (int)headers.ContentLength.GetValueOrDefault()))
{
try
{
await responseStream.CopyToAsync(buffer).ConfigureAwait(false);
}
catch (Exception e) when (HttpContent.StreamCopyExceptionNeedsWrapping(e))
{
throw HttpContent.WrapStreamCopyException(e);
}
if (buffer.Length > 0)
{
// Decode and return the data from the buffer.
return HttpContent.ReadBufferAsString(buffer.GetBuffer(), headers);
}
}
#endif
}
// No content to return.
return string.Empty;
}
}
public Task<byte[]> GetByteArrayAsync(string requestUri) =>
GetByteArrayAsync(CreateUri(requestUri));
public Task<byte[]> GetByteArrayAsync(Uri requestUri) =>
GetByteArrayAsyncCore(GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead));
private async Task<byte[]> GetByteArrayAsyncCore(Task<HttpResponseMessage> getTask)
{
// Wait for the response message.
using (HttpResponseMessage responseMessage = await getTask.ConfigureAwait(false))
{
// Make sure it completed successfully.
responseMessage.EnsureSuccessStatusCode();
// Get the response content.
HttpContent c = responseMessage.Content;
if (c != null)
{
#if NET46
return await c.ReadAsByteArrayAsync().ConfigureAwait(false);
#else
HttpContentHeaders headers = c.Headers;
using (Stream responseStream = c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false))
{
long? contentLength = headers.ContentLength;
Stream buffer; // declared here to share the state machine field across both if/else branches
if (contentLength.HasValue)
{
// If we got a content length, then we assume that it's correct and create a MemoryStream
// to which the content will be transferred. That way, assuming we actually get the exact
// amount we were expecting, we can simply return the MemoryStream's underlying buffer.
buffer = new HttpContent.LimitMemoryStream(_maxResponseContentBufferSize, (int)contentLength.GetValueOrDefault());
try
{
await responseStream.CopyToAsync(buffer).ConfigureAwait(false);
}
catch (Exception e) when (HttpContent.StreamCopyExceptionNeedsWrapping(e))
{
throw HttpContent.WrapStreamCopyException(e);
}
if (buffer.Length > 0)
{
return ((HttpContent.LimitMemoryStream)buffer).GetSizedBuffer();
}
}
else
{
// If we didn't get a content length, then we assume we're going to have to grow
// the buffer potentially several times and that it's unlikely the underlying buffer
// at the end will be the exact size needed, in which case it's more beneficial to use
// ArrayPool buffers and copy out to a new array at the end.
buffer = new HttpContent.LimitArrayPoolWriteStream(_maxResponseContentBufferSize);
try
{
try
{
await responseStream.CopyToAsync(buffer).ConfigureAwait(false);
}
catch (Exception e) when (HttpContent.StreamCopyExceptionNeedsWrapping(e))
{
throw HttpContent.WrapStreamCopyException(e);
}
if (buffer.Length > 0)
{
return ((HttpContent.LimitArrayPoolWriteStream)buffer).ToArray();
}
}
finally { buffer.Dispose(); }
}
}
#endif
}
// No content to return.
return Array.Empty<byte>();
}
}
// Unbuffered by default
public Task<Stream> GetStreamAsync(string requestUri)
{
return GetStreamAsync(CreateUri(requestUri));
}
// Unbuffered by default
public Task<Stream> GetStreamAsync(Uri requestUri)
{
return FinishGetStreamAsync(GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead));
}
private async Task<Stream> FinishGetStreamAsync(Task<HttpResponseMessage> getTask)
{
HttpResponseMessage response = await getTask.ConfigureAwait(false);
response.EnsureSuccessStatusCode();
HttpContent c = response.Content;
return c != null ?
(c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false)) :
Stream.Null;
}
#endregion Simple Get Overloads
#region REST Send Overloads
public Task<HttpResponseMessage> GetAsync(string requestUri)
{
return GetAsync(CreateUri(requestUri));
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri)
{
return GetAsync(requestUri, defaultCompletionOption);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption)
{
return GetAsync(CreateUri(requestUri), completionOption);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption)
{
return GetAsync(requestUri, completionOption, CancellationToken.None);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken)
{
return GetAsync(CreateUri(requestUri), cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, CancellationToken cancellationToken)
{
return GetAsync(requestUri, defaultCompletionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
return GetAsync(CreateUri(requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
return SendAsync(CreateRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
{
return PostAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content)
{
return PostAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PostAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content)
{
return PutAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content)
{
return PutAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PutAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = CreateRequestMessage(HttpMethod.Put, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> PatchAsync(string requestUri, HttpContent content)
{
return PatchAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PatchAsync(Uri requestUri, HttpContent content)
{
return PatchAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PatchAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PatchAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PatchAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = CreateRequestMessage(HttpMethod.Patch, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri)
{
return DeleteAsync(CreateUri(requestUri));
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri)
{
return DeleteAsync(requestUri, CancellationToken.None);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri, CancellationToken cancellationToken)
{
return DeleteAsync(CreateUri(requestUri), cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri, CancellationToken cancellationToken)
{
return SendAsync(CreateRequestMessage(HttpMethod.Delete, requestUri), cancellationToken);
}
#endregion REST Send Overloads
#region Advanced Send Overloads
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
{
return SendAsync(request, defaultCompletionOption, CancellationToken.None);
}
public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
return SendAsync(request, defaultCompletionOption, cancellationToken);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption)
{
return SendAsync(request, completionOption, CancellationToken.None);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
CheckDisposed();
CheckRequestMessage(request);
SetOperationStarted();
PrepareRequestMessage(request);
// PrepareRequestMessage will resolve the request address against the base address.
// We need a CancellationTokenSource to use with the request. We always have the global
// _pendingRequestsCts to use, plus we may have a token provided by the caller, and we may
// have a timeout. If we have a timeout or a caller-provided token, we need to create a new
// CTS (we can't, for example, timeout the pending requests CTS, as that could cancel other
// unrelated operations). Otherwise, we can use the pending requests CTS directly.
CancellationTokenSource cts;
bool disposeCts;
bool hasTimeout = _timeout != s_infiniteTimeout;
if (hasTimeout || cancellationToken.CanBeCanceled)
{
disposeCts = true;
cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _pendingRequestsCts.Token);
if (hasTimeout)
{
cts.CancelAfter(_timeout);
}
}
else
{
disposeCts = false;
cts = _pendingRequestsCts;
}
// Initiate the send.
Task<HttpResponseMessage> sendTask;
try
{
sendTask = base.SendAsync(request, cts.Token);
}
catch
{
HandleFinishSendAsyncCleanup(cts, disposeCts);
throw;
}
return completionOption == HttpCompletionOption.ResponseContentRead && !string.Equals(request.Method.Method, "HEAD", StringComparison.OrdinalIgnoreCase) ?
FinishSendAsyncBuffered(sendTask, request, cts, disposeCts) :
FinishSendAsyncUnbuffered(sendTask, request, cts, disposeCts);
}
private async Task<HttpResponseMessage> FinishSendAsyncBuffered(
Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts)
{
HttpResponseMessage response = null;
try
{
// Wait for the send request to complete, getting back the response.
response = await sendTask.ConfigureAwait(false);
if (response == null)
{
throw new InvalidOperationException(SR.net_http_handler_noresponse);
}
// Buffer the response content if we've been asked to and we have a Content to buffer.
if (response.Content != null)
{
await response.Content.LoadIntoBufferAsync(_maxResponseContentBufferSize, cts.Token).ConfigureAwait(false);
}
if (NetEventSource.IsEnabled) NetEventSource.ClientSendCompleted(this, response, request);
return response;
}
catch (Exception e)
{
response?.Dispose();
HandleFinishSendAsyncError(e, cts);
throw;
}
finally
{
HandleFinishSendAsyncCleanup(cts, disposeCts);
}
}
private async Task<HttpResponseMessage> FinishSendAsyncUnbuffered(
Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts)
{
try
{
HttpResponseMessage response = await sendTask.ConfigureAwait(false);
if (response == null)
{
throw new InvalidOperationException(SR.net_http_handler_noresponse);
}
if (NetEventSource.IsEnabled) NetEventSource.ClientSendCompleted(this, response, request);
return response;
}
catch (Exception e)
{
HandleFinishSendAsyncError(e, cts);
throw;
}
finally
{
HandleFinishSendAsyncCleanup(cts, disposeCts);
}
}
private void HandleFinishSendAsyncError(Exception e, CancellationTokenSource cts)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e);
// If the cancellation token was canceled, we consider the exception to be caused by the
// cancellation (e.g. WebException when reading from canceled response stream).
if (cts.IsCancellationRequested && e is HttpRequestException)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, "Canceled");
throw new OperationCanceledException(cts.Token);
}
}
private void HandleFinishSendAsyncCleanup(CancellationTokenSource cts, bool disposeCts)
{
// Dispose of the CancellationTokenSource if it was created specially for this request
// rather than being used across multiple requests.
if (disposeCts)
{
cts.Dispose();
}
// This method used to also dispose of the request content, e.g.:
// request.Content?.Dispose();
// This has multiple problems:
// 1. It prevents code from reusing request content objects for subsequent requests,
// as disposing of the object likely invalidates it for further use.
// 2. It prevents the possibility of partial or full duplex communication, even if supported
// by the handler, as the request content may still be in use even if the response
// (or response headers) has been received.
// By changing this to not dispose of the request content, disposal may end up being
// left for the finalizer to handle, or the developer can explicitly dispose of the
// content when they're done with it. But it allows request content to be reused,
// and more importantly it enables handlers that allow receiving of the response before
// fully sending the request. Prior to this change, a handler like CurlHandler would
// fail trying to access certain sites, if the site sent its response before it had
// completely received the request: CurlHandler might then find that the request content
// was disposed of while it still needed to read from it.
}
public void CancelPendingRequests()
{
CheckDisposed();
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
// With every request we link this cancellation token source.
CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts,
new CancellationTokenSource());
currentCts.Cancel();
currentCts.Dispose();
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
#endregion Advanced Send Overloads
#endregion Public Send
#region IDisposable Members
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
// Cancel all pending requests (if any). Note that we don't call CancelPendingRequests() but cancel
// the CTS directly. The reason is that CancelPendingRequests() would cancel the current CTS and create
// a new CTS. We don't want a new CTS in this case.
_pendingRequestsCts.Cancel();
_pendingRequestsCts.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Private Helpers
private void SetOperationStarted()
{
// This method flags the HttpClient instances as "active". I.e. we executed at least one request (or are
// in the process of doing so). This information is used to lock-down all property setters. Once a
// Send/SendAsync operation started, no property can be changed.
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
}
private static void CheckRequestMessage(HttpRequestMessage request)
{
if (!request.MarkAsSent())
{
throw new InvalidOperationException(SR.net_http_client_request_already_sent);
}
}
private void PrepareRequestMessage(HttpRequestMessage request)
{
Uri requestUri = null;
if ((request.RequestUri == null) && (_baseAddress == null))
{
throw new InvalidOperationException(SR.net_http_client_invalid_requesturi);
}
if (request.RequestUri == null)
{
requestUri = _baseAddress;
}
else
{
// If the request Uri is an absolute Uri, just use it. Otherwise try to combine it with the base Uri.
if (!request.RequestUri.IsAbsoluteUri)
{
if (_baseAddress == null)
{
throw new InvalidOperationException(SR.net_http_client_invalid_requesturi);
}
else
{
requestUri = new Uri(_baseAddress, request.RequestUri);
}
}
}
// We modified the original request Uri. Assign the new Uri to the request message.
if (requestUri != null)
{
request.RequestUri = requestUri;
}
// Add default headers
if (_defaultRequestHeaders != null)
{
request.Headers.AddHeaders(_defaultRequestHeaders);
}
}
private static void CheckBaseAddress(Uri baseAddress, string parameterName)
{
if (baseAddress == null)
{
return; // It's OK to not have a base address specified.
}
if (!baseAddress.IsAbsoluteUri)
{
throw new ArgumentException(SR.net_http_client_absolute_baseaddress_required, parameterName);
}
if (!HttpUtilities.IsHttpUri(baseAddress))
{
throw new ArgumentException(SR.net_http_client_http_baseaddress_required, parameterName);
}
}
private Uri CreateUri(string uri) =>
string.IsNullOrEmpty(uri) ? null : new Uri(uri, UriKind.RelativeOrAbsolute);
private HttpRequestMessage CreateRequestMessage(HttpMethod method, Uri uri) =>
new HttpRequestMessage(method, uri) { Version = _defaultRequestVersion };
#endregion Private Helpers
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Data.Common;
using System.Data.SqlClient;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Benchmarks.Configuration;
using Benchmarks.Data;
using Benchmarks.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MySqlConnector;
using Npgsql;
namespace Benchmarks
{
public class Startup
{
public Startup(IWebHostEnvironment hostingEnv, Scenarios scenarios)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(hostingEnv.ContentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{hostingEnv.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.AddCommandLine(Program.Args)
;
Configuration = builder.Build();
Scenarios = scenarios;
}
public IConfigurationRoot Configuration { get; set; }
public Scenarios Scenarios { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration);
// We re-register the Scenarios as an instance singleton here to avoid it being created again due to the
// registration done in Program.Main
services.AddSingleton(Scenarios);
// Common DB services
services.AddSingleton<IRandom, DefaultRandom>();
services.AddEntityFrameworkSqlServer();
var appSettings = Configuration.Get<AppSettings>();
BatchUpdateString.DatabaseServer = appSettings.Database;
Console.WriteLine($"Database: {appSettings.Database}");
if (appSettings.Database == DatabaseServer.PostgreSql)
{
if (Scenarios.Any("Ef"))
{
services.AddDbContextPool<ApplicationDbContext>(options => options.UseNpgsql(appSettings.ConnectionString));
}
if (Scenarios.Any("Raw") || Scenarios.Any("Dapper"))
{
services.AddSingleton<DbProviderFactory>(NpgsqlFactory.Instance);
}
}
else if (appSettings.Database == DatabaseServer.MySql)
{
if (Scenarios.Any("Raw") || Scenarios.Any("Dapper"))
{
services.AddSingleton<DbProviderFactory>(MySqlConnectorFactory.Instance);
}
}
if (Scenarios.Any("Ef"))
{
services.AddScoped<EfDb>();
}
if (Scenarios.Any("Raw"))
{
services.AddScoped<RawDb>();
}
if (Scenarios.Any("Dapper"))
{
services.AddScoped<DapperDb>();
}
if (Scenarios.Any("Fortunes"))
{
var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana);
settings.AllowCharacter('\u2014'); // allow EM DASH through
services.AddWebEncoders((options) =>
{
options.TextEncoderSettings = settings;
});
}
if (Scenarios.Any("Mvc"))
{
var mvcBuilder = services
.AddMvcCore()
.SetCompatibilityVersion(CompatibilityVersion.Latest)
;
if (Scenarios.MvcViews || Scenarios.Any("MvcDbFortunes"))
{
mvcBuilder
.AddViews()
.AddRazorViewEngine();
}
}
}
public void Configure(IApplicationBuilder app)
{
if (Scenarios.Plaintext)
{
app.UsePlainText();
}
if (Scenarios.Json)
{
app.UseJson();
}
// Fortunes endpoints
if (Scenarios.DbFortunesRaw)
{
app.UseFortunesRaw();
}
if (Scenarios.DbFortunesDapper)
{
app.UseFortunesDapper();
}
if (Scenarios.DbFortunesEf)
{
app.UseFortunesEf();
}
// Single query endpoints
if (Scenarios.DbSingleQueryRaw)
{
app.UseSingleQueryRaw();
}
if (Scenarios.DbSingleQueryDapper)
{
app.UseSingleQueryDapper();
}
if (Scenarios.DbSingleQueryEf)
{
app.UseSingleQueryEf();
}
// Multiple query endpoints
if (Scenarios.DbMultiQueryRaw)
{
app.UseMultipleQueriesRaw();
}
if (Scenarios.DbMultiQueryDapper)
{
app.UseMultipleQueriesDapper();
}
if (Scenarios.DbMultiQueryEf)
{
app.UseMultipleQueriesEf();
}
// Multiple update endpoints
if (Scenarios.DbMultiUpdateRaw)
{
app.UseMultipleUpdatesRaw();
}
if (Scenarios.DbMultiUpdateDapper)
{
app.UseMultipleUpdatesDapper();
}
if (Scenarios.DbMultiUpdateEf)
{
app.UseMultipleUpdatesEf();
}
if (Scenarios.Any("Mvc"))
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
if (Scenarios.StaticFiles)
{
app.UseStaticFiles();
}
}
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Store;
using System;
namespace Lucene.Net.Index
{
using NUnit.Framework;
using System.IO;
using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory;
using Directory = Lucene.Net.Store.Directory;
/*
* 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 Document = Documents.Document;
using Field = Field;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using SimpleFSDirectory = Lucene.Net.Store.SimpleFSDirectory;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestCompoundFile : LuceneTestCase
{
private Directory Dir;
[SetUp]
public override void SetUp()
{
base.SetUp();
DirectoryInfo file = CreateTempDir("testIndex");
// use a simple FSDir here, to be sure to have SimpleFSInputs
Dir = new SimpleFSDirectory(file, null);
}
[TearDown]
public override void TearDown()
{
Dir.Dispose();
base.TearDown();
}
/// <summary>
/// Creates a file of the specified size with random data. </summary>
private void CreateRandomFile(Directory dir, string name, int size)
{
IndexOutput os = dir.CreateOutput(name, NewIOContext(Random()));
for (int i = 0; i < size; i++)
{
var b = unchecked((sbyte)(new Random(1).NextDouble() * 256));
os.WriteByte((byte)b);
}
os.Dispose();
}
/// <summary>
/// Creates a file of the specified size with sequential data. The first
/// byte is written as the start byte provided. All subsequent bytes are
/// computed as start + offset where offset is the number of the byte.
/// </summary>
private void CreateSequenceFile(Directory dir, string name, sbyte start, int size)
{
IndexOutput os = dir.CreateOutput(name, NewIOContext(Random()));
for (int i = 0; i < size; i++)
{
os.WriteByte((byte)start);
start++;
}
os.Dispose();
}
private void AssertSameStreams(string msg, IndexInput expected, IndexInput test)
{
Assert.IsNotNull(expected, msg + " null expected");
Assert.IsNotNull(test, msg + " null test");
Assert.AreEqual(expected.Length, test.Length, msg + " length");
Assert.AreEqual(expected.GetFilePointer(), test.GetFilePointer(), msg + " position");
var expectedBuffer = new byte[512];
var testBuffer = new byte[expectedBuffer.Length];
long remainder = expected.Length - expected.GetFilePointer();
while (remainder > 0)
{
int readLen = (int)Math.Min(remainder, expectedBuffer.Length);
expected.ReadBytes(expectedBuffer, 0, readLen);
test.ReadBytes(testBuffer, 0, readLen);
AssertEqualArrays(msg + ", remainder " + remainder, expectedBuffer, testBuffer, 0, readLen);
remainder -= readLen;
}
}
private void AssertSameStreams(string msg, IndexInput expected, IndexInput actual, long seekTo)
{
if (seekTo >= 0 && seekTo < expected.Length)
{
expected.Seek(seekTo);
actual.Seek(seekTo);
AssertSameStreams(msg + ", seek(mid)", expected, actual);
}
}
private void AssertSameSeekBehavior(string msg, IndexInput expected, IndexInput actual)
{
// seek to 0
long point = 0;
AssertSameStreams(msg + ", seek(0)", expected, actual, point);
// seek to middle
point = expected.Length / 2L;
AssertSameStreams(msg + ", seek(mid)", expected, actual, point);
// seek to end - 2
point = expected.Length - 2;
AssertSameStreams(msg + ", seek(end-2)", expected, actual, point);
// seek to end - 1
point = expected.Length - 1;
AssertSameStreams(msg + ", seek(end-1)", expected, actual, point);
// seek to the end
point = expected.Length;
AssertSameStreams(msg + ", seek(end)", expected, actual, point);
// seek past end
point = expected.Length + 1;
AssertSameStreams(msg + ", seek(end+1)", expected, actual, point);
}
private void AssertEqualArrays(string msg, byte[] expected, byte[] test, int start, int len)
{
Assert.IsNotNull(expected, msg + " null expected");
Assert.IsNotNull(test, msg + " null test");
for (int i = start; i < len; i++)
{
Assert.AreEqual(expected[i], test[i], msg + " " + i);
}
}
// ===========================================================
// Tests of the basic CompoundFile functionality
// ===========================================================
/// <summary>
/// this test creates compound file based on a single file.
/// Files of different sizes are tested: 0, 1, 10, 100 bytes.
/// </summary>
[Test]
public virtual void TestSingleFile()
{
int[] data = new int[] { 0, 1, 10, 100 };
for (int i = 0; i < data.Length; i++)
{
string name = "t" + data[i];
CreateSequenceFile(Dir, name, (sbyte)0, data[i]);
CompoundFileDirectory csw = new CompoundFileDirectory(Dir, name + ".cfs", NewIOContext(Random()), true);
Dir.Copy(csw, name, name, NewIOContext(Random()));
csw.Dispose();
CompoundFileDirectory csr = new CompoundFileDirectory(Dir, name + ".cfs", NewIOContext(Random()), false);
IndexInput expected = Dir.OpenInput(name, NewIOContext(Random()));
IndexInput actual = csr.OpenInput(name, NewIOContext(Random()));
AssertSameStreams(name, expected, actual);
AssertSameSeekBehavior(name, expected, actual);
expected.Dispose();
actual.Dispose();
csr.Dispose();
}
}
/// <summary>
/// this test creates compound file based on two files.
///
/// </summary>
[Test]
public virtual void TestTwoFiles()
{
CreateSequenceFile(Dir, "d1", (sbyte)0, 15);
CreateSequenceFile(Dir, "d2", (sbyte)0, 114);
CompoundFileDirectory csw = new CompoundFileDirectory(Dir, "d.cfs", NewIOContext(Random()), true);
Dir.Copy(csw, "d1", "d1", NewIOContext(Random()));
Dir.Copy(csw, "d2", "d2", NewIOContext(Random()));
csw.Dispose();
CompoundFileDirectory csr = new CompoundFileDirectory(Dir, "d.cfs", NewIOContext(Random()), false);
IndexInput expected = Dir.OpenInput("d1", NewIOContext(Random()));
IndexInput actual = csr.OpenInput("d1", NewIOContext(Random()));
AssertSameStreams("d1", expected, actual);
AssertSameSeekBehavior("d1", expected, actual);
expected.Dispose();
actual.Dispose();
expected = Dir.OpenInput("d2", NewIOContext(Random()));
actual = csr.OpenInput("d2", NewIOContext(Random()));
AssertSameStreams("d2", expected, actual);
AssertSameSeekBehavior("d2", expected, actual);
expected.Dispose();
actual.Dispose();
csr.Dispose();
}
/// <summary>
/// this test creates a compound file based on a large number of files of
/// various length. The file content is generated randomly. The sizes range
/// from 0 to 1Mb. Some of the sizes are selected to test the buffering
/// logic in the file reading code. For this the chunk variable is set to
/// the length of the buffer used internally by the compound file logic.
/// </summary>
[Test]
public virtual void TestRandomFiles()
{
// Setup the test segment
string segment = "test";
int chunk = 1024; // internal buffer size used by the stream
CreateRandomFile(Dir, segment + ".zero", 0);
CreateRandomFile(Dir, segment + ".one", 1);
CreateRandomFile(Dir, segment + ".ten", 10);
CreateRandomFile(Dir, segment + ".hundred", 100);
CreateRandomFile(Dir, segment + ".big1", chunk);
CreateRandomFile(Dir, segment + ".big2", chunk - 1);
CreateRandomFile(Dir, segment + ".big3", chunk + 1);
CreateRandomFile(Dir, segment + ".big4", 3 * chunk);
CreateRandomFile(Dir, segment + ".big5", 3 * chunk - 1);
CreateRandomFile(Dir, segment + ".big6", 3 * chunk + 1);
CreateRandomFile(Dir, segment + ".big7", 1000 * chunk);
// Setup extraneous files
CreateRandomFile(Dir, "onetwothree", 100);
CreateRandomFile(Dir, segment + ".notIn", 50);
CreateRandomFile(Dir, segment + ".notIn2", 51);
// Now test
CompoundFileDirectory csw = new CompoundFileDirectory(Dir, "test.cfs", NewIOContext(Random()), true);
string[] data = new string[] { ".zero", ".one", ".ten", ".hundred", ".big1", ".big2", ".big3", ".big4", ".big5", ".big6", ".big7" };
for (int i = 0; i < data.Length; i++)
{
string fileName = segment + data[i];
Dir.Copy(csw, fileName, fileName, NewIOContext(Random()));
}
csw.Dispose();
CompoundFileDirectory csr = new CompoundFileDirectory(Dir, "test.cfs", NewIOContext(Random()), false);
for (int i = 0; i < data.Length; i++)
{
IndexInput check = Dir.OpenInput(segment + data[i], NewIOContext(Random()));
IndexInput test = csr.OpenInput(segment + data[i], NewIOContext(Random()));
AssertSameStreams(data[i], check, test);
AssertSameSeekBehavior(data[i], check, test);
test.Dispose();
check.Dispose();
}
csr.Dispose();
}
/// <summary>
/// Setup a larger compound file with a number of components, each of
/// which is a sequential file (so that we can easily tell that we are
/// reading in the right byte). The methods sets up 20 files - f0 to f19,
/// the size of each file is 1000 bytes.
/// </summary>
private void SetUp_2()
{
CompoundFileDirectory cw = new CompoundFileDirectory(Dir, "f.comp", NewIOContext(Random()), true);
for (int i = 0; i < 20; i++)
{
CreateSequenceFile(Dir, "f" + i, (sbyte)0, 2000);
string fileName = "f" + i;
Dir.Copy(cw, fileName, fileName, NewIOContext(Random()));
}
cw.Dispose();
}
[Test]
public virtual void TestReadAfterClose()
{
try
{
Demo_FSIndexInputBug(Dir, "test");
}
#pragma warning disable 168
catch (ObjectDisposedException ode)
#pragma warning restore 168
{
// expected
}
}
private void Demo_FSIndexInputBug(Directory fsdir, string file)
{
// Setup the test file - we need more than 1024 bytes
IndexOutput os = fsdir.CreateOutput(file, IOContext.DEFAULT);
for (int i = 0; i < 2000; i++)
{
os.WriteByte((byte)(sbyte)i);
}
os.Dispose();
IndexInput @in = fsdir.OpenInput(file, IOContext.DEFAULT);
// this read primes the buffer in IndexInput
@in.ReadByte();
// Close the file
@in.Dispose();
// ERROR: this call should fail, but succeeds because the buffer
// is still filled
@in.ReadByte();
// ERROR: this call should fail, but succeeds for some reason as well
@in.Seek(1099);
try
{
// OK: this call correctly fails. We are now past the 1024 internal
// buffer, so an actual IO is attempted, which fails
@in.ReadByte();
Assert.Fail("expected readByte() to throw exception");
}
#pragma warning disable 168
catch (IOException e)
#pragma warning restore 168
{
// expected exception
}
}
[Test]
public virtual void TestClonedStreamsClosing()
{
SetUp_2();
CompoundFileDirectory cr = new CompoundFileDirectory(Dir, "f.comp", NewIOContext(Random()), false);
// basic clone
IndexInput expected = Dir.OpenInput("f11", NewIOContext(Random()));
// this test only works for FSIndexInput
Assert.IsTrue(TestHelper.IsSimpleFSIndexInput(expected));
Assert.IsTrue(TestHelper.IsSimpleFSIndexInputOpen(expected));
IndexInput one = cr.OpenInput("f11", NewIOContext(Random()));
IndexInput two = (IndexInput)one.Clone();
AssertSameStreams("basic clone one", expected, one);
expected.Seek(0);
AssertSameStreams("basic clone two", expected, two);
// Now close the first stream
one.Dispose();
// The following should really fail since we couldn't expect to
// access a file once close has been called on it (regardless of
// buffering and/or clone magic)
expected.Seek(0);
two.Seek(0);
AssertSameStreams("basic clone two/2", expected, two);
// Now close the compound reader
cr.Dispose();
// The following may also fail since the compound stream is closed
expected.Seek(0);
two.Seek(0);
//assertSameStreams("basic clone two/3", expected, two);
// Now close the second clone
two.Dispose();
expected.Seek(0);
two.Seek(0);
//assertSameStreams("basic clone two/4", expected, two);
expected.Dispose();
}
/// <summary>
/// this test opens two files from a compound stream and verifies that
/// their file positions are independent of each other.
/// </summary>
[Test]
public virtual void TestRandomAccess()
{
SetUp_2();
CompoundFileDirectory cr = new CompoundFileDirectory(Dir, "f.comp", NewIOContext(Random()), false);
// Open two files
IndexInput e1 = Dir.OpenInput("f11", NewIOContext(Random()));
IndexInput e2 = Dir.OpenInput("f3", NewIOContext(Random()));
IndexInput a1 = cr.OpenInput("f11", NewIOContext(Random()));
IndexInput a2 = Dir.OpenInput("f3", NewIOContext(Random()));
// Seek the first pair
e1.Seek(100);
a1.Seek(100);
Assert.AreEqual(100, e1.GetFilePointer());
Assert.AreEqual(100, a1.GetFilePointer());
byte be1 = e1.ReadByte();
byte ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
// Now seek the second pair
e2.Seek(1027);
a2.Seek(1027);
Assert.AreEqual(1027, e2.GetFilePointer());
Assert.AreEqual(1027, a2.GetFilePointer());
byte be2 = e2.ReadByte();
byte ba2 = a2.ReadByte();
Assert.AreEqual(be2, ba2);
// Now make sure the first one didn't move
Assert.AreEqual(101, e1.GetFilePointer());
Assert.AreEqual(101, a1.GetFilePointer());
be1 = e1.ReadByte();
ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
// Now more the first one again, past the buffer length
e1.Seek(1910);
a1.Seek(1910);
Assert.AreEqual(1910, e1.GetFilePointer());
Assert.AreEqual(1910, a1.GetFilePointer());
be1 = e1.ReadByte();
ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
// Now make sure the second set didn't move
Assert.AreEqual(1028, e2.GetFilePointer());
Assert.AreEqual(1028, a2.GetFilePointer());
be2 = e2.ReadByte();
ba2 = a2.ReadByte();
Assert.AreEqual(be2, ba2);
// Move the second set back, again cross the buffer size
e2.Seek(17);
a2.Seek(17);
Assert.AreEqual(17, e2.GetFilePointer());
Assert.AreEqual(17, a2.GetFilePointer());
be2 = e2.ReadByte();
ba2 = a2.ReadByte();
Assert.AreEqual(be2, ba2);
// Finally, make sure the first set didn't move
// Now make sure the first one didn't move
Assert.AreEqual(1911, e1.GetFilePointer());
Assert.AreEqual(1911, a1.GetFilePointer());
be1 = e1.ReadByte();
ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
e1.Dispose();
e2.Dispose();
a1.Dispose();
a2.Dispose();
cr.Dispose();
}
/// <summary>
/// this test opens two files from a compound stream and verifies that
/// their file positions are independent of each other.
/// </summary>
[Test]
public virtual void TestRandomAccessClones()
{
SetUp_2();
CompoundFileDirectory cr = new CompoundFileDirectory(Dir, "f.comp", NewIOContext(Random()), false);
// Open two files
IndexInput e1 = cr.OpenInput("f11", NewIOContext(Random()));
IndexInput e2 = cr.OpenInput("f3", NewIOContext(Random()));
IndexInput a1 = (IndexInput)e1.Clone();
IndexInput a2 = (IndexInput)e2.Clone();
// Seek the first pair
e1.Seek(100);
a1.Seek(100);
Assert.AreEqual(100, e1.GetFilePointer());
Assert.AreEqual(100, a1.GetFilePointer());
byte be1 = e1.ReadByte();
byte ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
// Now seek the second pair
e2.Seek(1027);
a2.Seek(1027);
Assert.AreEqual(1027, e2.GetFilePointer());
Assert.AreEqual(1027, a2.GetFilePointer());
byte be2 = e2.ReadByte();
byte ba2 = a2.ReadByte();
Assert.AreEqual(be2, ba2);
// Now make sure the first one didn't move
Assert.AreEqual(101, e1.GetFilePointer());
Assert.AreEqual(101, a1.GetFilePointer());
be1 = e1.ReadByte();
ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
// Now more the first one again, past the buffer length
e1.Seek(1910);
a1.Seek(1910);
Assert.AreEqual(1910, e1.GetFilePointer());
Assert.AreEqual(1910, a1.GetFilePointer());
be1 = e1.ReadByte();
ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
// Now make sure the second set didn't move
Assert.AreEqual(1028, e2.GetFilePointer());
Assert.AreEqual(1028, a2.GetFilePointer());
be2 = e2.ReadByte();
ba2 = a2.ReadByte();
Assert.AreEqual(be2, ba2);
// Move the second set back, again cross the buffer size
e2.Seek(17);
a2.Seek(17);
Assert.AreEqual(17, e2.GetFilePointer());
Assert.AreEqual(17, a2.GetFilePointer());
be2 = e2.ReadByte();
ba2 = a2.ReadByte();
Assert.AreEqual(be2, ba2);
// Finally, make sure the first set didn't move
// Now make sure the first one didn't move
Assert.AreEqual(1911, e1.GetFilePointer());
Assert.AreEqual(1911, a1.GetFilePointer());
be1 = e1.ReadByte();
ba1 = a1.ReadByte();
Assert.AreEqual(be1, ba1);
e1.Dispose();
e2.Dispose();
a1.Dispose();
a2.Dispose();
cr.Dispose();
}
[Test]
public virtual void TestFileNotFound()
{
SetUp_2();
CompoundFileDirectory cr = new CompoundFileDirectory(Dir, "f.comp", NewIOContext(Random()), false);
// Open two files
try
{
cr.OpenInput("bogus", NewIOContext(Random()));
Assert.Fail("File not found");
}
#pragma warning disable 168
catch (Exception e)
#pragma warning restore 168
{
/* success */
//System.out.println("SUCCESS: File Not Found: " + e);
}
cr.Dispose();
}
[Test]
public virtual void TestReadPastEOF()
{
SetUp_2();
var cr = new CompoundFileDirectory(Dir, "f.comp", NewIOContext(Random()), false);
IndexInput @is = cr.OpenInput("f2", NewIOContext(Random()));
@is.Seek(@is.Length - 10);
var b = new byte[100];
@is.ReadBytes(b, 0, 10);
try
{
@is.ReadByte();
Assert.Fail("Single byte read past end of file");
}
#pragma warning disable 168
catch (IOException e)
#pragma warning restore 168
{
/* success */
//System.out.println("SUCCESS: single byte read past end of file: " + e);
}
@is.Seek(@is.Length - 10);
try
{
@is.ReadBytes(b, 0, 50);
Assert.Fail("Block read past end of file");
}
#pragma warning disable 168
catch (IOException e)
#pragma warning restore 168
{
/* success */
//System.out.println("SUCCESS: block read past end of file: " + e);
}
@is.Dispose();
cr.Dispose();
}
/// <summary>
/// this test that writes larger than the size of the buffer output
/// will correctly increment the file pointer.
/// </summary>
[Test]
public virtual void TestLargeWrites()
{
IndexOutput os = Dir.CreateOutput("testBufferStart.txt", NewIOContext(Random()));
var largeBuf = new byte[2048];
for (int i = 0; i < largeBuf.Length; i++)
{
largeBuf[i] = (byte)unchecked((sbyte)(new Random(1).NextDouble() * 256));
}
long currentPos = os.GetFilePointer();
os.WriteBytes(largeBuf, largeBuf.Length);
try
{
Assert.AreEqual(currentPos + largeBuf.Length, os.GetFilePointer());
}
finally
{
os.Dispose();
}
}
[Test]
public virtual void TestAddExternalFile()
{
CreateSequenceFile(Dir, "d1", (sbyte)0, 15);
Directory newDir = NewDirectory();
CompoundFileDirectory csw = new CompoundFileDirectory(newDir, "d.cfs", NewIOContext(Random()), true);
Dir.Copy(csw, "d1", "d1", NewIOContext(Random()));
csw.Dispose();
CompoundFileDirectory csr = new CompoundFileDirectory(newDir, "d.cfs", NewIOContext(Random()), false);
IndexInput expected = Dir.OpenInput("d1", NewIOContext(Random()));
IndexInput actual = csr.OpenInput("d1", NewIOContext(Random()));
AssertSameStreams("d1", expected, actual);
AssertSameSeekBehavior("d1", expected, actual);
expected.Dispose();
actual.Dispose();
csr.Dispose();
newDir.Dispose();
}
[Test]
public virtual void TestAppend()
{
Directory newDir = NewDirectory();
CompoundFileDirectory csw = new CompoundFileDirectory(newDir, "d.cfs", NewIOContext(Random()), true);
int size = 5 + Random().Next(128);
for (int j = 0; j < 2; j++)
{
IndexOutput os = csw.CreateOutput("seg_" + j + "_foo.txt", NewIOContext(Random()));
for (int i = 0; i < size; i++)
{
os.WriteInt32(i * j);
}
os.Dispose();
string[] listAll = newDir.ListAll();
Assert.AreEqual(1, listAll.Length);
Assert.AreEqual("d.cfs", listAll[0]);
}
CreateSequenceFile(Dir, "d1", (sbyte)0, 15);
Dir.Copy(csw, "d1", "d1", NewIOContext(Random()));
string[] listAll_ = newDir.ListAll();
Assert.AreEqual(1, listAll_.Length);
Assert.AreEqual("d.cfs", listAll_[0]);
csw.Dispose();
CompoundFileDirectory csr = new CompoundFileDirectory(newDir, "d.cfs", NewIOContext(Random()), false);
for (int j = 0; j < 2; j++)
{
IndexInput openInput = csr.OpenInput("seg_" + j + "_foo.txt", NewIOContext(Random()));
Assert.AreEqual(size * 4, openInput.Length);
for (int i = 0; i < size; i++)
{
Assert.AreEqual(i * j, openInput.ReadInt32());
}
openInput.Dispose();
}
IndexInput expected = Dir.OpenInput("d1", NewIOContext(Random()));
IndexInput actual = csr.OpenInput("d1", NewIOContext(Random()));
AssertSameStreams("d1", expected, actual);
AssertSameSeekBehavior("d1", expected, actual);
expected.Dispose();
actual.Dispose();
csr.Dispose();
newDir.Dispose();
}
[Test]
public virtual void TestAppendTwice()
{
Directory newDir = NewDirectory();
CompoundFileDirectory csw = new CompoundFileDirectory(newDir, "d.cfs", NewIOContext(Random()), true);
CreateSequenceFile(newDir, "d1", (sbyte)0, 15);
IndexOutput @out = csw.CreateOutput("d.xyz", NewIOContext(Random()));
@out.WriteInt32(0);
@out.Dispose();
Assert.AreEqual(1, csw.ListAll().Length);
Assert.AreEqual("d.xyz", csw.ListAll()[0]);
csw.Dispose();
CompoundFileDirectory cfr = new CompoundFileDirectory(newDir, "d.cfs", NewIOContext(Random()), false);
Assert.AreEqual(1, cfr.ListAll().Length);
Assert.AreEqual("d.xyz", cfr.ListAll()[0]);
cfr.Dispose();
newDir.Dispose();
}
[Test]
public virtual void TestEmptyCFS()
{
Directory newDir = NewDirectory();
CompoundFileDirectory csw = new CompoundFileDirectory(newDir, "d.cfs", NewIOContext(Random()), true);
csw.Dispose();
CompoundFileDirectory csr = new CompoundFileDirectory(newDir, "d.cfs", NewIOContext(Random()), false);
Assert.AreEqual(0, csr.ListAll().Length);
csr.Dispose();
newDir.Dispose();
}
[Test]
public virtual void TestReadNestedCFP()
{
Directory newDir = NewDirectory();
CompoundFileDirectory csw = new CompoundFileDirectory(newDir, "d.cfs", NewIOContext(Random()), true);
CompoundFileDirectory nested = new CompoundFileDirectory(newDir, "b.cfs", NewIOContext(Random()), true);
IndexOutput @out = nested.CreateOutput("b.xyz", NewIOContext(Random()));
IndexOutput out1 = nested.CreateOutput("b_1.xyz", NewIOContext(Random()));
@out.WriteInt32(0);
out1.WriteInt32(1);
@out.Dispose();
out1.Dispose();
nested.Dispose();
newDir.Copy(csw, "b.cfs", "b.cfs", NewIOContext(Random()));
newDir.Copy(csw, "b.cfe", "b.cfe", NewIOContext(Random()));
newDir.DeleteFile("b.cfs");
newDir.DeleteFile("b.cfe");
csw.Dispose();
Assert.AreEqual(2, newDir.ListAll().Length);
csw = new CompoundFileDirectory(newDir, "d.cfs", NewIOContext(Random()), false);
Assert.AreEqual(2, csw.ListAll().Length);
nested = new CompoundFileDirectory(csw, "b.cfs", NewIOContext(Random()), false);
Assert.AreEqual(2, nested.ListAll().Length);
IndexInput openInput = nested.OpenInput("b.xyz", NewIOContext(Random()));
Assert.AreEqual(0, openInput.ReadInt32());
openInput.Dispose();
openInput = nested.OpenInput("b_1.xyz", NewIOContext(Random()));
Assert.AreEqual(1, openInput.ReadInt32());
openInput.Dispose();
nested.Dispose();
csw.Dispose();
newDir.Dispose();
}
[Test]
public virtual void TestDoubleClose()
{
Directory newDir = NewDirectory();
CompoundFileDirectory csw = new CompoundFileDirectory(newDir, "d.cfs", NewIOContext(Random()), true);
IndexOutput @out = csw.CreateOutput("d.xyz", NewIOContext(Random()));
@out.WriteInt32(0);
@out.Dispose();
csw.Dispose();
// close a second time - must have no effect according to IDisposable
csw.Dispose();
csw = new CompoundFileDirectory(newDir, "d.cfs", NewIOContext(Random()), false);
IndexInput openInput = csw.OpenInput("d.xyz", NewIOContext(Random()));
Assert.AreEqual(0, openInput.ReadInt32());
openInput.Dispose();
csw.Dispose();
// close a second time - must have no effect according to IDisposable
csw.Dispose();
newDir.Dispose();
}
// Make sure we don't somehow use more than 1 descriptor
// when reading a CFS with many subs:
[Test]
public virtual void TestManySubFiles()
{
Directory d = NewFSDirectory(CreateTempDir("CFSManySubFiles"));
int FILE_COUNT = AtLeast(500);
for (int fileIdx = 0; fileIdx < FILE_COUNT; fileIdx++)
{
IndexOutput @out = d.CreateOutput("file." + fileIdx, NewIOContext(Random()));
@out.WriteByte((byte)(sbyte)fileIdx);
@out.Dispose();
}
CompoundFileDirectory cfd = new CompoundFileDirectory(d, "c.cfs", NewIOContext(Random()), true);
for (int fileIdx = 0; fileIdx < FILE_COUNT; fileIdx++)
{
string fileName = "file." + fileIdx;
d.Copy(cfd, fileName, fileName, NewIOContext(Random()));
}
cfd.Dispose();
IndexInput[] ins = new IndexInput[FILE_COUNT];
CompoundFileDirectory cfr = new CompoundFileDirectory(d, "c.cfs", NewIOContext(Random()), false);
for (int fileIdx = 0; fileIdx < FILE_COUNT; fileIdx++)
{
ins[fileIdx] = cfr.OpenInput("file." + fileIdx, NewIOContext(Random()));
}
for (int fileIdx = 0; fileIdx < FILE_COUNT; fileIdx++)
{
Assert.AreEqual((byte)fileIdx, ins[fileIdx].ReadByte());
}
for (int fileIdx = 0; fileIdx < FILE_COUNT; fileIdx++)
{
ins[fileIdx].Dispose();
}
cfr.Dispose();
d.Dispose();
}
[Test]
public virtual void TestListAll()
{
Directory dir = NewDirectory();
// riw should sometimes create docvalues fields, etc
RandomIndexWriter riw = new RandomIndexWriter(Random(), dir, Similarity, TimeZone);
Document doc = new Document();
// these fields should sometimes get term vectors, etc
Field idField = NewStringField("id", "", Field.Store.NO);
Field bodyField = NewTextField("body", "", Field.Store.NO);
doc.Add(idField);
doc.Add(bodyField);
for (int i = 0; i < 100; i++)
{
idField.SetStringValue(Convert.ToString(i));
bodyField.SetStringValue(TestUtil.RandomUnicodeString(Random()));
riw.AddDocument(doc);
if (Random().Next(7) == 0)
{
riw.Commit();
}
}
riw.Dispose();
CheckFiles(dir);
dir.Dispose();
}
// checks that we can open all files returned by listAll!
private void CheckFiles(Directory dir)
{
foreach (string file in dir.ListAll())
{
if (file.EndsWith(IndexFileNames.COMPOUND_FILE_EXTENSION))
{
CompoundFileDirectory cfsDir = new CompoundFileDirectory(dir, file, NewIOContext(Random()), false);
CheckFiles(cfsDir); // recurse into cfs
cfsDir.Dispose();
}
IndexInput @in = null;
bool success = false;
try
{
@in = dir.OpenInput(file, NewIOContext(Random()));
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(@in);
}
else
{
IOUtils.DisposeWhileHandlingException(@in);
}
}
}
}
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using Internal.Runtime.CompilerServices;
#pragma warning disable SA1121 // explicitly using type aliases instead of built-in types
#if BIT64
using nuint = System.UInt64;
#else // BIT64
using nuint = System.UInt32;
#endif // BIT64
namespace System
{
/// <summary>
/// Memory represents a contiguous region of arbitrary memory similar to <see cref="Span{T}"/>.
/// Unlike <see cref="Span{T}"/>, it is not a byref-like type.
/// </summary>
[DebuggerTypeProxy(typeof(MemoryDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public readonly struct Memory<T> : IEquatable<Memory<T>>
{
// NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout,
// as code uses Unsafe.As to cast between them.
// The highest order bit of _index is used to discern whether _object is a pre-pinned array.
// (_index < 0) => _object is a pre-pinned array, so Pin() will not allocate a new GCHandle
// (else) => Pin() needs to allocate a new GCHandle to pin the object.
private readonly object? _object;
private readonly int _index;
private readonly int _length;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory(T[]? array)
{
if (array == null)
{
this = default;
return; // returns default
}
if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
ThrowHelper.ThrowArrayTypeMismatchException();
_object = array;
_index = 0;
_length = array.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(T[]? array, int start)
{
if (array == null)
{
if (start != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
this = default;
return; // returns default
}
if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
ThrowHelper.ThrowArrayTypeMismatchException();
if ((uint)start > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
_object = array;
_index = start;
_length = array.Length - start;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory(T[]? array, int start, int length)
{
if (array == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
this = default;
return; // returns default
}
if (default(T)! == null && array.GetType() != typeof(T[])) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
ThrowHelper.ThrowArrayTypeMismatchException();
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
#else
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
#endif
_object = array;
_index = start;
_length = length;
}
/// <summary>
/// Creates a new memory from a memory manager that provides specific method implementations beginning
/// at 0 index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="manager">The memory manager.</param>
/// <param name="length">The number of items in the memory.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="length"/> is negative.
/// </exception>
/// <remarks>For internal infrastructure only</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(MemoryManager<T> manager, int length)
{
Debug.Assert(manager != null);
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
_object = manager;
_index = 0;
_length = length;
}
/// <summary>
/// Creates a new memory from a memory manager that provides specific method implementations beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="manager">The memory manager.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or <paramref name="length"/> is negative.
/// </exception>
/// <remarks>For internal infrastructure only</remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(MemoryManager<T> manager, int start, int length)
{
Debug.Assert(manager != null);
if (length < 0 || start < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
_object = manager;
_index = start;
_length = length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Memory(object? obj, int start, int length)
{
// No validation performed in release builds; caller must provide any necessary validation.
// 'obj is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert((obj == null)
|| (typeof(T) == typeof(char) && obj is string)
#if FEATURE_UTF8STRING
|| ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && obj is Utf8String)
#endif // FEATURE_UTF8STRING
|| (obj is T[])
|| (obj is MemoryManager<T>));
_object = obj;
_index = start;
_length = length;
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator Memory<T>(T[]? array) => new Memory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator Memory<T>(ArraySegment<T> segment) => new Memory<T>(segment.Array, segment.Offset, segment.Count);
/// <summary>
/// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) =>
Unsafe.As<Memory<T>, ReadOnlyMemory<T>>(ref memory);
/// <summary>
/// Returns an empty <see cref="Memory{T}"/>
/// </summary>
public static Memory<T> Empty => default;
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// For <see cref="Memory{Char}"/>, returns a new instance of string that represents the characters pointed to by the memory.
/// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements.
/// </summary>
public override string ToString()
{
if (typeof(T) == typeof(char))
{
return (_object is string str) ? str.Substring(_index, _length) : Span.ToString();
}
#if FEATURE_UTF8STRING
else if (typeof(T) == typeof(Char8))
{
// TODO_UTF8STRING: Call into optimized transcoding routine when it's available.
Span<T> span = Span;
return Encoding.UTF8.GetString(new ReadOnlySpan<byte>(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length));
}
#endif // FEATURE_UTF8STRING
return string.Format("System.Memory<{0}>[{1}]", typeof(T).Name, _length);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
// It is expected for _index + start to be negative if the memory is already pre-pinned.
return new Memory<T>(_object, _index + start, _length - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Memory<T> Slice(int start, int length)
{
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException();
#else
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
#endif
// It is expected for _index + start to be negative if the memory is already pre-pinned.
return new Memory<T>(_object, _index + start, length);
}
/// <summary>
/// Returns a span from the memory.
/// </summary>
public unsafe Span<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
// This property getter has special support for returning a mutable Span<char> that wraps
// an immutable String instance. This is obviously a dangerous feature and breaks type safety.
// However, we need to handle the case where a ReadOnlyMemory<char> was created from a string
// and then cast to a Memory<T>. Such a cast can only be done with unsafe or marshaling code,
// in which case that's the dangerous operation performed by the dev, and we're just following
// suit here to make it work as best as possible.
ref T refToReturn = ref Unsafe.NullRef<T>();
int lengthOfUnderlyingSpan = 0;
// Copy this field into a local so that it can't change out from under us mid-operation.
object? tmpObject = _object;
if (tmpObject != null)
{
if (typeof(T) == typeof(char) && tmpObject.GetType() == typeof(string))
{
// Special-case string since it's the most common for ROM<char>.
refToReturn = ref Unsafe.As<char, T>(ref Unsafe.As<string>(tmpObject).GetRawStringData());
lengthOfUnderlyingSpan = Unsafe.As<string>(tmpObject).Length;
}
#if FEATURE_UTF8STRING
else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject.GetType() == typeof(Utf8String))
{
refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<Utf8String>(tmpObject).DangerousGetMutableReference());
lengthOfUnderlyingSpan = Unsafe.As<Utf8String>(tmpObject).Length;
}
#endif // FEATURE_UTF8STRING
else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject))
{
// We know the object is not null, it's not a string, and it is variable-length. The only
// remaining option is for it to be a T[] (or a U[] which is blittable to T[], like int[]
// and uint[]). Otherwise somebody used private reflection to set this field, and we're not
// too worried about type safety violations at this point.
// 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert(tmpObject is T[]);
refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData());
lengthOfUnderlyingSpan = Unsafe.As<T[]>(tmpObject).Length;
}
else
{
// We know the object is not null, and it's not variable-length, so it must be a MemoryManager<T>.
// Otherwise somebody used private reflection to set this field, and we're not too worried about
// type safety violations at that point. Note that it can't be a MemoryManager<U>, even if U and
// T are blittable (e.g., MemoryManager<int> to MemoryManager<uint>), since there exists no
// constructor or other public API which would allow such a conversion.
Debug.Assert(tmpObject is MemoryManager<T>);
Span<T> memoryManagerSpan = Unsafe.As<MemoryManager<T>>(tmpObject).GetSpan();
refToReturn = ref MemoryMarshal.GetReference(memoryManagerSpan);
lengthOfUnderlyingSpan = memoryManagerSpan.Length;
}
// If the Memory<T> or ReadOnlyMemory<T> instance is torn, this property getter has undefined behavior.
// We try to detect this condition and throw an exception, but it's possible that a torn struct might
// appear to us to be valid, and we'll return an undesired span. Such a span is always guaranteed at
// least to be in-bounds when compared with the original Memory<T> instance, so using the span won't
// AV the process.
nuint desiredStartIndex = (uint)_index & (uint)ReadOnlyMemory<T>.RemoveFlagsBitMask;
int desiredLength = _length;
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)desiredStartIndex + (ulong)(uint)desiredLength > (ulong)(uint)lengthOfUnderlyingSpan)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
#else
if ((uint)desiredStartIndex > (uint)lengthOfUnderlyingSpan || (uint)desiredLength > (uint)(lengthOfUnderlyingSpan - desiredStartIndex))
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
#endif
refToReturn = ref Unsafe.Add(ref refToReturn, (IntPtr)(void*)desiredStartIndex);
lengthOfUnderlyingSpan = desiredLength;
}
return new Span<T>(ref refToReturn, lengthOfUnderlyingSpan);
}
}
/// <summary>
/// Copies the contents of the memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The Memory to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination is shorter than the source.
/// </exception>
/// </summary>
public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span);
/// <summary>
/// Copies the contents of the memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination is shorter than the source, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span);
/// <summary>
/// Creates a handle for the memory.
/// The GC will not move the memory until the returned <see cref="MemoryHandle"/>
/// is disposed, enabling taking and using the memory's address.
/// <exception cref="System.ArgumentException">
/// An instance with nonprimitive (non-blittable) members cannot be pinned.
/// </exception>
/// </summary>
public unsafe MemoryHandle Pin()
{
// Just like the Span property getter, we have special support for a mutable Memory<char>
// that wraps an immutable String instance. This might happen if a caller creates an
// immutable ROM<char> wrapping a String, then uses Unsafe.As to create a mutable M<char>.
// This needs to work, however, so that code that uses a single Memory<char> field to store either
// a readable ReadOnlyMemory<char> or a writable Memory<char> can still be pinned and
// used for interop purposes.
// It's possible that the below logic could result in an AV if the struct
// is torn. This is ok since the caller is expecting to use raw pointers,
// and we're not required to keep this as safe as the other Span-based APIs.
object? tmpObject = _object;
if (tmpObject != null)
{
if (typeof(T) == typeof(char) && tmpObject is string s)
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
ref char stringData = ref Unsafe.Add(ref s.GetRawStringData(), _index);
return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle);
}
#if FEATURE_UTF8STRING
else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject is Utf8String utf8String)
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
ref byte stringData = ref utf8String.DangerousGetMutableReference(_index);
return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle);
}
#endif // FEATURE_UTF8STRING
else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject))
{
// 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert(tmpObject is T[]);
// Array is already pre-pinned
if (_index < 0)
{
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index & ReadOnlyMemory<T>.RemoveFlagsBitMask);
return new MemoryHandle(pointer);
}
else
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index);
return new MemoryHandle(pointer, handle);
}
}
else
{
Debug.Assert(tmpObject is MemoryManager<T>);
return Unsafe.As<MemoryManager<T>>(tmpObject).Pin(_index);
}
}
return default;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// Returns true if the object is Memory or ReadOnlyMemory and if both objects point to the same array and have the same length.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj)
{
if (obj is ReadOnlyMemory<T>)
{
return ((ReadOnlyMemory<T>)obj).Equals(this);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(Memory<T> other)
{
return
_object == other._object &&
_index == other._index &&
_length == other._length;
}
/// <summary>
/// Serves as the default hash function.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
// We use RuntimeHelpers.GetHashCode instead of Object.GetHashCode because the hash
// code is based on object identity and referential equality, not deep equality (as common with string).
return (_object != null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0;
}
}
}
| |
/*
* Copyright (C) 2005-2015 Christoph Rupp (chris@crupp.de).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Hamster;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Unittests
{
public class CursorTest
{
private int counter;
private int Callback(byte[] b1, byte[] b2) {
counter++;
if (b1.GetLength(0) < b2.GetLength(0))
return (-1);
if (b1.GetLength(0) > b2.GetLength(0))
return (+1);
for (int i = b1.GetLength(0); --i >= 0; ) {
if (b1[i] < b2[i])
return (-1);
if (b1[i] > b2[i])
return (+1);
}
return 0;
}
private Hamster.Environment env;
private Database db;
private void SetUp() {
env = new Hamster.Environment();
db = new Database();
env.Create("ntest.db");
db = env.CreateDatabase(1, HamConst.HAM_ENABLE_DUPLICATE_KEYS);
}
private void TearDown() {
env.Close();
}
private void Create() {
Cursor c = new Cursor(db);
c.Close();
}
private void Clone() {
Cursor c1 = new Cursor(db);
Cursor c2 = c1.Clone();
}
private void Move() {
Cursor c = new Cursor(db);
byte[] k = new byte[5];
byte[] r = new byte[5];
k[0] = 0;
db.Insert(k, r);
k[0] = 1;
db.Insert(k, r);
k[0] = 2;
db.Insert(k, r);
k[0] = 3;
db.Insert(k, r);
k[0] = 4;
db.Insert(k, r);
c.Move(HamConst.HAM_CURSOR_NEXT);
c.Move(HamConst.HAM_CURSOR_NEXT);
c.Move(HamConst.HAM_CURSOR_PREVIOUS);
c.Move(HamConst.HAM_CURSOR_LAST);
c.Move(HamConst.HAM_CURSOR_FIRST);
}
private void MoveNegative() {
Cursor c = new Cursor(db);
try {
c.Move(HamConst.HAM_CURSOR_NEXT);
}
catch (DatabaseException e) {
Assert.AreEqual(HamConst.HAM_KEY_NOT_FOUND, e.ErrorCode);
}
}
private void MoveFirst() {
Cursor c = new Cursor(db);
byte[] k = new byte[5];
byte[] r = new byte[5];
db.Insert(k, r);
c.MoveFirst();
}
private void MoveLast() {
Cursor c = new Cursor(db);
byte[] k = new byte[5];
byte[] r = new byte[5];
db.Insert(k, r);
c.MoveLast();
}
private void MoveNext() {
Cursor c = new Cursor(db);
byte[] k = new byte[5];
byte[] r = new byte[5];
db.Insert(k, r);
c.MoveNext();
}
private void MovePrevious() {
Cursor c = new Cursor(db);
byte[] k = new byte[5];
byte[] r = new byte[5];
db.Insert(k, r);
c.MovePrevious();
}
void checkEqual(byte[] lhs, byte[] rhs)
{
Assert.AreEqual(lhs.Length, rhs.Length);
for (int i = 0; i < lhs.Length; i++)
Assert.AreEqual(lhs[i], rhs[i]);
}
private void GetKey() {
Cursor c = new Cursor(db);
byte[] k = new byte[5];
byte[] r = new byte[5];
db.Insert(k, r);
c.MovePrevious();
byte[] f = c.GetKey();
checkEqual(k, f);
}
private void GetRecord() {
Cursor c = new Cursor(db);
byte[] k = new byte[5];
byte[] r = new byte[5];
db.Insert(k, r);
c.MovePrevious();
byte[] f = c.GetRecord();
checkEqual(r, f);
}
private void Overwrite() {
Cursor c = new Cursor(db);
byte[] k = new byte[5];
byte[] r1 = new byte[5]; r1[0] = 1;
byte[] r2 = new byte[5]; r2[0] = 2;
db.Insert(k, r1);
c.MoveFirst();
byte[] f = c.GetRecord();
checkEqual(r1, f);
c.Overwrite(r2);
byte[] g = c.GetRecord();
checkEqual(r2, g);
}
private void Find() {
Cursor c = new Cursor(db);
byte[] k1 = new byte[5]; k1[0] = 5;
byte[] k2 = new byte[5]; k2[0] = 6;
byte[] r1 = new byte[5]; r1[0] = 1;
byte[] r2 = new byte[5]; r2[0] = 2;
db.Insert(k1, r1);
db.Insert(k2, r2);
c.Find(k1);
byte[] f = c.GetRecord();
checkEqual(r1, f);
c.Find(k2);
byte[] g = c.GetRecord();
checkEqual(r2, g);
}
private void TryFind()
{
Cursor c = new Cursor(db);
byte[] k1 = new byte[5]; k1[0] = 5;
byte[] k2 = new byte[5]; k2[0] = 6;
byte[] k3 = new byte[5]; k3[0] = 7;
byte[] r1 = new byte[5]; r1[0] = 1;
byte[] r2 = new byte[5]; r2[0] = 2;
db.Insert(k1, r1);
db.Insert(k2, r2);
var f = c.TryFind(k1);
checkEqual(r1, f);
var g = c.TryFind(k2);
checkEqual(r2, g);
var h = c.TryFind(k3);
Assert.IsNull(h);
}
private void Insert() {
Cursor c = new Cursor(db);
byte[] q;
byte[] k1 = new byte[5]; k1[0] = 5;
byte[] k2 = new byte[5]; k2[0] = 6;
byte[] r1 = new byte[5]; r1[0] = 1;
byte[] r2 = new byte[5]; r2[0] = 2;
c.Insert(k1, r1);
q = c.GetRecord();
checkEqual(r1, q);
q = c.GetKey();
checkEqual(k1, q);
c.Insert(k2, r2);
q = c.GetRecord();
checkEqual(r2, q);
q = c.GetKey();
checkEqual(k2, q);
}
private void InsertDuplicate() {
Cursor c = new Cursor(db);
byte[] q;
byte[] k1 = new byte[5]; k1[0] = 5;
byte[] r1 = new byte[5]; r1[0] = 1;
byte[] r2 = new byte[5]; r2[0] = 2;
c.Insert(k1, r1);
q = c.GetRecord();
checkEqual(r1, q);
q = c.GetKey();
checkEqual(k1, q);
c.Insert(k1, r2, HamConst.HAM_DUPLICATE);
q = c.GetRecord();
checkEqual(r2, q);
q = c.GetKey();
checkEqual(k1, q);
}
private void InsertNegative() {
Cursor c = new Cursor(db);
byte[] q;
byte[] k1 = new byte[5]; k1[0] = 5;
byte[] r1 = new byte[5]; r1[0] = 1;
byte[] r2 = new byte[5]; r2[0] = 2;
c.Insert(k1, r1);
q = c.GetRecord();
checkEqual(r1, q);
q = c.GetKey();
checkEqual(k1, q);
try {
c.Insert(k1, r2);
}
catch (DatabaseException e) {
Assert.AreEqual(HamConst.HAM_DUPLICATE_KEY, e.ErrorCode);
}
}
private void Erase() {
Cursor c = new Cursor(db);
byte[] k1 = new byte[5]; k1[0] = 5;
byte[] r1 = new byte[5]; r1[0] = 1;
c.Insert(k1, r1);
c.Erase();
}
private void EraseNegative() {
Cursor c = new Cursor(db);
try {
c.Erase();
}
catch (DatabaseException e) {
Assert.AreEqual(HamConst.HAM_CURSOR_IS_NIL, e.ErrorCode);
}
}
private void GetDuplicateCount() {
Cursor c = new Cursor(db);
byte[] k1 = new byte[5]; k1[0] = 5;
byte[] r1 = new byte[5]; r1[0] = 1;
byte[] r2 = new byte[5]; r2[0] = 2;
byte[] r3 = new byte[5]; r2[0] = 2;
c.Insert(k1, r1);
Assert.AreEqual(1, c.GetDuplicateCount());
c.Insert(k1, r2, HamConst.HAM_DUPLICATE);
Assert.AreEqual(2, c.GetDuplicateCount());
c.Insert(k1, r3, HamConst.HAM_DUPLICATE);
Assert.AreEqual(3, c.GetDuplicateCount());
c.Erase();
c.MoveFirst();
Assert.AreEqual(2, c.GetDuplicateCount());
}
private void ApproxMatching()
{
Hamster.Environment env = new Hamster.Environment();
Database db = new Database();
byte[] k1 = new byte[5];
byte[] r1 = new byte[5];
k1[0] = 1; r1[0] = 1;
byte[] k2 = new byte[5];
byte[] r2 = new byte[5];
k2[0] = 2; r2[0] = 2;
byte[] k3 = new byte[5];
byte[] r3 = new byte[5];
k3[0] = 3; r3[0] = 3;
try
{
env.Create("ntest.db");
db = env.CreateDatabase(1);
db.Insert(k1, r1);
db.Insert(k2, r2);
db.Insert(k3, r3);
Cursor c = new Cursor(db);
byte[] r = c.Find(k2, HamConst.HAM_FIND_GT_MATCH);
checkEqual(r, r3);
checkEqual(k2, k3);
k2[0] = 2;
r = c.Find(k2, HamConst.HAM_FIND_GT_MATCH);
checkEqual(r, r1);
checkEqual(k2, k1);
db.Close();
env.Close();
}
catch (DatabaseException e)
{
Assert.Fail("unexpected exception " + e);
}
}
public void Run()
{
Console.WriteLine("CursorTest.Create");
SetUp();
Create();
TearDown();
Console.WriteLine("CursorTest.Clone");
SetUp();
Clone();
TearDown();
Console.WriteLine("CursorTest.Move");
SetUp();
Move();
TearDown();
Console.WriteLine("CursorTest.MoveNegative");
SetUp();
MoveNegative();
TearDown();
Console.WriteLine("CursorTest.MoveFirst");
SetUp();
MoveFirst();
TearDown();
Console.WriteLine("CursorTest.MoveLast");
SetUp();
MoveLast();
TearDown();
Console.WriteLine("CursorTest.MoveNext");
SetUp();
MoveNext();
TearDown();
Console.WriteLine("CursorTest.MovePrevious");
SetUp();
MovePrevious();
TearDown();
Console.WriteLine("CursorTest.GetKey");
SetUp();
GetKey();
TearDown();
Console.WriteLine("CursorTest.GetRecord");
SetUp();
GetRecord();
TearDown();
Console.WriteLine("CursorTest.Find");
SetUp();
Find();
TearDown();
Console.WriteLine("CursorTest.TryFind");
SetUp();
TryFind();
TearDown();
Console.WriteLine("CursorTest.Insert");
SetUp();
Insert();
TearDown();
Console.WriteLine("CursorTest.InsertDuplicate");
SetUp();
InsertDuplicate();
TearDown();
Console.WriteLine("CursorTest.InsertNegative");
SetUp();
InsertNegative();
TearDown();
Console.WriteLine("CursorTest.Erase");
SetUp();
Erase();
TearDown();
Console.WriteLine("CursorTest.EraseNegative");
SetUp();
EraseNegative();
TearDown();
Console.WriteLine("CursorTest.GetDuplicateCount");
SetUp();
GetDuplicateCount();
TearDown();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.