context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ICSharpCode.WpfDesign.XamlDom
{
public static class XamlFormatter
{
public static char IndentChar = ' ';
public static int Indenation = 2;
public static int LengthBeforeNewLine = 60;
static StringBuilder sb;
static int currentColumn;
static int nextColumn;
static int lineNumber;
public static string Format(string xaml)
{
Dictionary<XamlElementLineInfo, XamlElementLineInfo> dict;
return Format(xaml, out dict);
}
public static string Format(string xaml, out Dictionary<XamlElementLineInfo, XamlElementLineInfo> mappingOldNewLineInfo)
{
sb = new StringBuilder();
lineNumber = 1;
mappingOldNewLineInfo = new Dictionary<XamlElementLineInfo, XamlElementLineInfo>();
currentColumn = 0;
nextColumn = 0;
try {
var doc = XDocument.Parse(xaml, LoadOptions.SetLineInfo);
WalkContainer(doc, mappingOldNewLineInfo);
return sb.ToString();
}
catch {
return xaml;
}
}
static void WalkContainer(XContainer node, Dictionary<XamlElementLineInfo, XamlElementLineInfo> mappingOldNewLineInfo)
{
foreach (var c in node.Nodes()) {
if (c is XElement) {
WalkElement(c as XElement, mappingOldNewLineInfo);
} else {
NewLine();
Append(c.ToString().Trim());
}
}
}
static void WalkElement(XElement e, Dictionary<XamlElementLineInfo, XamlElementLineInfo> mappingOldNewLineInfo)
{
var info = (IXmlLineInfo)e;
var newLineInfo = new XamlElementLineInfo(lineNumber, currentColumn);
mappingOldNewLineInfo.Add(new XamlElementLineInfo(info.LineNumber, info.LinePosition), newLineInfo);
NewLine();
var defaultNs = e.GetDefaultNamespace();
string prefix1 = null;
if (defaultNs != e.Name.Namespace)
prefix1 = e.GetPrefixOfNamespace(e.Name.Namespace);
string name1 = prefix1 == null ? e.Name.LocalName : prefix1 + ":" + e.Name.LocalName;
newLineInfo.Position = sb.Length;
Append("<" + name1);
List<AttributeString> list = new List<AttributeString>();
int length = name1.Length;
foreach (var a in e.Attributes()) {
string prefix2 = null;
if (defaultNs != a.Name.Namespace)
prefix2 = e.GetPrefixOfNamespace(a.Name.Namespace);
var g = new AttributeString() { Name = a.Name, Prefix = prefix2, Value = a.Value };
list.Add(g);
length += g.FinalString.Length;
}
list.Sort(AttributeComparrer.Instance);
if (length > LengthBeforeNewLine) {
nextColumn = currentColumn + 1;
for (int i = 0; i < list.Count; i++) {
if (i > 0) {
NewLine();
}
else {
Append(" ");
}
Append(list[i].FinalString);
}
nextColumn -= name1.Length + 2;
}
else {
foreach (var a in list) {
Append(" " + a.FinalString);
}
}
if (e.Nodes().Count() > 0) {
Append(">");
nextColumn += Indenation;
WalkContainer(e, mappingOldNewLineInfo);
nextColumn -= Indenation;
NewLine();
Append("</" + name1 + ">");
}
else {
Append(" />");
}
newLineInfo.Length = sb.Length - newLineInfo.Position;
}
static void NewLine()
{
if (sb.Length > 0)
{
lineNumber++;
sb.AppendLine();
sb.Append(new string(' ', nextColumn));
currentColumn = nextColumn;
}
}
static void Append(string s)
{
sb.Append(s);
currentColumn += s.Length;
}
enum AttributeLayout
{
X,
XmlnsMicrosoft,
Xmlns,
XmlnsWithClr,
SpecialOrder,
ByName,
Attached,
WithPrefix
}
class AttributeString
{
public XName Name;
public string Prefix;
public string Value;
public string LocalName {
get { return Name.LocalName; }
}
public string FinalName {
get {
return Prefix == null ? Name.LocalName : Prefix + ":" + Name.LocalName;
}
}
public string FinalString {
get {
return FinalName + "=\"" + Value + "\"";
}
}
public AttributeLayout GetAttributeLayout()
{
if (Prefix == "xmlns" || LocalName == "xmlns") {
if (Value.StartsWith("http://schemas.microsoft.com")) return AttributeLayout.XmlnsMicrosoft;
if (Value.StartsWith("clr")) return AttributeLayout.XmlnsWithClr;
return AttributeLayout.Xmlns;
}
if (Prefix == "x") return AttributeLayout.X;
if (Prefix != null) return AttributeLayout.WithPrefix;
if (LocalName.Contains(".")) return AttributeLayout.Attached;
if (AttributeComparrer.SpecialOrder.Contains(LocalName)) return AttributeLayout.SpecialOrder;
return AttributeLayout.ByName;
}
}
class AttributeComparrer : IComparer<AttributeString>
{
public static AttributeComparrer Instance = new AttributeComparrer();
public int Compare(AttributeString a1, AttributeString a2)
{
var y1 = a1.GetAttributeLayout();
var y2 = a2.GetAttributeLayout();
if (y1 == y2) {
if (y1 == AttributeLayout.SpecialOrder) {
return
Array.IndexOf(SpecialOrder, a1.LocalName).CompareTo(
Array.IndexOf(SpecialOrder, a2.LocalName));
}
return a1.FinalName.CompareTo(a2.FinalName);
}
return y1.CompareTo(y2);
}
public static string[] SpecialOrder = new string[] {
"Name",
"Content",
"Command",
"Executed",
"CanExecute",
"Width",
"Height",
"Margin",
"HorizontalAlignment",
"VerticalAlignment",
"HorizontalContentAlignment",
"VerticalContentAlignment",
"StartPoint",
"EndPoint",
"Offset",
"Color"
};
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using EggsAndHoney.WebApi.ViewModels;
using Newtonsoft.Json;
using Xunit;
namespace EggsAndHoney.WebApi.Tests
{
public class OrdersTests : OrdersApiTestBase
{
[Fact]
public async Task GettingAllOrders_ShouldReturnNonEmptyData()
{
var response = await _client.GetAsync(_ordersEndpoint);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
Assert.NotEmpty(responseString);
}
[Fact]
public async Task AddedOrder_ShouldBeInTheList_FetchedByGet()
{
var orderName = Guid.NewGuid().ToString();
var orderType = "Eggs";
var addedOrderId = await AddOrderAndGetId(orderName, orderType);
var fetchedOrders = await GetOrders();
AssertOrderIsInList(fetchedOrders, addedOrderId, orderName, orderType);
}
[Fact]
public async Task ResolvedOrder_ShouldDisappearFromOrderList_AndAppearInResolvedList()
{
var orderName = Guid.NewGuid().ToString();
var orderType = "Honey";
var addedOrderId = await AddOrderAndGetId(orderName, orderType);
var resolvedOrderId = await ResolveOrderAndGetId(addedOrderId);
var fetchedOrders = await GetOrders();
var fetchedResolvedOrders = await GetResolvedOrders();
AssertOrderIsNotInList(fetchedOrders, addedOrderId, orderName, orderType);
AssertResolvedOrderIsInList(fetchedResolvedOrders, resolvedOrderId, orderName, orderType);
}
[Fact]
public async Task UnresolvedOrder_ShouldDisappearFromResolvedOrderList_AndAppearInOrderList()
{
var orderName = Guid.NewGuid().ToString();
var orderType = "Eggs";
var addedOrderId = await AddOrderAndGetId(orderName, orderType);
var resolvedOrderId = await ResolveOrderAndGetId(addedOrderId);
var unresolvedOrderId = await UnresolveOrderAndGetId(resolvedOrderId);
var fetchedOrders = await GetOrders();
var fetchedResolvedOrders = await GetResolvedOrders();
AssertResolvedOrderIsNotInList(fetchedResolvedOrders, resolvedOrderId, orderName, orderType);
AssertOrderIsInList(fetchedOrders, unresolvedOrderId, orderName, orderType);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(5)]
[InlineData(10)]
public async Task OrdersCount_ShouldIncreaseBy_TheNumberOfAddedOrders(int numberOfOrdersToAdd)
{
var initialNumberOfOrders = await GetOrdersCount();
for (var i = 0; i < numberOfOrdersToAdd; i++)
{
var orderName = Guid.NewGuid().ToString();
var orderType = "Eggs";
await AddOrderAndGetId(orderName, orderType);
}
var finalNumberOfOrders = await GetOrdersCount();
var numberOfAddedOrders = finalNumberOfOrders - initialNumberOfOrders;
Assert.Equal(numberOfOrdersToAdd, numberOfAddedOrders);
}
[Fact]
public async Task GetOrders_ShouldReturnOrders_OrderedByDate()
{
var numberOfOrdersToAdd = 10;
for (var i = 0; i < numberOfOrdersToAdd; i++)
{
var orderName = Guid.NewGuid().ToString();
var orderType = "Honey";
await AddOrderAndGetId(orderName, orderType);
}
var fetchedOrders = await GetOrders();
var fetchedOrdersInExpectedOrder = fetchedOrders.OrderBy(o => o.DatePlaced).ToList();
Assert.Equal(fetchedOrdersInExpectedOrder, fetchedOrders);
}
[Fact]
public async Task GetResolvedOrders_ShouldReturnOrders_OrderedByDate()
{
var numberOfOrdersToAdd = 10;
var addedOrderIds = new List<int>();
for (var i = 0; i < numberOfOrdersToAdd; i++)
{
var orderName = Guid.NewGuid().ToString();
var orderType = "Eggs";
var addedOrderId = await AddOrderAndGetId(orderName, orderType);
addedOrderIds.Add(addedOrderId);
}
// Resolve orders in reverse order just to make sure they are not sorted by datePlaced on the server
for (var i = addedOrderIds.Count() - 1; i >= 0; i--)
{
await ResolveOrderAndGetId(addedOrderIds[i]);
}
var fetchedResolvedOrders = await GetResolvedOrders();
var fetchedResolvedOrdersInExpectedOrder = fetchedResolvedOrders.OrderByDescending(o => o.DateResolved).ToList();
Assert.Equal(fetchedResolvedOrdersInExpectedOrder, fetchedResolvedOrders);
}
/* Helper methods */
private void AssertOrderIsNotInList(IList<OrderViewModel> orderList, int id, string name, string order)
{
Assert.False(orderList.Any(o => o.Id == id && o.Name == name && o.Order == order));
}
private void AssertOrderIsInList(IList<OrderViewModel> orderList, int id, string name, string order)
{
Assert.True(orderList.Single(o => o.Name == name && o.Order == order).Id == id);
}
private void AssertResolvedOrderIsNotInList(IList<ResolvedOrderViewModel> resolvedOrderList, int id, string name, string order)
{
Assert.False(resolvedOrderList.Any(o => o.Id == id && o.Name == name && o.Order == order));
}
private void AssertResolvedOrderIsInList(IList<ResolvedOrderViewModel> resolvedOrderList, int id, string name, string order)
{
Assert.True(resolvedOrderList.Single(o => o.Name == name && o.Order == order).Id == id);
}
private async Task<int> AddOrderAndGetId(string name, string order)
{
var jsonString = JsonConvert.SerializeObject(new { name, order });
var postContent = new StringContent(jsonString, _defaultEncoding, __postContentType);
var response = await _client.PostAsync(_addOrderEndpoint, postContent);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
var createdOrderViewModel = JsonConvert.DeserializeObject<dynamic>(responseBody);
return createdOrderViewModel.id;
}
private async Task<int> ResolveOrderAndGetId(int id)
{
var jsonString = JsonConvert.SerializeObject(new { id });
var postContent = new StringContent(jsonString, _defaultEncoding, __postContentType);
var response = await _client.PostAsync(_resolveOrderEndpoint, postContent);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
var resolvedOrderViewModel = JsonConvert.DeserializeObject<ResolvedOrderViewModel>(responseBody);
return resolvedOrderViewModel.Id;
}
private async Task<int> UnresolveOrderAndGetId(int id)
{
var jsonString = JsonConvert.SerializeObject(new { id });
var postContent = new StringContent(jsonString, _defaultEncoding, __postContentType);
var response = await _client.PostAsync(_unresolveOrderEndpoint, postContent);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
var unresolvedOrderViewModel = JsonConvert.DeserializeObject<OrderViewModel>(responseBody);
return unresolvedOrderViewModel.Id;
}
private async Task<IList<OrderViewModel>> GetOrders()
{
var getResponse = await _client.GetAsync(_ordersEndpoint);
getResponse.EnsureSuccessStatusCode();
var responseString = await getResponse.Content.ReadAsStringAsync();
var fetchedOrderCollectionViewModel = JsonConvert.DeserializeObject<ItemCollectionResponseViewModel<OrderViewModel>>(responseString);
return fetchedOrderCollectionViewModel.Items;
}
private async Task<IList<ResolvedOrderViewModel>> GetResolvedOrders()
{
var getResponse = await _client.GetAsync(_resolvedOrdersEndpoint);
getResponse.EnsureSuccessStatusCode();
var responseString = await getResponse.Content.ReadAsStringAsync();
var fetchedOrderCollectionViewModel = JsonConvert.DeserializeObject<ItemCollectionResponseViewModel<ResolvedOrderViewModel>>(responseString);
return fetchedOrderCollectionViewModel.Items;
}
private async Task<int> GetOrdersCount()
{
var getResponse = await _client.GetAsync(_ordersCountEndpoint);
getResponse.EnsureSuccessStatusCode();
var responseString = await getResponse.Content.ReadAsStringAsync();
var itemCountResponseViewModel = JsonConvert.DeserializeObject<ItemCountResponseViewModel>(responseString);
return itemCountResponseViewModel.Count;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
namespace Trionic5Tools
{
public class Trionic5Properties : IECUProperties
{
// contains all firmware options for Trionic 5!
private DateTime m_syncDateTime = DateTime.MinValue;
[Category("Car"), Description("Determines when the last synchronization between file and ECU was done")]
public override DateTime SyncDateTime
{
get
{
return m_syncDateTime;
}
set
{
m_syncDateTime = value;
}
}
private int _hardcodedRPMLimit = 7500;
public int HardcodedRPMLimit
{
get { return _hardcodedRPMLimit; }
set { _hardcodedRPMLimit = value; }
}
private bool m_Afterstartenrichment = false; // byte 0 - bit 1
/// <summary>
/// Determines whether or not enrichment after starting should be enabled
/// </summary>
[Category("Enrichment"), Description("Determines whether or not enrichment after starting should be enabled")]
public override bool Afterstartenrichment
{
get { return m_Afterstartenrichment; }
set { m_Afterstartenrichment = value; }
}
private bool m_WOTenrichment = false; // byte 0 - bit 2
[Category("Enrichment"), Description("Determines whether or not enrichment should occur at wide open throttle")]
public override bool WOTenrichment
{
get { return m_WOTenrichment; }
set { m_WOTenrichment = value; }
}
private bool m_Interpolationofdelay = false; // byte 0 - bit 3
[Category("Misc"), Description("Interpolation of delay parameter")]
public override bool Interpolationofdelay
{
get { return m_Interpolationofdelay; }
set { m_Interpolationofdelay = value; }
}
private bool m_Temperaturecompensation = false; // byte 0 - bit 4
[Category("Temperature"), Description("Determines whether or not the system should correct for temperatures")]
public override bool Temperaturecompensation
{
get { return m_Temperaturecompensation; }
set { m_Temperaturecompensation = value; }
}
private bool m_Lambdacontrol = false; // byte 0 - bit 5
[Category("Lambda control"), Description("Turns lambda control on/off")]
public override bool Lambdacontrol
{
get { return m_Lambdacontrol; }
set { m_Lambdacontrol = value; }
}
private bool m_Adaptivity = false; // byte 0 - bit 6
[Category("Adaption"), Description("Turns fuel adaption on/off")]
public override bool Adaptivity
{
get { return m_Adaptivity; }
set { m_Adaptivity = value; }
}
private bool m_Idlecontrol = false; // byte 0 - bit 7
[Category("Idle"), Description("Turns specific idle control on/off")]
public override bool Idlecontrol
{
get { return m_Idlecontrol; }
set { m_Idlecontrol = value; }
}
private bool m_Enrichmentduringstart = false; // byte 0 - bit 8
[Category("Enrichment"), Description("Turns enrichment during start (cranking) on/off")]
public override bool Enrichmentduringstart
{
get { return m_Enrichmentduringstart; }
set { m_Enrichmentduringstart = value; }
}
private bool m_ConstantinjectiontimeE51 = false; // byte 1 - bit 1
[Category("Fuelling"), Description("Turns a constant injection time on/off")]
public override bool ConstantinjectiontimeE51
{
get { return m_ConstantinjectiontimeE51; }
set { m_ConstantinjectiontimeE51 = value; }
}
private bool m_Lambdacontrolduringtransients = false; // byte 1 - bit 2
[Category("Lambda control"), Description("Turns closed loop control during transients on/off")]
public override bool Lambdacontrolduringtransients
{
get { return m_Lambdacontrolduringtransients; }
set { m_Lambdacontrolduringtransients = value; }
}
private bool m_Fuelcut = false; // byte 1 - bit 3
[Category("Fuelling"), Description("Turns fuel cut during engine braking on/off")]
public override bool Fuelcut
{
get { return m_Fuelcut; }
set { m_Fuelcut = value; }
}
private bool m_Constantinjtimeduringidle = false; // byte 1 - bit 4
[Category("Idle"), Description("Turns the constant injection time during idle on/off")]
public override bool Constantinjtimeduringidle
{
get { return m_Constantinjtimeduringidle; }
set { m_Constantinjtimeduringidle = value; }
}
private bool m_Accelerationsenrichment = false; // byte 1 - bit 5
[Category("Enrichment"), Description("Turns enrichment during acceleration on/off")]
public override bool Accelerationsenrichment
{
get { return m_Accelerationsenrichment; }
set { m_Accelerationsenrichment = value; }
}
private bool m_Decelerationsenleanment = false; // byte 1 - bit 6
[Category("Enrichment"), Description("Turns enleanment during deceleration on/off")]
public override bool Decelerationsenleanment
{
get { return m_Decelerationsenleanment; }
set { m_Decelerationsenleanment = value; }
}
private bool m_Car104 = false; // byte 1 - bit 7
[Category("Misc"), Description("Car104")]
public override bool Car104
{
get { return m_Car104; }
set { m_Car104 = value; }
}
private bool m_Adaptivitywithclosedthrottle = false; // byte 1 - bit 8
[Category("Adaption"), Description("Turns adaption during closed throttle plate on/off")]
public override bool Adaptivitywithclosedthrottle
{
get { return m_Adaptivitywithclosedthrottle; }
set { m_Adaptivitywithclosedthrottle = value; }
}
private bool m_Factortolambdawhenthrottleopening = false; // byte 2 - bit 1
[Category("Lambda control"), Description("Turns an allowed correction factor during the opening of the throttle plate to the lambda controller on/off")]
public override bool Factortolambdawhenthrottleopening
{
get { return m_Factortolambdawhenthrottleopening; }
set { m_Factortolambdawhenthrottleopening = value; }
}
private bool m_Usesseparateinjmapduringidle = false; // byte 2 - bit 2
[Category("Idle"), Description("Turns the usage of the idle fuel map on/off")]
public override bool Usesseparateinjmapduringidle
{
get { return m_Usesseparateinjmapduringidle; }
set { m_Usesseparateinjmapduringidle = value; }
}
private bool m_FactortolambdawhenACisengaged = false; // byte 2 - bit 3
[Category("Lambda control"), Description("Turns an allowed correction factor whilst the airco is engaged to the lambda controller on/off")]
public override bool FactortolambdawhenACisengaged
{
get { return m_FactortolambdawhenACisengaged; }
set { m_FactortolambdawhenACisengaged = value; }
}
private bool m_ThrottleAccRetadjustsimultMY95 = false; // byte 2 - bit 4
[Category("Misc"), Description("Unknown test option")]
public override bool ThrottleAccRetadjustsimultMY95
{
get { return m_ThrottleAccRetadjustsimultMY95; }
set { m_ThrottleAccRetadjustsimultMY95 = value; }
}
private bool m_Fueladjustingduringidle = false; // byte 2 - bit 5
[Category("Adaption"), Description("Turns fuel adaption during idle on/off")]
public override bool Fueladjustingduringidle
{
get { return m_Fueladjustingduringidle; }
set { m_Fueladjustingduringidle = value; }
}
private bool m_Purge = false; // byte 2 - bit 6
[Category("Purge"), Description("Turns the purge option on/off")]
public override bool Purge
{
get { return m_Purge; }
set { m_Purge = value; }
}
private bool m_Adaptionofidlecontrol = false; // byte 2 - bit 7
[Category("Adaption"), Description("Turns adaptive behaviour for idle control on/off")]
public override bool Adaptionofidlecontrol
{
get { return m_Adaptionofidlecontrol; }
set { m_Adaptionofidlecontrol = value; }
}
private bool m_Lambdacontrolduringidle = false; // byte 2 - bit 8
[Category("Lambda control"), Description("Turns closed loop control during idle on/off")]
public override bool Lambdacontrolduringidle
{
get { return m_Lambdacontrolduringidle; }
set { m_Lambdacontrolduringidle = value; }
}
private bool m_Heatedplates = false; // byte 3 - bit 1
[Category("Car"), Description("Turns correction factor for cars with heatplates on/off")]
public override bool Heatedplates
{
get { return m_Heatedplates; }
set { m_Heatedplates = value; }
}
private bool m_AutomaticTransmission = false; // byte 3 - bit 2
[Category("Car"), Description("Indicates whether the car has an automatic gearbox or not")]
public override bool AutomaticTransmission
{
get { return m_AutomaticTransmission; }
set { m_AutomaticTransmission = value; }
}
private bool m_Loadcontrol = false; // byte 3 - bit 3
[Category("Fuelling"), Description("Turns correction factor for load changes on/off")]
public override bool Loadcontrol
{
get { return m_Loadcontrol; }
set { m_Loadcontrol = value; }
}
private bool m_ETS = false; // byte 3 - bit 4
[Category("Car"), Description("Turns ETS (traction control) on/off")]
public override bool ETS
{
get { return m_ETS; }
set { m_ETS = value; }
}
private bool m_APCcontrol = false; // byte 3 - bit 5
[Category("Boost"), Description("Turns boost control on/off")]
public override bool APCcontrol
{
get { return m_APCcontrol; }
set { m_APCcontrol = value; }
}
private bool m_Higheridleduringstart = false; // byte 3 - bit 6
[Category("Idle"), Description("Turns a higher engine speed during starting on/off")]
public override bool Higheridleduringstart
{
get { return m_Higheridleduringstart; }
set { m_Higheridleduringstart = value; }
}
private bool m_Globaladaption = false; // byte 3 - bit 7
[Category("Adaption"), Description("Turns global fuel adaption on/off")]
public override bool Globaladaption
{
get { return m_Globaladaption; }
set { m_Globaladaption = value; }
}
private bool m_Tempcompwithactivelambdacontrol = false; // byte 3 - bit 8
[Category("Temperature"), Description("Turns temperature correction in closed loop on/off")]
public override bool Tempcompwithactivelambdacontrol
{
get { return m_Tempcompwithactivelambdacontrol; }
set { m_Tempcompwithactivelambdacontrol = value; }
}
private bool m_Loadbufferduringidle = false; // byte 4 - bit 1
[Category("Idle"), Description("Turns load buffering during idle on/off")]
public override bool Loadbufferduringidle
{
get { return m_Loadbufferduringidle; }
set { m_Loadbufferduringidle = value; }
}
private bool m_Constidleignangleduringgearoneandtwo = false;// byte 4 - bit 2
[Category("Ignition"), Description("Turns a constant ignition advance during first and second gear on/off")]
public override bool Constidleignangleduringgearoneandtwo
{
get { return m_Constidleignangleduringgearoneandtwo; }
set { m_Constidleignangleduringgearoneandtwo = value; }
}
private bool m_NofuelcutR12 = false; // byte 4 - bit 3
[Category("Fuelling"), Description("Turns the fuelcut in engine braking function during reverse, first and second gear on/off")]
public override bool NofuelcutR12
{
get { return m_NofuelcutR12; }
set { m_NofuelcutR12 = value; }
}
private bool m_Airpumpcontrol = false; // byte 4 - bit 4
[Category("Airpump"), Description("Turns the airpump control on/off")]
public override bool Airpumpcontrol
{
get { return m_Airpumpcontrol; }
set { m_Airpumpcontrol = value; }
}
private bool m_Normalasperatedengine = false; // byte 4 - bit 5
[Category("Car"), Description("Indicates whether the car is turbocharged or N/A")]
public override bool Normalasperatedengine
{
get { return m_Normalasperatedengine; }
set { m_Normalasperatedengine = value; }
}
private bool m_Knockregulatingdisabled = false; // byte 4 - bit 6
[Category("Knock"), Description("Turns knock control on/off")]
public override bool Knockregulatingdisabled
{
get { return m_Knockregulatingdisabled; }
set { m_Knockregulatingdisabled = value; }
}
private bool m_Constantangle = false; // byte 4 - bit 7
[Category("Misc"), Description("Constantangle")]
public override bool Constantangle
{
get { return m_Constantangle; }
set { m_Constantangle = value; }
}
private bool m_PurgevalveMY94 = false; // byte 4 - bit 8
[Category("Purge"), Description("Turns the purge specific function for MY94 cars on/off")]
public override bool PurgevalveMY94
{
get { return m_PurgevalveMY94; }
set { m_PurgevalveMY94 = value; }
}
private string m_VSSCode = string.Empty;
[Category("VSS/Immo"), Description("The VSS (Vehicle Security System) for the car")]
public override string VSSCode
{
get { return m_VSSCode; }
set { m_VSSCode = value; }
}
private bool m_HasVSSProperties = false;
[Category("Misc"), Description("Binary has VSS options")]
public override bool HasVSSOptions
{
get { return m_HasVSSProperties; }
set { m_HasVSSProperties = value; }
}
private bool m_IsExtendedProperties = false;
[Category("Misc"), Description("Binary has extended options")]
public override bool ExtendedProgramModeOptions
{
get { return m_IsExtendedProperties; }
set { m_IsExtendedProperties = value; }
}
private bool m_tank_diagnosticsactive = false;
[Category("Diagnostics"), Description("Turns Fuel tank pressure diagnostics on/off")]
public bool Tank_diagnosticsactive
{
get { return m_tank_diagnosticsactive; }
set { m_tank_diagnosticsactive = value; }
}
private bool m_vssactive = false;
[Category("VSS/Immo"), Description("Turns VSS (Vehicle Security System) on/off")]
public override bool VSSactive
{
get { return m_vssactive; }
set { m_vssactive = value; }
}
private string m_carmodel = string.Empty;
[Category("Car"), Description("The description of the car model")]
public override string Carmodel
{
get { return m_carmodel; }
set { m_carmodel = value; }
}
private string m_enginetype = string.Empty;
[Category("Car"), Description("The description of the engine type")]
public override string Enginetype
{
get { return m_enginetype; }
set { m_enginetype = value; }
}
private InjectorType m_injectorType = InjectorType.Stock;
[Category("Car"), Description("Injector type")]
public override InjectorType InjectorType
{
get { return m_injectorType; }
set { m_injectorType = value; }
}
private MapSensorType m_mapsensorType = MapSensorType.MapSensor25;
[Category("Car"), Description("Mapsensor type")]
public override MapSensorType MapSensorType
{
get { return m_mapsensorType; }
set { m_mapsensorType = value; }
}
private TuningStage _tuningStage = TuningStage.Stock;
[Category("Car"), Description("Tuning stage")]
public override TuningStage TuningStage
{
get { return _tuningStage; }
set { _tuningStage = value; }
}
private TurboType m_turboType = TurboType.Stock;
[Category("Car"), Description("Turbo type")]
public override TurboType TurboType
{
get { return m_turboType; }
set { m_turboType = value; }
}
private string m_partnumber = string.Empty;
[Category("ECU"), Description("The partnumber associated with this binary file")]
public override string Partnumber
{
get { return m_partnumber; }
set { m_partnumber = value; }
}
private string m_softwareID = string.Empty;
[Category("ECU"), Description("The software ID associated with this binary file")]
public override string SoftwareID
{
get { return m_softwareID; }
set { m_softwareID = value; }
}
private string m_dataname = string.Empty;
[Category("ECU"), Description("The dataname associated with this binary file")]
public override string Dataname
{
get { return m_dataname; }
set { m_dataname = value; }
}
private string m_CPUspeed = string.Empty;
[Category("ECU"), Description("The processor speed this binary file initializes the ECU at")]
public override string CPUspeed
{
get { return m_CPUspeed; }
set { m_CPUspeed = value; }
}
private bool m_RAMlocked = false;
[Category("ECU"), Description("Determines whether or not the SRAM content can be altered through the canbus connection")]
public override bool RAMlocked
{
get { return m_RAMlocked; }
set { m_RAMlocked = value; }
}
private bool m_isTrionic55 = false;
[Category("ECU"), Description("Indicates whether the file is a Trionic 5.2 file or a Trionic 5.5 file")]
public override bool IsTrionic55
{
get { return m_isTrionic55; }
set { m_isTrionic55 = value; }
}
private bool m_SecondO2Enable = false;
[Category("Lambda control"), Description("Turns the control of the second (post cat) lambda sonde on/off")]
public override bool SecondO2Enable
{
get { return m_SecondO2Enable; }
set { m_SecondO2Enable = value; }
}
}
}
| |
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Firebase.Firestore.Internal;
using Firebase.Platform;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Firebase.Firestore {
using QuerySnapshotCallbackMap =
ListenerRegistrationMap<Action<QuerySnapshotProxy, FirestoreError, string>>;
/// <summary>
/// A query which you can read or listen to. You can also construct refined <c>Query</c> objects
/// by adding filters, ordering, and other constraints.
/// </summary>
/// <remarks>
/// <see cref="CollectionReference"/> derives from this class as a "return-all" query against the
/// collection it refers to.
/// </remarks>
public class Query {
// _proxy could be either QueryProxy or CollectionReferenceProxy type.
internal readonly QueryProxy _proxy;
private readonly FirebaseFirestore _firestore;
internal Query(QueryProxy proxy, FirebaseFirestore firestore) {
_proxy = Util.NotNull(proxy);
_firestore = Util.NotNull(firestore);
}
internal static void ClearCallbacksForOwner(FirebaseFirestore owner) {
snapshotListenerCallbacks.ClearCallbacksForOwner(owner);
}
/// <summary>
/// The Cloud Firestore instance associated with this query.
/// </summary>
public FirebaseFirestore Firestore {
get {
return _firestore;
}
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value should be equal to the specified value.
/// </summary>
/// <param name="fieldPath">The dot-separated field path to filter on. Must not be <c>null</c>
/// or empty.</param>
/// <param name="value">The value to compare in the filter.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereEqualTo(string fieldPath, object value) {
Preconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereEqualTo(fieldPath, ValueSerializer.Serialize(SerializationContext.Default, value)), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value should be equal to the specified value.
/// </summary>
/// <param name="fieldPath">The field path to filter on. Must not be <c>null</c>.</param>
/// <param name="value">The value to compare in the filter.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereEqualTo(FieldPath fieldPath, object value) {
Preconditions.CheckNotNull(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereEqualTo(fieldPath.ConvertToProxy(),
ValueSerializer.Serialize(SerializationContext.Default, value)), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value should not equal the specified value.
///
/// A Query can have only one <c>WhereNotEqualTo()</c> filter, and it cannot be
/// combined with <c>WhereNotIn()</c>.
/// </summary>
/// <param name="fieldPath">The dot-separated field path to filter on. Must not be <c>null</c>
/// or empty.</param>
/// <param name="value">The value to compare in the filter.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereNotEqualTo(string fieldPath, object value) {
Preconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereNotEqualTo(fieldPath, ValueSerializer.Serialize(
SerializationContext.Default, value)),
Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value should not equal the specified value.
///
/// A Query can have only one <c>WhereNotEqualTo()</c> filter, and it cannot be
/// combined with <c>WhereNotIn()</c>.
/// </summary>
/// <param name="fieldPath">The field path to filter on. Must not be <c>null</c>.</param>
/// <param name="value">The value to compare in the filter.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereNotEqualTo(FieldPath fieldPath, object value) {
Preconditions.CheckNotNull(fieldPath, nameof(fieldPath));
return new Query(
_proxy.WhereNotEqualTo(fieldPath.ConvertToProxy(),
ValueSerializer.Serialize(SerializationContext.Default, value)),
Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value should be less than the specified value.
/// </summary>
/// <param name="fieldPath">The dot-separated field path to filter on. Must not be <c>null</c>
/// or empty.</param>
/// <param name="value">The value to compare in the filter.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereLessThan(string fieldPath, object value) {
Preconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereLessThan(fieldPath, ValueSerializer.Serialize(SerializationContext.Default, value)), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value should be less than the specified value.
/// </summary>
/// <param name="fieldPath">The field path to filter on. Must not be <c>null</c>.</param>
/// <param name="value">The value to compare in the filter.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereLessThan(FieldPath fieldPath, object value) {
Preconditions.CheckNotNull(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereLessThan(fieldPath.ConvertToProxy(),
ValueSerializer.Serialize(SerializationContext.Default, value)), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value should be less than or equal to the specified
/// value.
/// </summary>
/// <param name="fieldPath">The dot-separated field path to filter on. Must not be <c>null</c>
/// or empty.</param>
/// <param name="value">The value to compare in the filter.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereLessThanOrEqualTo(string fieldPath, object value) {
Preconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereLessThanOrEqualTo(fieldPath, ValueSerializer.Serialize(SerializationContext.Default, value)), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value should be less than or equal to the specified
/// value.
/// </summary>
/// <param name="fieldPath">The field path to filter on. Must not be <c>null</c>.</param>
/// <param name="value">The value to compare in the filter.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereLessThanOrEqualTo(FieldPath fieldPath, object value) {
Preconditions.CheckNotNull(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereLessThanOrEqualTo(fieldPath.ConvertToProxy(),
ValueSerializer.Serialize(SerializationContext.Default, value)), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value should be greater than the specified value.
/// </summary>
/// <param name="fieldPath">The dot-separated field path to filter on. Must not be <c>null</c>
/// or empty.</param>
/// <param name="value">The value to compare in the filter.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereGreaterThan(string fieldPath, object value) {
Preconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereGreaterThan(fieldPath, ValueSerializer.Serialize(SerializationContext.Default, value)), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value should be greater than the specified value.
/// </summary>
/// <param name="fieldPath">The field path to filter on. Must not be <c>null</c>.</param>
/// <param name="value">The value to compare in the filter.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereGreaterThan(FieldPath fieldPath, object value) {
Preconditions.CheckNotNull(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereGreaterThan(fieldPath.ConvertToProxy(),
ValueSerializer.Serialize(SerializationContext.Default, value)), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value should be greater than or equal to the specified
/// value.
/// </summary>
/// <param name="fieldPath">The dot-separated field path to filter on. Must not be <c>null</c>
/// or empty.</param>
/// <param name="value">The value to compare in the filter.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereGreaterThanOrEqualTo(string fieldPath, object value) {
Preconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereGreaterThanOrEqualTo(fieldPath, ValueSerializer.Serialize(SerializationContext.Default, value)), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value should be greater than or equal to the specified
/// value.
/// </summary>
/// <param name="fieldPath">The field path to filter on. Must not be <c>null</c>.</param>
/// <param name="value">The value to compare in the filter.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereGreaterThanOrEqualTo(FieldPath fieldPath, object value) {
Preconditions.CheckNotNull(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereGreaterThanOrEqualTo(fieldPath.ConvertToProxy(),
ValueSerializer.Serialize(SerializationContext.Default, value)), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field, the value must be an array, and that the array must contain
/// the provided value.
///
/// A Query can have only one <c>WhereArrayContains()</c> filter and it cannot be combined
/// with <c>WhereArrayContainsAny()</c>.
/// </summary>
/// <param name="fieldPath">The name of the fields containing an array to search</param>
/// <param name="value">The value that must be contained in the array.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereArrayContains(FieldPath fieldPath, object value) {
Preconditions.CheckNotNull(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereArrayContains(fieldPath.ConvertToProxy(),
ValueSerializer.Serialize(SerializationContext.Default, value)), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field, the value must be an array, and that the array must contain
/// the provided value.
///
/// A <c>Query</c> can have only one <c>WhereArrayContains()</c> filter and it cannot be
/// combined with <c>WhereArrayContainsAny()</c>.
/// </summary>
/// <param name="fieldPath">The dot-separated field path to filter on. Must not be <c>null</c>
/// or empty.</param>
/// <param name="value">The value that must be contained in the array.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereArrayContains(string fieldPath, object value) {
Preconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath));
return new Query(_proxy.WhereArrayContains(fieldPath,
ValueSerializer.Serialize(SerializationContext.Default, value)), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must contain
/// the specified field, the value must be an array, and that the array must contain at least one
/// value from the provided list.
///
/// A <c>Query</c> can have only one <c>WhereArrayContainsAny()</c> filter and it cannot be
/// combined with <c>WhereArrayContains()</c> or <c>WhereIn()</c>.
/// </summary>
/// <param name="fieldPath">The name of the fields containing an array to search.</param>
/// <param name="values">The list that contains the values to match.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereArrayContainsAny(FieldPath fieldPath, IEnumerable<object> values) {
Preconditions.CheckNotNull(fieldPath, nameof(fieldPath));
Preconditions.CheckNotNull(values, nameof(values));
var array = ValueSerializer.Serialize(SerializationContext.Default, values);
var query = FirestoreCpp.QueryWhereArrayContainsAny(_proxy, fieldPath.ConvertToProxy(), array);
return new Query(query, Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must contain
/// the specified field, the value must be an array, and that the array must contain at least one
/// value from the provided list.
///
/// A <c>Query</c> can have only one <c>WhereArrayContainsAny()</c> filter and it cannot be
/// combined with <c>WhereArrayContains()</c> or <c>WhereIn()</c>.
/// </summary>
/// <param name="fieldPath">The dot-separated field path to filter on. Must not be <c>null</c>
/// or empty.</param>
/// <param name="values">The list that contains the values to match.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereArrayContainsAny(string fieldPath, IEnumerable<object> values) {
Preconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath));
Preconditions.CheckNotNull(values, nameof(values));
var array = ValueSerializer.Serialize(SerializationContext.Default, values);
var query = FirestoreCpp.QueryWhereArrayContainsAny(_proxy, fieldPath, array);
return new Query(query, Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value must equal one of the values from the
/// provided list.
///
/// A <c>Query</c> can have only one <c>WhereIn()</c> filter and it cannot be combined
/// with <c>WhereArrayContainsAny()</c>.
/// </summary>
/// <param name="fieldPath">The name of the fields containing an array to search.</param>
/// <param name="values">The list that contains the values to match.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereIn(FieldPath fieldPath, IEnumerable<object> values) {
Preconditions.CheckNotNull(fieldPath, nameof(fieldPath));
Preconditions.CheckNotNull(values, nameof(values));
var array = ValueSerializer.Serialize(SerializationContext.Default, values);
var query = FirestoreCpp.QueryWhereIn(_proxy, fieldPath.ConvertToProxy(), array);
return new Query(query, Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value must equal one of the values from the
/// provided list.
///
/// A <c>Query</c> can have only one <c>WhereIn()</c> filter and it cannot be combined
/// with <c>WhereArrayContainsAny()</c>.
/// </summary>
/// <param name="fieldPath">The dot-separated field path to filter on. Must not be <c>null</c>
/// or empty.</param>
/// <param name="values">The list that contains the values to match.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereIn(string fieldPath, IEnumerable<object> values) {
Preconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath));
Preconditions.CheckNotNull(values, nameof(values));
var array = ValueSerializer.Serialize(SerializationContext.Default, values);
var query = FirestoreCpp.QueryWhereIn(_proxy, fieldPath, array);
return new Query(query, Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value must not equal any value from the
/// provided list.
///
/// One special case is that <c>WhereNotIn</c> cannot match null values. To query for
/// documents where a field exists and is null, use <c>WhereNotEqualTo</c>, which can handle
/// this special case.
///
/// A <c>Query</c> can have only one <c>WhereNotIn()</c> filter, and it cannot be
/// combined with <c>WhereArrayContains()</c>, <c>WhereArrayContainsAny()</c>,
/// <c>WhereIn()</c>, or <c>WhereNotEqualTo()</c>.
/// </summary>
/// <param name="fieldPath">The name of the fields containing an array to search.</param>
/// <param name="values">The list that contains the values to match.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereNotIn(FieldPath fieldPath, IEnumerable<object> values) {
Preconditions.CheckNotNull(fieldPath, nameof(fieldPath));
Preconditions.CheckNotNull(values, nameof(values));
var array = ValueSerializer.Serialize(SerializationContext.Default, values);
var query = FirestoreCpp.QueryWhereNotIn(_proxy, fieldPath.ConvertToProxy(), array);
return new Query(query, Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> with the additional filter that documents must
/// contain the specified field and the value must not equal any value from the
/// provided list.
///
/// One special case is that <c>WhereNotIn</c> cannot match null values. To query for
/// documents where a field exists and is null, use <c>WhereNotEqualTo</c>, which can handle
/// this special case.
///
/// A <c>Query</c> can have only one <c>WhereNotIn()</c> filter, and it cannot be
/// combined with <c>WhereArrayContains()</c>, <c>WhereArrayContainsAny()</c>,
/// <c>WhereIn()</c>, or <c>WhereNotEqualTo()</c>.
/// </summary>
/// <param name="fieldPath">The name of the fields containing an array to search.</param>
/// <param name="values">The list that contains the values to match.</param>
/// <returns>A new query based on the current one, but with the additional filter applied.
/// </returns>
public Query WhereNotIn(string fieldPath, IEnumerable<object> values) {
Preconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath));
Preconditions.CheckNotNull(values, nameof(values));
var array = ValueSerializer.Serialize(SerializationContext.Default, values);
var query = FirestoreCpp.QueryWhereNotIn(_proxy, fieldPath, array);
return new Query(query, Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that's additionally sorted by the specified field.
/// </summary>
/// <remarks>
/// <para>Unlike OrderBy in LINQ, this call makes each additional ordering subordinate to the
/// preceding ones. This means that <c>query.OrderBy("foo").OrderBy("bar")</c> in Cloud
/// Firestore is similar to <c>query.OrderBy(x => x.Foo).ThenBy(x => x.Bar)</c> in LINQ.
/// </para>
///
/// <para>This method cannot be called after a start/end cursor has been specified with
/// <see cref="StartAt(DocumentSnapshot)"/>, <see cref="StartAfter(DocumentSnapshot)"/>,
/// <see cref="EndAt(DocumentSnapshot)"/> or <see cref="EndBefore(DocumentSnapshot)"/> or
/// other overloads. </para>
/// </remarks>
/// <param name="fieldPath">The dot-separated field path to order by. Must not be <c>null</c> or
/// empty.</param>
/// <returns>A new query based on the current one, but with the additional specified ordering
/// applied.</returns>
public Query OrderBy(string fieldPath) {
Preconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath));
return new Query(_proxy.OrderBy(fieldPath), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that's additionally sorted by the specified field in
/// descending order.
/// </summary>
/// <remarks>
/// <para>Unlike OrderByDescending in LINQ, this call makes each additional ordering subordinate
/// to the preceding ones. This means that
/// <c>query.OrderByDescending("foo").OrderByDescending("bar")</c> in Cloud Firestore is similar
/// to <c>query.OrderByDescending(x => x.Foo).ThenByDescending(x => x.Bar)</c> in LINQ. </para>
///
/// <para>This method cannot be called after a start/end cursor has been specified with
/// <see cref="StartAt(DocumentSnapshot)"/>, <see cref="StartAfter(DocumentSnapshot)"/>,
/// <see cref="EndAt(DocumentSnapshot)"/> or <see cref="EndBefore(DocumentSnapshot)"/> or
/// other overloads. </para>
/// </remarks>
/// <param name="fieldPath">The dot-separated field path to order by. Must not be <c>null</c> or
/// empty.</param>
/// <returns>A new query based on the current one, but with the additional specified ordering
/// applied.</returns>
public Query OrderByDescending(string fieldPath) {
Preconditions.CheckNotNullOrEmpty(fieldPath, nameof(fieldPath));
return new Query(_proxy.OrderBy(fieldPath, QueryProxy.Direction.Descending), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that's additionally sorted by the specified field.
/// </summary>
/// <remarks>
/// <para>Unlike OrderBy in LINQ, this call makes each additional ordering subordinate to the
/// preceding ones. This means that <c>query.OrderBy("foo").OrderBy("bar")</c> in Cloud
/// Firestore is similar to <c>query.OrderBy(x => x.Foo).ThenBy(x => x.Bar)</c> in LINQ.
/// </para>
///
/// <para>This method cannot be called after a start/end cursor has been specified with
/// <see cref="StartAt(DocumentSnapshot)"/>, <see cref="StartAfter(DocumentSnapshot)"/>,
/// <see cref="EndAt(DocumentSnapshot)"/> or <see cref="EndBefore(DocumentSnapshot)"/> or
/// other overloads. </para>
/// </remarks>
/// <param name="fieldPath">The field path to order by. Must not be <c>null</c>.</param>
/// <returns>A new query based on the current one, but with the additional specified ordering
/// applied.</returns>
public Query OrderBy(FieldPath fieldPath) {
Preconditions.CheckNotNull(fieldPath, nameof(fieldPath));
return new Query(_proxy.OrderBy(fieldPath.ConvertToProxy()), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that's additionally sorted by the specified field in
/// descending order.
/// </summary>
/// <remarks>
/// <para>Unlike OrderByDescending in LINQ, this call makes each additional ordering subordinate
/// to the preceding ones. This means that
/// <c>query.OrderByDescending("foo").OrderByDescending("bar")</c> in Cloud Firestore is similar
/// to <c>query.OrderByDescending(x => x.Foo).ThenByDescending(x => x.Bar)</c> in LINQ. </para>
///
/// <para>This method cannot be called after a start/end cursor has been specified with
/// <see cref="StartAt(DocumentSnapshot)"/>, <see cref="StartAfter(DocumentSnapshot)"/>,
/// <see cref="EndAt(DocumentSnapshot)"/> or <see cref="EndBefore(DocumentSnapshot)"/> or
/// other overloads. </para>
/// </remarks>
/// <param name="fieldPath">The field path to order by. Must not be <c>null</c>.</param>
/// <returns>A new query based on the current one, but with the additional specified ordering
/// applied.</returns>
public Query OrderByDescending(FieldPath fieldPath) {
Preconditions.CheckNotNull(fieldPath, nameof(fieldPath));
return new Query(_proxy.OrderBy(fieldPath.ConvertToProxy(),
QueryProxy.Direction.Descending), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that only returns the last matching documents up to the
/// specified number.
/// </summary>
/// <remarks>
/// This call replaces any previously-specified limit in the query.
/// </remarks>
/// <param name="limit">The maximum number of items to return. Must be greater than 0.</param>
/// <returns>A new query based on the current one, but with the specified limit applied.
/// </returns>
public Query Limit(int limit) {
return new Query(_proxy.Limit(limit), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that only returns the last matching documents up to the
/// specified number.
/// </summary>
/// <remarks>
/// You must specify at least one <c>OrderBy</c> clause for <c>LimitToLast</c> queries,
/// otherwise an exception will be thrown during execution.
///
/// This call replaces any previously-specified limit in the query.
/// </remarks>
/// <param name="limit">The maximum number of items to return. Must be greater than 0.</param>
/// <returns>A new query based on the current one, but with the specified limit applied.
/// </returns>
public Query LimitToLast(int limit) {
return new Query(_proxy.LimitToLast(limit), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that starts at the provided document (inclusive). The
/// starting position is relative to the order of the query. The document must contain all of
/// the fields provided in order-by clauses of the query.
/// </summary>
/// <remarks>
/// This call replaces any previously specified start position in the query.
/// </remarks>
/// <param name="snapshot">The snapshot of the document to start at.</param>
/// <returns>A new query based on the current one, but with the specified start position.</returns>
public Query StartAt(DocumentSnapshot snapshot) {
Preconditions.CheckNotNull(snapshot, nameof(snapshot));
return new Query(_proxy.StartAt(snapshot.Proxy), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that starts at the provided fields relative to the
/// order of the query. The order of the field values must match the order of the order-by
/// clauses of the query.
/// </summary>
/// <remarks>
/// This call replaces any previously specified start position in the query.
/// </remarks>
/// <param name="fieldValues">The field values. The <c>fieldValues</c> array must not be
/// <c>null</c> or empty (though elements of the array may be), or have more values than query
/// has orderings.</param>
/// <returns>A new query based on the current one, but with the specified start position.
/// </returns>
public Query StartAt(params object[] fieldValues) {
Preconditions.CheckNotNull(fieldValues, nameof(fieldValues));
var array = ValueSerializer.Serialize(SerializationContext.Default, fieldValues);
var query = FirestoreCpp.QueryStartAt(_proxy, array);
return new Query(query, Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that starts after the provided document (exclusive).
/// The starting position is relative to the order of the query. The document must contain all
/// of the fields provided in the order-by clauses of the query.
/// </summary>
/// <remarks>
/// This call replaces any previously specified start position in the query.
/// </remarks>
/// <param name="snapshot">The snapshot of the document to start after.</param>
/// <returns>A new query based on the current one, but with the specified start position.
/// </returns>
public Query StartAfter(DocumentSnapshot snapshot) {
Preconditions.CheckNotNull(snapshot, nameof(snapshot));
return new Query(_proxy.StartAfter(snapshot.Proxy), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that starts after the provided fields relative to the
/// order of the query. The order of the field values must match the order of the order-by
/// clauses of the query.
/// </summary>
/// <remarks>
/// This call replaces any previously specified start position in the query.
/// </remarks>
/// <param name="fieldValues">The field values. The <c>fieldValues</c> array must not be
/// <c>null</c> or empty (though elements of the array may be), or have more values than query
/// has orderings.</param>
/// <returns>A new query based on the current one, but with the specified start position.
/// </returns>
public Query StartAfter(params object[] fieldValues) {
Preconditions.CheckNotNull(fieldValues, nameof(fieldValues));
var array = ValueSerializer.Serialize(SerializationContext.Default, fieldValues);
var query = FirestoreCpp.QueryStartAfter(_proxy, array);
return new Query(query, Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that ends before the provided document (exclusive).
/// The end position is relative to the order of the query. The document must contain all of the
/// fields provided in the order-by clauses of the query.
/// </summary>
/// <remarks>
/// This call replaces any previously specified end position in the query.
/// </remarks>
/// <param name="snapshot">The snapshot of the document to end before.</param>
/// <returns>A new query based on the current one, but with the specified end position.
/// </returns>
public Query EndBefore(DocumentSnapshot snapshot) {
Preconditions.CheckNotNull(snapshot, nameof(snapshot));
return new Query(_proxy.EndBefore(snapshot.Proxy), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that ends before the provided fields relative to the
/// order of the query. The order of the field values must match the order of the order-by
/// clauses of the query.
/// </summary>
/// <remarks>
/// This call replaces any previously specified end position in the query.
/// </remarks>
/// <param name="fieldValues">The field values. The <c>fieldValues</c> array must not be
/// <c>null</c> or empty (though elements of the array may be), or have more values than query
/// has orderings.</param>
/// <returns>A new query based on the current one, but with the specified end position.
/// </returns>
public Query EndBefore(params object[] fieldValues) {
Preconditions.CheckNotNull(fieldValues, nameof(fieldValues));
var array = ValueSerializer.Serialize(SerializationContext.Default, fieldValues);
var query = FirestoreCpp.QueryEndBefore(_proxy, array);
return new Query(query, Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that ends at the provided document (inclusive). The
/// end position is relative to the order of the query. The document must contain all of the
/// fields provided in the order-by clauses of the query.
/// </summary>
/// <remarks>
/// This call replaces any previously specified end position in the query.
/// </remarks>
/// <param name="snapshot">The snapshot of the document to end at.</param>
/// <returns>A new query based on the current one, but with the specified end position.
/// </returns>
public Query EndAt(DocumentSnapshot snapshot) {
Preconditions.CheckNotNull(snapshot, nameof(snapshot));
return new Query(_proxy.EndAt(snapshot.Proxy), Firestore);
}
/// <summary>
/// Creates and returns a new <c>Query</c> that ends at the provided fields relative to the
/// order of the query. The order of the field values must match the order of the order-by
/// clauses of the query.
/// </summary>
/// <remarks>
/// This call replaces any previously specified end position in the query.
/// </remarks>
/// <param name="fieldValues">The field values. The <c>fieldValues</c> array must not be
/// <c>null</c> or empty (though elements of the array may be), or have more values than query
/// has orderings.</param>
/// <returns>A new query based on the current one, but with the specified end position.
/// </returns>
public Query EndAt(params object[] fieldValues) {
Preconditions.CheckNotNull(fieldValues, nameof(fieldValues));
var array = ValueSerializer.Serialize(SerializationContext.Default, fieldValues);
var query = FirestoreCpp.QueryEndAt(_proxy, array);
return new Query(query, Firestore);
}
/// <summary>
/// Asynchronously executes the query and returns all matching documents as a
/// <c>QuerySnapshot</c>.
/// </summary>
/// <remarks>
/// <para>By default, <c>GetSnapshotAsync</c> attempts to provide up-to-date data when possible
/// by waiting for data from the server, but it may return cached data or fail if you are
/// offline and the server cannot be reached. This behavior can be altered via the <c>source</c>
/// parameter.</para>
/// </remarks>
/// <param name="source">indicates whether the results should be fetched from the cache only
/// (<c>Source.Cache</c>), the server only (<c>Source.Server</c>), or to attempt the server and
/// fall back to the cache (<c>Source.Default</c>).</param>
/// <returns>A snapshot of documents matching the query.</returns>
public Task<QuerySnapshot> GetSnapshotAsync(Source source = Source.Default) {
var sourceProxy = Enums.Convert(source);
return Util.MapResult(_proxy.GetAsync(sourceProxy), taskResult => {
return new QuerySnapshot(taskResult, Firestore);
});
}
/// <summary>
/// Starts listening to changes to the query results described by this <c>Query</c>.
/// </summary>
/// <param name="callback">The callback to invoke each time the query results change. Must not
/// be <c>null</c>. The callback will be invoked on the main thread.</param>
/// <returns>A <see cref="ListenerRegistration"/> which may be used to stop listening
/// gracefully.</returns>
public ListenerRegistration Listen(Action<QuerySnapshot> callback) {
Preconditions.CheckNotNull(callback, nameof(callback));
return Listen(MetadataChanges.Exclude, callback);
}
/// <summary>
/// Starts listening to changes to the query results described by this <c>Query</c>.
/// </summary>
/// <param name="metadataChanges">Indicates whether metadata-only changes (i.e. only
/// <c>QuerySnapshot.Metadata</c> changed) should trigger snapshot events.</param>
/// <param name="callback">The callback to invoke each time the query results change. Must not
/// be <c>null</c>. The callback will be invoked on the main thread.</param>
/// <returns>A <see cref="ListenerRegistration"/> which may be used to stop listening
/// gracefully.</returns>
public ListenerRegistration Listen(MetadataChanges metadataChanges, Action<QuerySnapshot> callback) {
Preconditions.CheckNotNull(callback, nameof(callback));
var tcs = new TaskCompletionSource<object>();
int uid = snapshotListenerCallbacks.Register(Firestore, (snapshotProxy, errorCode,
errorMessage) => {
if (errorCode != FirestoreError.Ok) {
tcs.SetException(new FirestoreException(errorCode, errorMessage));
} else {
FirebaseHandler.RunOnMainThread<object>(() => {
callback(new QuerySnapshot(snapshotProxy, Firestore));
return null;
});
}
});
var metadataChangesProxy = Enums.Convert(metadataChanges);
var listener = FirestoreCpp.AddQuerySnapshotListener(_proxy, metadataChangesProxy, uid,
querySnapshotsHandler);
return new ListenerRegistration(snapshotListenerCallbacks, uid, tcs, listener);
}
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as Query);
/// <inheritdoc />
public bool Equals(Query other) => other != null
&& FirestoreCpp.QueryEquals(_proxy, other._proxy);
/// <inheritdoc />
public override int GetHashCode() {
return FirestoreCpp.QueryHashCode(_proxy);
}
private static QuerySnapshotCallbackMap snapshotListenerCallbacks = new QuerySnapshotCallbackMap();
internal delegate void ListenerDelegate(int callbackId, IntPtr snapshotPtr,
FirestoreError errorCode, string errorMessage);
private static ListenerDelegate querySnapshotsHandler = new ListenerDelegate(QuerySnapshotsHandler);
[MonoPInvokeCallback(typeof(ListenerDelegate))]
private static void QuerySnapshotsHandler(int callbackId, IntPtr snapshotPtr,
FirestoreError errorCode, string errorMessage) {
try {
// Create the proxy object _before_ doing anything else to ensure that the C++ object's
// memory does not get leaked (https://github.com/firebase/firebase-unity-sdk/issues/49).
var querySnapshotProxy = new QuerySnapshotProxy(snapshotPtr, /*cMemoryOwn=*/true);
Action<QuerySnapshotProxy, FirestoreError, string> callback;
if (snapshotListenerCallbacks.TryGetCallback(callbackId, out callback)) {
callback(querySnapshotProxy, errorCode, errorMessage);
}
} catch (Exception e) {
Util.OnPInvokeManagedException(e, nameof(QuerySnapshotsHandler));
}
}
}
}
| |
namespace ClrPlus.Core.Sgml {
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
/// <summary>
/// An Entity declared in a DTD.
/// </summary>
public class Entity : IDisposable {
/// <summary>
/// The character indicating End Of File.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1705", Justification = "The capitalisation is correct since EOF is an acronym.")]
public const char EOF = (char)65535;
private string m_proxy;
private string m_name;
private bool m_isInternal;
private string m_publicId;
private string m_uri;
private string m_literal;
private LiteralType m_literalType;
private Entity m_parent;
private bool m_isHtml;
private int m_line;
private char m_lastchar;
private bool m_isWhitespace;
private Encoding m_encoding;
private Uri m_resolvedUri;
private TextReader m_stm;
private bool m_weOwnTheStream;
private int m_lineStart;
private int m_absolutePos;
/// <summary>
/// Initialises a new instance of an Entity declared in a DTD.
/// </summary>
/// <param name="name">The name of the entity.</param>
/// <param name="pubid">The public id of the entity.</param>
/// <param name="uri">The uri of the entity.</param>
/// <param name="proxy">The proxy server to use when retrieving any web content.</param>
public Entity(string name, string pubid, string uri, string proxy) {
m_name = name;
m_publicId = pubid;
m_uri = uri;
m_proxy = proxy;
m_isHtml = (name != null && StringUtilities.EqualsIgnoreCase(name, "html"));
}
/// <summary>
/// Initialises a new instance of an Entity declared in a DTD.
/// </summary>
/// <param name="name">The name of the entity.</param>
/// <param name="literal">The literal value of the entity.</param>
public Entity(string name, string literal) {
m_name = name;
m_literal = literal;
m_isInternal = true;
}
/// <summary>
/// Initialises a new instance of an Entity declared in a DTD.
/// </summary>
/// <param name="name">The name of the entity.</param>
/// <param name="baseUri">The baseUri for the entity to read from the TextReader.</param>
/// <param name="stm">The TextReader to read the entity from.</param>
/// <param name="proxy">The proxy server to use when retrieving any web content.</param>
public Entity(string name, Uri baseUri, TextReader stm, string proxy) {
m_name = name;
m_isInternal = true;
m_stm = stm;
m_resolvedUri = baseUri;
m_proxy = proxy;
m_isHtml = string.Equals(name, "html", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// The name of the entity.
/// </summary>
public string Name {
get {
return m_name;
}
}
/// <summary>
/// True if the entity is the html element entity.
/// </summary>
public bool IsHtml {
get {
return m_isHtml;
}
set {
m_isHtml = value;
}
}
/// <summary>
/// The public identifier of this entity.
/// </summary>
public string PublicId {
get {
return m_publicId;
}
}
/// <summary>
/// The Uri that is the source for this entity.
/// </summary>
public string Uri {
get {
return m_uri;
}
}
/// <summary>
/// The resolved location of the DTD this entity is from.
/// </summary>
public Uri ResolvedUri {
get {
if (this.m_resolvedUri != null) {
return this.m_resolvedUri;
} else if (m_parent != null) {
return m_parent.ResolvedUri;
} else {
return null;
}
}
}
/// <summary>
/// Gets the parent Entity of this Entity.
/// </summary>
public Entity Parent {
get {
return m_parent;
}
}
/// <summary>
/// The last character read from the input stream for this entity.
/// </summary>
public char Lastchar {
get {
return m_lastchar;
}
}
/// <summary>
/// The line on which this entity was defined.
/// </summary>
public int Line {
get {
return m_line;
}
}
/// <summary>
/// The index into the line where this entity is defined.
/// </summary>
public int LinePosition {
get {
return this.m_absolutePos - this.m_lineStart + 1;
}
}
/// <summary>
/// Whether this entity is an internal entity or not.
/// </summary>
/// <value>true if this entity is internal, otherwise false.</value>
public bool IsInternal {
get {
return m_isInternal;
}
}
/// <summary>
/// The literal value of this entity.
/// </summary>
public string Literal {
get {
return m_literal;
}
}
/// <summary>
/// The <see cref="LiteralType" /> of this entity.
/// </summary>
public LiteralType LiteralType {
get {
return m_literalType;
}
}
/// <summary>
/// Whether the last char read for this entity is a whitespace character.
/// </summary>
public bool IsWhitespace {
get {
return m_isWhitespace;
}
}
/// <summary>
/// The proxy server to use when making web requests to resolve entities.
/// </summary>
public string Proxy {
get {
return m_proxy;
}
}
/// <summary>
/// Reads the next character from the DTD stream.
/// </summary>
/// <returns>The next character from the DTD stream.</returns>
public char ReadChar() {
var ch = (char)this.m_stm.Read();
if (ch == 0) {
// convert nulls to whitespace, since they are not valid in XML anyway.
ch = ' ';
}
this.m_absolutePos++;
if (ch == 0xa) {
m_isWhitespace = true;
this.m_lineStart = this.m_absolutePos + 1;
this.m_line++;
} else if (ch == ' ' || ch == '\t') {
m_isWhitespace = true;
if (m_lastchar == 0xd) {
this.m_lineStart = this.m_absolutePos;
m_line++;
}
} else if (ch == 0xd) {
m_isWhitespace = true;
} else {
m_isWhitespace = false;
if (m_lastchar == 0xd) {
m_line++;
this.m_lineStart = this.m_absolutePos;
}
}
m_lastchar = ch;
return ch;
}
/// <summary>
/// Begins processing an entity.
/// </summary>
/// <param name="parent">The parent of this entity.</param>
/// <param name="baseUri">The base Uri for processing this entity within.</param>
public void Open(Entity parent, Uri baseUri) {
this.m_parent = parent;
if (parent != null) {
this.m_isHtml = parent.IsHtml;
}
this.m_line = 1;
if (m_isInternal) {
if (this.m_literal != null) {
this.m_stm = new StringReader(this.m_literal);
}
} else if (this.m_uri == null) {
this.Error("Unresolvable entity '{0}'", this.m_name);
} else {
if (baseUri != null) {
this.m_resolvedUri = new Uri(baseUri, this.m_uri);
} else {
this.m_resolvedUri = new Uri(this.m_uri);
}
Stream stream = null;
var e = Encoding.Default;
switch (this.m_resolvedUri.Scheme) {
case "file": {
var path = this.m_resolvedUri.LocalPath;
stream = new FileStream(path, FileMode.Open, FileAccess.Read);
}
break;
default:
Console.WriteLine("Fetching:" + ResolvedUri.AbsoluteUri);
var wr = (HttpWebRequest)WebRequest.Create(ResolvedUri);
wr.UserAgent = "Mozilla/4.0 (compatible;);";
wr.Timeout = 10000; // in case this is running in an ASPX page.
if (m_proxy != null) {
wr.Proxy = new WebProxy(m_proxy);
}
wr.PreAuthenticate = false;
// Pass the credentials of the process.
wr.Credentials = CredentialCache.DefaultCredentials;
var resp = wr.GetResponse();
var actual = resp.ResponseUri;
if (!string.Equals(actual.AbsoluteUri, this.m_resolvedUri.AbsoluteUri, StringComparison.OrdinalIgnoreCase)) {
this.m_resolvedUri = actual;
}
var contentType = resp.ContentType.ToLowerInvariant();
var mimeType = contentType;
var i = contentType.IndexOf(';');
if (i >= 0) {
mimeType = contentType.Substring(0, i);
}
if (StringUtilities.EqualsIgnoreCase(mimeType, "text/html")) {
this.m_isHtml = true;
}
i = contentType.IndexOf("charset");
e = Encoding.Default;
if (i >= 0) {
var j = contentType.IndexOf("=", i);
var k = contentType.IndexOf(";", j);
if (k < 0) {
k = contentType.Length;
}
if (j > 0) {
j++;
var charset = contentType.Substring(j, k - j).Trim();
try {
e = Encoding.GetEncoding(charset);
} catch (ArgumentException) {
}
}
}
stream = resp.GetResponseStream();
break;
}
this.m_weOwnTheStream = true;
var html = new HtmlStream(stream, e);
this.m_encoding = html.Encoding;
this.m_stm = html;
}
}
/// <summary>
/// Gets the character encoding for this entity.
/// </summary>
public Encoding Encoding {
get {
return this.m_encoding;
}
}
/// <summary>
/// Closes the reader from which the entity is being read.
/// </summary>
public void Close() {
if (this.m_weOwnTheStream) {
this.m_stm.Close();
}
}
/// <summary>
/// Returns the next character after any whitespace.
/// </summary>
/// <returns>The next character that is not whitespace.</returns>
public char SkipWhitespace() {
var ch = m_lastchar;
while (ch != EOF && (ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t')) {
ch = ReadChar();
}
return ch;
}
/// <summary>
/// Scans a token from the input stream and returns the result.
/// </summary>
/// <param name="sb">
/// The <see cref="StringBuilder" /> to use to process the token.
/// </param>
/// <param name="term">A set of characters to look for as terminators for the token.</param>
/// <param name="nmtoken">true if the token should be a NMToken, otherwise false.</param>
/// <returns>The scanned token.</returns>
public string ScanToken(StringBuilder sb, string term, bool nmtoken) {
if (sb == null) {
throw new ArgumentNullException("sb");
}
if (term == null) {
throw new ArgumentNullException("term");
}
sb.Length = 0;
var ch = m_lastchar;
if (nmtoken && ch != '_' && !char.IsLetter(ch)) {
throw new SgmlParseException(string.Format(CultureInfo.CurrentUICulture, "Invalid name start character '{0}'", ch));
}
while (ch != EOF && term.IndexOf(ch) < 0) {
if (!nmtoken || ch == '_' || ch == '.' || ch == '-' || ch == ':' || char.IsLetterOrDigit(ch)) {
sb.Append(ch);
} else {
throw new SgmlParseException(
string.Format(CultureInfo.CurrentUICulture, "Invalid name character '{0}'", ch));
}
ch = ReadChar();
}
return sb.ToString();
}
/// <summary>
/// Read a literal from the input stream.
/// </summary>
/// <param name="sb">
/// The <see cref="StringBuilder" /> to use to build the literal.
/// </param>
/// <param name="quote">The delimiter for the literal.</param>
/// <returns>The literal scanned from the input stream.</returns>
public string ScanLiteral(StringBuilder sb, char quote) {
if (sb == null) {
throw new ArgumentNullException("sb");
}
sb.Length = 0;
var ch = ReadChar();
while (ch != EOF && ch != quote) {
if (ch == '&') {
ch = ReadChar();
if (ch == '#') {
var charent = ExpandCharEntity();
sb.Append(charent);
ch = this.m_lastchar;
} else {
sb.Append('&');
sb.Append(ch);
ch = ReadChar();
}
} else {
sb.Append(ch);
ch = ReadChar();
}
}
ReadChar(); // consume end quote.
return sb.ToString();
}
/// <summary>
/// Reads input until the end of the input stream or until a string of terminator characters is found.
/// </summary>
/// <param name="sb">
/// The <see cref="StringBuilder" /> to use to build the string.
/// </param>
/// <param name="type">The type of the element being read (only used in reporting errors).</param>
/// <param name="terminators">The string of terminator characters to look for.</param>
/// <returns>The string read from the input stream.</returns>
public string ScanToEnd(StringBuilder sb, string type, string terminators) {
if (terminators == null) {
throw new ArgumentNullException("terminators");
}
if (sb != null) {
sb.Length = 0;
}
var start = m_line;
// This method scans over a chunk of text looking for the
// termination sequence specified by the 'terminators' parameter.
var ch = ReadChar();
var state = 0;
var next = terminators[state];
while (ch != EOF) {
if (ch == next) {
state++;
if (state >= terminators.Length) {
// found it!
break;
}
next = terminators[state];
} else if (state > 0) {
// char didn't match, so go back and see how much does still match.
var i = state - 1;
var newstate = 0;
while (i >= 0 && newstate == 0) {
if (terminators[i] == ch) {
// character is part of the terminators pattern, ok, so see if we can
// match all the way back to the beginning of the pattern.
var j = 1;
while (i - j >= 0) {
if (terminators[i - j] != terminators[state - j]) {
break;
}
j++;
}
if (j > i) {
newstate = i + 1;
}
} else {
i--;
}
}
if (sb != null) {
i = (i < 0) ? 1 : 0;
for (var k = 0; k <= state - newstate - i; k++) {
sb.Append(terminators[k]);
}
if (i > 0) // see if we've matched this char or not
{
sb.Append(ch); // if not then append it to buffer.
}
}
state = newstate;
next = terminators[newstate];
} else {
if (sb != null) {
sb.Append(ch);
}
}
ch = ReadChar();
}
if (ch == 0) {
Error(type + " starting on line {0} was never closed", start);
}
ReadChar(); // consume last char in termination sequence.
if (sb != null) {
return sb.ToString();
} else {
return string.Empty;
}
}
/// <summary>
/// Expands a character entity to be read from the input stream.
/// </summary>
/// <returns>The string for the character entity.</returns>
public string ExpandCharEntity() {
var ch = ReadChar();
var v = 0;
if (ch == 'x') {
ch = ReadChar();
for (; ch != EOF && ch != ';'; ch = ReadChar()) {
var p = 0;
if (ch >= '0' && ch <= '9') {
p = (ch - '0');
} else if (ch >= 'a' && ch <= 'f') {
p = (ch - 'a') + 10;
} else if (ch >= 'A' && ch <= 'F') {
p = (ch - 'A') + 10;
} else {
break; //we must be done!
//Error("Hex digit out of range '{0}'", (int)ch);
}
v = (v*16) + p;
}
} else {
for (; ch != EOF && ch != ';'; ch = ReadChar()) {
if (ch >= '0' && ch <= '9') {
v = (v*10) + (ch - '0');
} else {
break; // we must be done!
//Error("Decimal digit out of range '{0}'", (int)ch);
}
}
}
if (ch == 0) {
Error("Premature {0} parsing entity reference", ch);
} else if (ch == ';') {
ReadChar();
}
// HACK ALERT: IE and Netscape map the unicode characters
if (this.m_isHtml && v >= 0x80 & v <= 0x9F) {
// This range of control characters is mapped to Windows-1252!
var size = CtrlMap.Length;
var i = v - 0x80;
var unicode = CtrlMap[i];
return Convert.ToChar(unicode).ToString();
}
// NOTE (steveb): we need to use ConvertFromUtf32 to allow for extended numeric encodings
return char.ConvertFromUtf32(v);
}
private static int[] CtrlMap = new[] {
// This is the windows-1252 mapping of the code points 0x80 through 0x9f.
8364, 129, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338, 141,
381, 143, 144, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250,
339, 157, 382, 376
};
/// <summary>
/// Raise a processing error.
/// </summary>
/// <param name="msg">The error message to use in the exception.</param>
/// <exception cref="SgmlParseException">Always thrown.</exception>
public void Error(string msg) {
throw new SgmlParseException(msg, this);
}
/// <summary>
/// Raise a processing error.
/// </summary>
/// <param name="msg">The error message to use in the exception.</param>
/// <param name="ch">The unexpected character causing the error.</param>
/// <exception cref="SgmlParseException">Always thrown.</exception>
public void Error(string msg, char ch) {
var str = (ch == EOF) ? "EOF" : char.ToString(ch);
throw new SgmlParseException(string.Format(CultureInfo.CurrentUICulture, msg, str), this);
}
/// <summary>
/// Raise a processing error.
/// </summary>
/// <param name="msg">The error message to use in the exception.</param>
/// <param name="x">The value causing the error.</param>
/// <exception cref="SgmlParseException">Always thrown.</exception>
public void Error(string msg, int x) {
throw new SgmlParseException(string.Format(CultureInfo.CurrentUICulture, msg, x), this);
}
/// <summary>
/// Raise a processing error.
/// </summary>
/// <param name="msg">The error message to use in the exception.</param>
/// <param name="arg">The argument for the error.</param>
/// <exception cref="SgmlParseException">Always thrown.</exception>
public void Error(string msg, string arg) {
throw new SgmlParseException(string.Format(CultureInfo.CurrentUICulture, msg, arg), this);
}
/// <summary>
/// Returns a string giving information on how the entity is referenced and declared, walking up the parents until the top level parent entity is found.
/// </summary>
/// <returns>Contextual information for the entity.</returns>
public string Context() {
var p = this;
var sb = new StringBuilder();
while (p != null) {
string msg;
if (p.m_isInternal) {
msg = string.Format(CultureInfo.InvariantCulture, "\nReferenced on line {0}, position {1} of internal entity '{2}'", p.m_line, p.LinePosition, p.m_name);
} else {
msg = string.Format(CultureInfo.InvariantCulture, "\nReferenced on line {0}, position {1} of '{2}' entity at [{3}]", p.m_line, p.LinePosition, p.m_name, p.ResolvedUri.AbsolutePath);
}
sb.Append(msg);
p = p.Parent;
}
return sb.ToString();
}
/// <summary>
/// Checks whether a token denotes a literal entity or not.
/// </summary>
/// <param name="token">The token to check.</param>
/// <returns>true if the token is "CDATA", "SDATA" or "PI", otherwise false.</returns>
public static bool IsLiteralType(string token) {
return string.Equals(token, "CDATA", StringComparison.OrdinalIgnoreCase) ||
string.Equals(token, "SDATA", StringComparison.OrdinalIgnoreCase) ||
string.Equals(token, "PI", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Sets the entity to be a literal of the type specified.
/// </summary>
/// <param name="token">One of "CDATA", "SDATA" or "PI".</param>
public void SetLiteralType(string token) {
switch (token) {
case "CDATA":
this.m_literalType = LiteralType.CDATA;
break;
case "SDATA":
this.m_literalType = LiteralType.SDATA;
break;
case "PI":
this.m_literalType = LiteralType.PI;
break;
}
}
#region IDisposable Members
/// <summary>
/// The finalizer for the Entity class.
/// </summary>
~Entity() {
Dispose(false);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <param name="isDisposing">true if this method has been called by user code, false if it has been called through a finalizer.</param>
protected virtual void Dispose(bool isDisposing) {
if (isDisposing) {
if (m_stm != null) {
m_stm.Dispose();
m_stm = null;
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace DevCamp.API.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
/*
Dijkstra's algorithm example
Finds shortest paths from a given vertex
to all other vertices in a graph
Copyright 2017, Sjors van Gelderen
Resources used:
https://en.wikipedia.org/wiki/Dijkstra's_algorithm - Dijkstra's algorithm
// https://msdn.microsoft.com/en-us/library/2s05feca.aspx - Jagged arrays
*/
using System;
using System.Collections.Generic;
namespace Program
{
// Edges for the weighted adjacency list
class Edge
{
public int Vertex { get; set; } // Terminating vertex of edge
public int Weight { get; set; } // Weight of edge
public Edge(int _vertex, int _weight)
{
Vertex = _vertex;
Weight = _weight;
}
}
static class Program
{
// Used for infinity. Not perfect, but certainly adequate.
const int MAX = int.MaxValue;
// Generates string from elements in an array
static string StringFromArray<T>(ref T[] _collection)
{
string buffer = "[";
foreach(var element in _collection)
{
buffer += element.ToString();
buffer += ", ";
}
buffer += "]";
return buffer;
}
// Generates string from elements in a list
static string StringFromList<T>(List<T> _list)
{
string buffer = "[";
foreach(var element in _list)
{
buffer += element.ToString();
buffer += ", ";
}
buffer += "]" + Environment.NewLine;
return buffer;
}
/*
Finds index of the vertex with the smallest distance
Complexity: O(n^2)
*/
static int FindClosest(int[] _distances, List<int> _unvisited)
{
int min_distance = MAX;
int result_index = -1;
for(int i = 0; i < _distances.Length; i++)
{
if(_unvisited.Contains(i))
{
if(_distances[i] < min_distance)
{
min_distance = _distances[i];
result_index = i;
}
}
}
Console.WriteLine("Closest vertex: {0}", result_index);
return result_index;
}
/*
Dijkstra's algorithm
Complexity: O(n^2)
*/
static int[] Dijkstra(Edge[][] _graph, int _source)
{
// Get amount of vertices (|V|)
var size = _graph.GetLength(0);
// Set all distances to infinite
var distances = new int[size];
for(int i = 0; i < distances.Length; i++)
{
distances[i] = MAX;
}
// Distance between source and itself is 0
distances[_source] = 0;
// Set up a chain in which to record the shortest path
var chain = new int[size];
for(int i = 0; i < size; i++)
{
chain[i] = -1;
}
// At first, all nodes are unvisited
var unvisited = new List<int>();
for(int i = 0; i < size; i++)
{
unvisited.Add(i);
}
while(unvisited.Count > 0)
{
Console.WriteLine("Remaining vertices: {0}",
StringFromList<int>(unvisited));
// Find the index of the closest vertex and visit it
int index = FindClosest(distances, unvisited);
unvisited.Remove(index);
// For each neighbor stored in the adjacency list
foreach(var neighbor in _graph[index])
{
int alternate = distances[index] + neighbor.Weight;
if(alternate < distances[neighbor.Vertex])
{
// Since this alternate path offers a shorter distance, record it
Console.WriteLine("{0} -> {1}", neighbor.Vertex, alternate);
distances[neighbor.Vertex] = alternate;
// Add the vertex to the chain
chain[neighbor.Vertex] = index;
Console.WriteLine("Chain: {0}", StringFromArray(ref chain));
}
}
Console.WriteLine("Distances: {0}", StringFromArray<int>(ref distances));
}
Console.WriteLine("Dijkstra's algorithm result:"
+ Environment.NewLine
+ "Distances: {0}"
+ Environment.NewLine
+ "Chain: {1}"
+ Environment.NewLine,
StringFromArray<int>(ref distances),
StringFromArray<int>(ref chain));
return chain;
}
// Extract the shortes path between source and target from a provided chain
static void ShortestPath(int _source, int _target, int[] _chain)
{
var path = new List<int>();
int current = _target;
while(current != -1)
{
path.Add(current);
current = _chain[current];
}
Console.WriteLine("Shortest path from {0} to {1}: {2}",
_source, _target, StringFromList<int>(path));
}
static void Main()
{
Console.WriteLine("Dijkstra's algorithm example - "
+ "Copyright 2017, Sjors van Gelderen"
+ Environment.NewLine);
// Weighted adjacency list for the graph
var graph = new Edge[][]{
new Edge[]{ // 0
new Edge(1, 8),
new Edge(2, 1)
},
new Edge[]{ // 1
new Edge(0, 8),
new Edge(3, 2)
},
new Edge[]{ // 2
new Edge(0, 1),
new Edge(3, 3)
},
new Edge[]{ // 3
new Edge(1, 2),
new Edge(2, 3),
new Edge(4, 4),
new Edge(5, 6)
},
new Edge[]{ // 4
new Edge(3, 4),
new Edge(5, 1)
},
new Edge[]{
new Edge(3, 6),
new Edge(4, 1)
}
};
// Run Dijkstra's algorithm on the graph with source vertex 0
int[] chain = Dijkstra(graph, 0);
// Calculate some shortest paths
ShortestPath(0, 5, chain);
ShortestPath(0, 3, chain);
ShortestPath(0, 4, chain);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Web;
using Funq;
using ServiceStack.Common.Utils;
using ServiceStack.ServiceHost;
namespace ServiceStack.WebHost.Endpoints.Extensions
{
public class HttpRequestWrapper
: IHttpRequest
{
private static readonly string physicalFilePath;
public Container Container { get; set; }
private readonly HttpRequest request;
static HttpRequestWrapper()
{
physicalFilePath = "~".MapHostAbsolutePath();
}
public HttpRequest Request
{
get { return request; }
}
public object OriginalRequest
{
get { return request; }
}
public HttpRequestWrapper(string operationName, HttpRequest request)
{
this.OperationName = operationName;
this.request = request;
this.Container = Container;
}
public T TryResolve<T>()
{
return Container == null
? EndpointHost.AppHost.TryResolve<T>()
: Container.TryResolve<T>();
}
public string OperationName { get; set; }
public string ContentType
{
get { return request.ContentType; }
}
public string HttpMethod
{
get { return request.HttpMethod; }
}
public string UserAgent
{
get { return request.UserAgent; }
}
private Dictionary<string, object> items;
public Dictionary<string, object> Items
{
get
{
if (items == null)
{
items = new Dictionary<string, object>();
}
return items;
}
}
private string responseContentType;
public string ResponseContentType
{
get
{
if (responseContentType == null)
{
responseContentType = this.GetResponseContentType();
}
return responseContentType;
}
set
{
this.responseContentType = value;
}
}
private Dictionary<string, Cookie> cookies;
public IDictionary<string, Cookie> Cookies
{
get
{
if (cookies == null)
{
cookies = new Dictionary<string, Cookie>();
for (var i = 0; i < this.request.Cookies.Count; i++)
{
var httpCookie = this.request.Cookies[i];
var cookie = new Cookie(
httpCookie.Name, httpCookie.Value, httpCookie.Path, httpCookie.Domain)
{
HttpOnly = httpCookie.HttpOnly,
Secure = httpCookie.Secure,
Expires = httpCookie.Expires,
};
cookies[httpCookie.Name] = cookie;
}
}
return cookies;
}
}
public NameValueCollection Headers
{
get { return request.Headers; }
}
public NameValueCollection QueryString
{
get { return request.QueryString; }
}
public NameValueCollection FormData
{
get { return request.Form; }
}
public string GetRawBody()
{
using (var reader = new StreamReader(request.InputStream))
{
return reader.ReadToEnd();
}
}
public string RawUrl
{
get { return request.RawUrl; }
}
public string AbsoluteUri
{
get
{
try
{
return request.Url.AbsoluteUri.TrimEnd('/');
}
catch (Exception)
{
//fastcgi mono, do a 2nd rounds best efforts
return "http://" + request.UserHostName + request.RawUrl;
}
}
}
public string UserHostAddress
{
get { return request.UserHostAddress; }
}
public bool IsSecureConnection
{
get { return request.IsSecureConnection; }
}
public string[] AcceptTypes
{
get { return request.AcceptTypes; }
}
public string PathInfo
{
get { return request.GetPathInfo(); }
}
public string UrlHostName
{
get { return request.GetUrlHostName(); }
}
public Stream InputStream
{
get { return request.InputStream; }
}
public long ContentLength
{
get { return request.ContentLength; }
}
private IFile[] files;
public IFile[] Files
{
get
{
if (files == null)
{
files = new IFile[request.Files.Count];
for (var i = 0; i < request.Files.Count; i++)
{
var reqFile = request.Files[i];
files[i] = new HttpFile
{
ContentType = reqFile.ContentType,
ContentLength = reqFile.ContentLength,
FileName = reqFile.FileName,
InputStream = reqFile.InputStream,
};
}
}
return files;
}
}
public string ApplicationFilePath
{
get { return physicalFilePath; }
}
}
}
| |
//Copyright 2014 Spin Services Limited
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using SS.Integration.Adapter.MarketRules.Interfaces;
using SS.Integration.Adapter.Model;
using SS.Integration.Adapter.Model.Interfaces;
namespace SS.Integration.Adapter.MarketRules.Model
{
[Serializable]
internal class SelectionState : IUpdatableSelectionState
{
private Dictionary<string, string> _tags;
/// <summary>
/// DO NOT USE - this constructor is for copying object only
/// </summary>
public SelectionState()
{
_tags = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
}
public SelectionState(Selection selection, bool fullSnapshot)
: this()
{
Id = selection.Id;
IsRollingSelection = selection is RollingSelection;
Update(selection, fullSnapshot);
}
#region ISelectionState
public string Id { get; private set; }
public string Name { get; private set; }
public double? Price { get; private set; }
public bool? Tradability { get; private set; }
public string Status { get; private set; }
public double? Line { get; private set; }
public bool IsRollingSelection { get; private set; }
public ISelectionResultState Result { get; private set; }
public ISelectionResultState PlaceResult { get; private set; }
#region Tags
public IEnumerable<string> TagKeys
{
get { return _tags.Keys; }
}
public string GetTagValue(string tagKey)
{
return _tags.ContainsKey(tagKey) ? _tags[tagKey] : null;
}
public int TagsCount
{
get { return _tags.Count; }
}
public bool HasTag(string tagKey)
{
return !string.IsNullOrEmpty(tagKey) && _tags.ContainsKey(tagKey);
}
#endregion
public bool IsEqualTo(ISelectionState selection)
{
if (selection == null)
throw new ArgumentNullException("selection", "selection is null in SelectionState comparison");
if (ReferenceEquals(this, selection))
return true;
if (selection.Id != Id)
throw new Exception("Cannot compare two selections with different Ids");
bool ret = (selection.Name == null || selection.Name == this.Name) &&
this.Price == selection.Price &&
this.Tradability == selection.Tradability &&
this.Status == selection.Status;
if (IsRollingSelection)
ret &= Line == selection.Line;
if(Result != null)
{
if(selection.Result == null)
return false;
ret &= Result.IsEqualTo(selection.Result);
}
else if(selection.Result != null)
return false;
if (PlaceResult != null)
{
if (selection.PlaceResult == null)
return false;
ret &= PlaceResult.IsEqualTo(selection.PlaceResult);
}
else if (selection.PlaceResult != null)
return false;
return ret;
}
public bool IsEquivalentTo(Selection selection, bool checkTags)
{
if (selection == null)
return false;
if (selection.Id != Id)
return false;
if (checkTags)
{
if (selection.TagsCount != TagsCount)
return false;
if (selection.TagKeys.Any(tag => !HasTag(tag) || GetTagValue(tag) != selection.GetTagValue(tag)))
return false;
// if we are here, there is no difference between the stored tags
// and those contained within the selection object...
// we can then proceed to check the selection's fields
// Note that Selection.Name is a shortcut for Selection.GetTagValue("name")
// as Result and PlaceResult are only present when dealing with full snapshots
// we only check these properties if checkTags is true
if (selection.Result != null)
{
if (Result == null)
return false;
if (!Result.IsEquivalentTo(selection.Result))
return false;
}
if (selection.PlaceResult != null)
{
if (PlaceResult == null)
return false;
if (!PlaceResult.IsEquivalentTo(selection.PlaceResult))
return false;
}
}
var result = Price == selection.Price &&
Status == selection.Status &&
Tradability == selection.Tradable;
if (IsRollingSelection)
return result &= Line == ((RollingSelection)selection).Line;
return result;
}
#endregion
#region IUpdatableSelectionState
public void Update(Selection selection, bool fullSnapshot)
{
Price = selection.Price;
Status = selection.Status;
Tradability = selection.Tradable;
if (fullSnapshot)
{
_tags = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
foreach (var key in selection.TagKeys)
_tags.Add(key, selection.GetTagValue(key));
Name = selection.Name;
// Result and PlaceResult (in the context of racing fixtures)
// are only present on a full snapshot
if (selection.Result != null)
{
if (Result == null)
Result = new SelectionResultState(selection.Result);
else
((IUpdatableSelectionResultState)Result).Update(selection.Result);
}
if (selection.PlaceResult != null)
{
if (PlaceResult == null)
PlaceResult = new SelectionResultState(selection.PlaceResult);
else
((IUpdatableSelectionResultState)PlaceResult).Update(selection.PlaceResult);
}
}
UpdateLineOnRollingSelection(selection);
}
private void UpdateLineOnRollingSelection(Selection selection)
{
var rollingSelection = selection as RollingSelection;
if(rollingSelection == null)
return;
this.Line = rollingSelection.Line;
}
public IUpdatableSelectionState Clone()
{
SelectionState clone = new SelectionState
{
Id = this.Id,
Name = this.Name,
Price = this.Price,
Tradability = this.Tradability,
Status = this.Status,
Line = this.Line,
IsRollingSelection = this.IsRollingSelection
};
if (Result != null)
clone.Result = ((IUpdatableSelectionResultState)Result).Clone();
if (PlaceResult != null)
clone.PlaceResult = ((IUpdatableSelectionResultState)Result).Clone();
foreach (var key in this.TagKeys)
clone._tags.Add(key, this.GetTagValue(key));
return clone;
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Common
{
using JetBrains.Annotations;
using System;
using System.ComponentModel;
public static partial class InternalLogger
{
/// <summary>
/// Gets a value indicating whether internal log includes Trace messages.
/// </summary>
public static bool IsTraceEnabled
{
get { return LogLevel.Trace >= LogLevel; }
}
/// <summary>
/// Gets a value indicating whether internal log includes Debug messages.
/// </summary>
public static bool IsDebugEnabled
{
get { return LogLevel.Debug >= LogLevel; }
}
/// <summary>
/// Gets a value indicating whether internal log includes Info messages.
/// </summary>
public static bool IsInfoEnabled
{
get { return LogLevel.Info >= LogLevel; }
}
/// <summary>
/// Gets a value indicating whether internal log includes Warn messages.
/// </summary>
public static bool IsWarnEnabled
{
get { return LogLevel.Warn >= LogLevel; }
}
/// <summary>
/// Gets a value indicating whether internal log includes Error messages.
/// </summary>
public static bool IsErrorEnabled
{
get { return LogLevel.Error >= LogLevel; }
}
/// <summary>
/// Gets a value indicating whether internal log includes Fatal messages.
/// </summary>
public static bool IsFatalEnabled
{
get { return LogLevel.Fatal >= LogLevel; }
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the Trace level.
/// </summary>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Trace([Localizable(false)] string message, params object[] args)
{
Write(null, LogLevel.Trace, message, args);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the Trace level.
/// </summary>
/// <param name="message">Log message.</param>
public static void Trace([Localizable(false)] string message)
{
Write(null, LogLevel.Trace, message, null);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the Trace level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Trace(Exception ex, [Localizable(false)] string message, params object[] args)
{
Write(ex, LogLevel.Trace, message, args);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the Trace level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="message">Log message.</param>
public static void Trace(Exception ex, [Localizable(false)] string message)
{
Write(ex, LogLevel.Trace, message, null);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the Debug level.
/// </summary>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Debug([Localizable(false)] string message, params object[] args)
{
Write(null, LogLevel.Debug, message, args);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the Debug level.
/// </summary>
/// <param name="message">Log message.</param>
public static void Debug([Localizable(false)] string message)
{
Write(null, LogLevel.Debug, message, null);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the Debug level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Debug(Exception ex, [Localizable(false)] string message, params object[] args)
{
Write(ex, LogLevel.Debug, message, args);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the Debug level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="message">Log message.</param>
public static void Debug(Exception ex, [Localizable(false)] string message)
{
Write(ex, LogLevel.Debug, message, null);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the Info level.
/// </summary>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Info([Localizable(false)] string message, params object[] args)
{
Write(null, LogLevel.Info, message, args);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the Info level.
/// </summary>
/// <param name="message">Log message.</param>
public static void Info([Localizable(false)] string message)
{
Write(null, LogLevel.Info, message, null);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the Info level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Info(Exception ex, [Localizable(false)] string message, params object[] args)
{
Write(ex, LogLevel.Info, message, args);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the Info level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="message">Log message.</param>
public static void Info(Exception ex, [Localizable(false)] string message)
{
Write(ex, LogLevel.Info, message, null);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the Warn level.
/// </summary>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Warn([Localizable(false)] string message, params object[] args)
{
Write(null, LogLevel.Warn, message, args);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the Warn level.
/// </summary>
/// <param name="message">Log message.</param>
public static void Warn([Localizable(false)] string message)
{
Write(null, LogLevel.Warn, message, null);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the Warn level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Warn(Exception ex, [Localizable(false)] string message, params object[] args)
{
Write(ex, LogLevel.Warn, message, args);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the Warn level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="message">Log message.</param>
public static void Warn(Exception ex, [Localizable(false)] string message)
{
Write(ex, LogLevel.Warn, message, null);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the Error level.
/// </summary>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Error([Localizable(false)] string message, params object[] args)
{
Write(null, LogLevel.Error, message, args);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the Error level.
/// </summary>
/// <param name="message">Log message.</param>
public static void Error([Localizable(false)] string message)
{
Write(null, LogLevel.Error, message, null);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the Error level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Error(Exception ex, [Localizable(false)] string message, params object[] args)
{
Write(ex, LogLevel.Error, message, args);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the Error level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="message">Log message.</param>
public static void Error(Exception ex, [Localizable(false)] string message)
{
Write(ex, LogLevel.Error, message, null);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the Fatal level.
/// </summary>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Fatal([Localizable(false)] string message, params object[] args)
{
Write(null, LogLevel.Fatal, message, args);
}
/// <summary>
/// Logs the specified message without an <see cref="Exception"/> at the Fatal level.
/// </summary>
/// <param name="message">Log message.</param>
public static void Fatal([Localizable(false)] string message)
{
Write(null, LogLevel.Fatal, message, null);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the Fatal level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Fatal(Exception ex, [Localizable(false)] string message, params object[] args)
{
Write(ex, LogLevel.Fatal, message, args);
}
/// <summary>
/// Logs the specified message with an <see cref="Exception"/> at the Fatal level.
/// </summary>
/// <param name="ex">Exception to be logged.</param>
/// <param name="message">Log message.</param>
public static void Fatal(Exception ex, [Localizable(false)] string message)
{
Write(ex, LogLevel.Fatal, message, null);
}
}
}
| |
// -----------------------------------------------------------------------------------------
// <copyright file="XmlConstants.cs" company="Microsoft">
// Copyright 2013 Microsoft 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.
// </copyright>
// -----------------------------------------------------------------------------------------
namespace Sandboxable.Microsoft.WindowsAzure.Storage.Table.Queryable
{
internal static class XmlConstants
{
#region CLR / Reflection constants.
internal const string ClrServiceInitializationMethodName = "InitializeService";
#endregion CLR / Reflection constants.
#region HTTP constants.
internal const string HttpContentID = "Content-ID";
internal const string HttpContentLength = "Content-Length";
internal const string HttpContentType = "Content-Type";
internal const string HttpContentDisposition = "Content-Disposition";
internal const string HttpDataServiceVersion = "DataServiceVersion";
internal const string HttpMaxDataServiceVersion = "MaxDataServiceVersion";
internal const string HttpCacheControlNoCache = "no-cache";
internal const string HttpCharsetParameter = "charset";
internal const string HttpMethodGet = "GET";
internal const string HttpMethodPost = "POST";
internal const string HttpMethodPut = "PUT";
internal const string HttpMethodDelete = "DELETE";
internal const string HttpMethodMerge = "MERGE";
internal const string HttpQueryStringExpand = "$expand";
internal const string HttpQueryStringFilter = "$filter";
internal const string HttpQueryStringOrderBy = "$orderby";
internal const string HttpQueryStringSkip = "$skip";
internal const string HttpQueryStringTop = "$top";
internal const string HttpQueryStringInlineCount = "$inlinecount";
internal const string HttpQueryStringSkipToken = "$skiptoken";
internal const string SkipTokenPropertyPrefix = "SkipTokenProperty";
internal const string HttpQueryStringValueCount = "$count";
internal const string HttpQueryStringSelect = "$select";
internal const string HttpQValueParameter = "q";
internal const string HttpXMethod = "X-HTTP-Method";
internal const string HttpRequestAccept = "Accept";
internal const string HttpRequestAcceptCharset = "Accept-Charset";
internal const string HttpRequestIfMatch = "If-Match";
internal const string HttpRequestIfNoneMatch = "If-None-Match";
internal const string HttpMultipartBoundary = "boundary";
#if ASTORIA_CLIENT
internal const string HttpMultipartBoundaryBatch = "batch";
internal const string HttpMultipartBoundaryChangeSet = "changeset";
#endif
internal const string HttpResponseAllow = "Allow";
internal const string HttpResponseCacheControl = "Cache-Control";
internal const string HttpResponseETag = "ETag";
internal const string HttpResponseLocation = "Location";
internal const string HttpResponseStatusCode = "Status-Code";
internal const string HttpMultipartBoundaryBatchResponse = "batchresponse";
internal const string HttpMultipartBoundaryChangesetResponse = "changesetresponse";
internal const string HttpContentTransferEncoding = "Content-Transfer-Encoding";
internal const string HttpVersionInBatching = "HTTP/1.1";
internal const string HttpAnyETag = "*";
internal const string HttpWeakETagPrefix = "W/\"";
internal const string HttpAcceptCharset = "Accept-Charset";
internal const string HttpCookie = "Cookie";
internal const string HttpSlug = "Slug";
#endregion HTTP constants.
#region MIME constants.
internal const string MimeAny = "*/*";
internal const string MimeApplicationAtom = "application/atom+xml";
internal const string MimeApplicationAtomService = "application/atomsvc+xml";
internal const string MimeApplicationJson = "application/json";
internal const string MimeApplicationOctetStream = "application/octet-stream";
internal const string MimeApplicationHttp = "application/http";
internal const string MimeApplicationType = "application";
internal const string MimeApplicationXml = "application/xml";
internal const string MimeJsonSubType = "json";
internal const string MimeMetadata = MimeApplicationXml;
internal const string MimeMultiPartMixed = "multipart/mixed";
internal const string MimeTextPlain = "text/plain";
internal const string MimeTextType = "text";
internal const string MimeTextXml = "text/xml";
internal const string MimeXmlSubType = "xml";
internal const string BatchRequestContentTransferEncoding = "binary";
#if ASTORIA_CLIENT
internal const string LinkMimeTypeFeed = "application/atom+xml;type=feed";
internal const string LinkMimeTypeEntry = "application/atom+xml;type=entry";
internal const string Utf8Encoding = "UTF-8";
internal const string MimeTypeUtf8Encoding = ";charset=" + Utf8Encoding;
#endif
#endregion MIME constants.
#region URI constants.
internal const string UriHttpAbsolutePrefix = "http://host";
internal const string UriMetadataSegment = "$metadata";
internal const string UriValueSegment = "$value";
internal const string UriBatchSegment = "$batch";
internal const string UriLinkSegment = "$links";
internal const string UriCountSegment = "$count";
internal const string UriRowCountAllOption = "allpages";
internal const string UriRowCountOffOption = "none";
#endregion URI constants.
#region WCF constants.
internal const string WcfBinaryElementName = "Binary";
#endregion WCF constants.
#region ATOM constants
internal const string AtomContentElementName = "content";
internal const string AtomEntryElementName = "entry";
internal const string AtomFeedElementName = "feed";
#if ASTORIA_CLIENT
internal const string AtomAuthorElementName = "author";
internal const string AtomContributorElementName = "contributor";
internal const string AtomCategoryElementName = "category";
internal const string AtomCategorySchemeAttributeName = "scheme";
internal const string AtomCategoryTermAttributeName = "term";
internal const string AtomIdElementName = "id";
internal const string AtomLinkElementName = "link";
internal const string AtomLinkRelationAttributeName = "rel";
internal const string AtomContentSrcAttributeName = "src";
internal const string AtomLinkNextAttributeString = "next";
#endif
internal const string MetadataAttributeEpmContentKind = "FC_ContentKind";
internal const string MetadataAttributeEpmKeepInContent = "FC_KeepInContent";
internal const string MetadataAttributeEpmNsPrefix = "FC_NsPrefix";
internal const string MetadataAttributeEpmNsUri = "FC_NsUri";
internal const string MetadataAttributeEpmTargetPath = "FC_TargetPath";
internal const string MetadataAttributeEpmSourcePath = "FC_SourcePath";
internal const string SyndAuthorEmail = "SyndicationAuthorEmail";
internal const string SyndAuthorName = "SyndicationAuthorName";
internal const string SyndAuthorUri = "SyndicationAuthorUri";
internal const string SyndPublished = "SyndicationPublished";
internal const string SyndRights = "SyndicationRights";
internal const string SyndSummary = "SyndicationSummary";
internal const string SyndTitle = "SyndicationTitle";
internal const string AtomUpdatedElementName = "updated";
internal const string SyndContributorEmail = "SyndicationContributorEmail";
internal const string SyndContributorName = "SyndicationContributorName";
internal const string SyndContributorUri = "SyndicationContributorUri";
internal const string SyndUpdated = "SyndicationUpdated";
internal const string SyndContentKindPlaintext = "text";
internal const string SyndContentKindHtml = "html";
internal const string SyndContentKindXHtml = "xhtml";
internal const string AtomHRefAttributeName = "href";
internal const string AtomSummaryElementName = "summary";
internal const string AtomNameElementName = "name";
internal const string AtomEmailElementName = "email";
internal const string AtomUriElementName = "uri";
internal const string AtomPublishedElementName = "published";
internal const string AtomRightsElementName = "rights";
internal const string AtomPublishingCollectionElementName = "collection";
internal const string AtomPublishingServiceElementName = "service";
internal const string AtomPublishingWorkspaceDefaultValue = "Default";
internal const string AtomPublishingWorkspaceElementName = "workspace";
internal const string AtomTitleElementName = "title";
internal const string AtomTypeAttributeName = "type";
internal const string AtomSelfRelationAttributeValue = "self";
internal const string AtomEditRelationAttributeValue = "edit";
internal const string AtomEditMediaRelationAttributeValue = "edit-media";
internal const string AtomNullAttributeName = "null";
internal const string AtomETagAttributeName = "etag";
internal const string AtomInlineElementName = "inline";
internal const string AtomPropertiesElementName = "properties";
internal const string RowCountElement = "count";
#endregion ATOM constants
#region XML constants.
internal const string XmlCollectionItemElementName = "element";
internal const string XmlErrorElementName = "error";
internal const string XmlErrorCodeElementName = "code";
internal const string XmlErrorInnerElementName = "innererror";
internal const string XmlErrorInternalExceptionElementName = "internalexception";
internal const string XmlErrorTypeElementName = "type";
internal const string XmlErrorStackTraceElementName = "stacktrace";
internal const string XmlErrorMessageElementName = "message";
internal const string XmlFalseLiteral = "false";
internal const string XmlTrueLiteral = "true";
internal const string XmlInfinityLiteral = "INF";
internal const string XmlNaNLiteral = "NaN";
internal const string XmlBaseAttributeName = "base";
internal const string XmlLangAttributeName = "lang";
internal const string XmlSpaceAttributeName = "space";
internal const string XmlSpacePreserveValue = "preserve";
internal const string XmlBaseAttributeNameWithPrefix = "xml:base";
#endregion XML constants.
#region XML namespaces.
internal const string EdmV1Namespace = "http://schemas.microsoft.com/ado/2006/04/edm";
internal const string EdmV1dot1Namespace = "http://schemas.microsoft.com/ado/2007/05/edm";
internal const string EdmV1dot2Namespace = "http://schemas.microsoft.com/ado/2008/01/edm";
internal const string EdmV2Namespace = "http://schemas.microsoft.com/ado/2008/09/edm";
internal const string DataWebNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices";
internal const string DataWebMetadataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
internal const string DataWebRelatedNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/related/";
internal const string DataWebSchemeNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme";
internal const string AppNamespace = "http://www.w3.org/2007/app";
internal const string AtomNamespace = "http://www.w3.org/2005/Atom";
internal const string XmlnsNamespacePrefix = "xmlns";
internal const string XmlNamespacePrefix = "xml";
internal const string DataWebNamespacePrefix = "d";
internal const string DataWebMetadataNamespacePrefix = "m";
internal const string XmlNamespacesNamespace = "http://www.w3.org/2000/xmlns/";
internal const string EdmxNamespace = "http://schemas.microsoft.com/ado/2007/06/edmx";
internal const string EdmxNamespacePrefix = "edmx";
#endregion XML namespaces.
#region CDM Schema Xml NodeNames
#region Constant node names in the CDM schema xml
internal const string Association = "Association";
internal const string AssociationSet = "AssociationSet";
internal const string ComplexType = "ComplexType";
internal const string Dependent = "Dependent";
internal const string EdmCollectionTypeFormat = "Collection({0})";
internal const string EdmEntitySetAttributeName = "EntitySet";
internal const string EdmFunctionImportElementName = "FunctionImport";
internal const string EdmModeAttributeName = "Mode";
internal const string EdmModeInValue = "In";
internal const string EdmParameterElementName = "Parameter";
internal const string EdmReturnTypeAttributeName = "ReturnType";
internal const string End = "End";
internal const string EntityType = "EntityType";
internal const string EntityContainer = "EntityContainer";
internal const string Key = "Key";
internal const string NavigationProperty = "NavigationProperty";
internal const string OnDelete = "OnDelete";
internal const string Principal = "Principal";
internal const string Property = "Property";
internal const string PropertyRef = "PropertyRef";
internal const string ReferentialConstraint = "ReferentialConstraint";
internal const string Role = "Role";
internal const string Schema = "Schema";
internal const string EdmxElement = "Edmx";
internal const string EdmxDataServicesElement = "DataServices";
internal const string EdmxVersion = "Version";
internal const string EdmxVersionValue = "1.0";
#endregion //Constant node names in the CDM schema xml
#region const attribute names in the CDM schema XML
internal const string Action = "Action";
internal const string BaseType = "BaseType";
internal const string EntitySet = "EntitySet";
internal const string FromRole = "FromRole";
internal const string Abstract = "Abstract";
internal const string Multiplicity = "Multiplicity";
internal const string Name = "Name";
internal const string Namespace = "Namespace";
internal const string ToRole = "ToRole";
internal const string Type = "Type";
internal const string Relationship = "Relationship";
#endregion //const attribute names in the CDM schema XML
#region values for multiplicity in Edm
internal const string Many = "*";
internal const string One = "1";
internal const string ZeroOrOne = "0..1";
#endregion
#region Edm Facets Names and Values
internal const string Nullable = "Nullable";
internal const string ConcurrencyAttribute = "ConcurrencyMode";
internal const string ConcurrencyFixedValue = "Fixed";
#endregion
#endregion
#region DataWeb Elements and Attributes.
internal const string DataWebMimeTypeAttributeName = "MimeType";
internal const string DataWebOpenTypeAttributeName = "OpenType";
internal const string DataWebAccessHasStreamAttribute = "HasStream";
internal const string DataWebAccessDefaultStreamPropertyValue = "true";
internal const string IsDefaultEntityContainerAttribute = "IsDefaultEntityContainer";
internal const string ServiceOperationHttpMethodName = "HttpMethod";
internal const string UriElementName = "uri";
internal const string NextElementName = "next";
internal const string LinkCollectionElementName = "links";
#endregion DataWeb Elements and Attributes.
#region JSON Format constants
internal const string JsonError = "error";
internal const string JsonErrorCode = "code";
internal const string JsonErrorInner = "innererror";
internal const string JsonErrorInternalException = "internalexception";
internal const string JsonErrorMessage = "message";
internal const string JsonErrorStackTrace = "stacktrace";
internal const string JsonErrorType = "type";
internal const string JsonErrorValue = "value";
internal const string JsonMetadataString = "__metadata";
internal const string JsonUriString = "uri";
internal const string JsonTypeString = "type";
internal const string JsonEditMediaString = "edit_media";
internal const string JsonMediaSrcString = "media_src";
internal const string JsonContentTypeString = "content_type";
internal const string JsonMediaETagString = "media_etag";
internal const string JsonDeferredString = "__deferred";
internal const string JsonETagString = "etag";
internal const string JsonRowCountString = "__count";
internal const string JsonNextString = "__next";
#endregion //JSON Format constants
#region Edm Primitive Type Names
internal const string EdmNamespace = "Edm";
internal const string EdmBinaryTypeName = "Edm.Binary";
internal const string EdmBooleanTypeName = "Edm.Boolean";
internal const string EdmByteTypeName = "Edm.Byte";
internal const string EdmDateTimeTypeName = "Edm.DateTime";
internal const string EdmDecimalTypeName = "Edm.Decimal";
internal const string EdmDoubleTypeName = "Edm.Double";
internal const string EdmGuidTypeName = "Edm.Guid";
internal const string EdmSingleTypeName = "Edm.Single";
internal const string EdmSByteTypeName = "Edm.SByte";
internal const string EdmInt16TypeName = "Edm.Int16";
internal const string EdmInt32TypeName = "Edm.Int32";
internal const string EdmInt64TypeName = "Edm.Int64";
internal const string EdmStringTypeName = "Edm.String";
#endregion
#region Astoria Constants
internal const string DataServiceVersion1Dot0 = "1.0";
internal const string DataServiceVersion2Dot0 = "2.0";
internal const string DataServiceVersion3Dot0 = "3.0";
internal const string DataServiceVersionCurrent = DataServiceVersion3Dot0 + ";";
internal const int DataServiceVersionCurrentMajor = 1;
internal const int DataServiceVersionCurrentMinor = 0;
internal const string LiteralPrefixBinary = "binary";
internal const string LiteralPrefixDateTime = "datetime";
internal const string LiteralPrefixGuid = "guid";
internal const string XmlBinaryPrefix = "X";
internal const string XmlDecimalLiteralSuffix = "M";
internal const string XmlInt64LiteralSuffix = "L";
internal const string XmlSingleLiteralSuffix = "f";
internal const string XmlDoubleLiteralSuffix = "D";
internal const string NullLiteralInETag = "null";
internal const string MicrosoftDataServicesRequestUri = "MicrosoftDataServicesRequestUri";
internal const string MicrosoftDataServicesRootUri = "MicrosoftDataServicesRootUri";
#endregion
#region EF constants
internal const string StoreGeneratedPattern = "http://schemas.microsoft.com/ado/2006/04/edm/ssdl:StoreGeneratedPattern";
#endregion //EF constants
}
}
| |
// -------------------------------------
// Domain : Avariceonline.com
// Author : Nicholas Ventimiglia
// Product : Unity3d Foundation
// Published : 2015
// -------------------------------------
using System;
using System.Linq;
using UnityEngine;
#if UNITY_WSA && !UNITY_EDITOR
using System.Reflection;
#endif
namespace Foundation.Databinding
{
/// <summary>
/// Base DataBinder. Used by presentation layer.
/// Depended on a (parent) BindingContext to mediate to the model
/// </summary>
/// <remarks>
/// If you want to write your own databinder, inherit from this.
/// </remarks>
[Serializable]
[ExecuteInEditMode]
public abstract class BindingBase : MonoBehaviour, IBindingElement
{
#region child
public enum BindingFilter
{
/// <summary>
/// void Methods or Coroutines
/// </summary>
Commands,
/// <summary>
/// Properties or Fields
/// </summary>
Properties
}
/// <summary>
/// PropertyBinder Child Item
/// </summary>
[Serializable]
public class BindingInfo
{
/// <summary>
/// Control Property that is being bound
/// </summary>
public string BindingName;
/// <summary>
/// Member Filter
/// </summary>
public BindingFilter Filters;
/// <summary>
/// Return Type Filter
/// </summary>
public Type[] FilterTypes;
/// <summary>
/// Model Property/Method bound to
/// </summary>
public string MemberName;
/// <summary>
/// Action invoked with this binding
/// </summary>
public Action<object> Action { get; set; }
/// <summary>
/// should show option
/// </summary>
public Func<bool> ShouldShow { get; set; }
}
#endregion
#region settings
/// <summary>
/// For binding to another object within the ui hierarchy
/// </summary>
/// <remarks>
/// For Master / Details situations.
/// </remarks>
public GameObject BindingProxy;
/// <summary>
/// Prints Debug messages. This can get spammy.
/// </summary>
public bool DebugMode;
#endregion
#region Props
[HideInInspector] private IObservableModel _model;
/// <summary>
/// Bound Model
/// </summary>
public IObservableModel Model
{
get { return _model; }
set
{
if (_model == value)
return;
if (DebugMode && Application.isPlaying)
{
Debug.Log(GetInstanceID() + ":" + name + ": " + "SetModel : " + value);
}
BeforeModelChanged();
_model = value;
OnModelChanged();
}
}
[HideInInspector] private BindingContext _context;
/// <summary>
/// Binding Root
/// </summary>
public BindingContext Context
{
get { return _context; }
set
{
if (_context == value)
return;
if (DebugMode && Application.isPlaying)
{
Debug.Log(GetInstanceID() + ":" + name + ": " + "Context Set :" + value);
}
if (_context != null)
_context.UnsubscribeBinder(this);
_context = value;
if (_context != null)
_context.SubscribeBinder(this);
}
}
/// <summary>
/// True if OnApplicationQuit was called
/// </summary>
public virtual bool IsApplicationQuit { get; protected set; }
#endregion
#region Internal
/// <summary>
/// find _root and bind
/// </summary>
protected virtual void OnEnable()
{
if (DebugMode && Application.isPlaying)
{
Debug.Log(GetInstanceID() + ":" + name + ": " + "OnEnable");
}
FindContext();
}
/// <summary>
/// release from _root
/// </summary>
protected virtual void OnDisable()
{
// Dont reset in editor.
if (!Application.isPlaying)
return;
if (IsApplicationQuit)
return;
if (DebugMode && Application.isPlaying)
{
Debug.Log(GetInstanceID() + ":" + name + ": " + "OnDisable");
}
Context = null;
Model = null;
}
/// <summary>
/// Handles UnityEngine ApplicationQuit event
/// </summary>
protected virtual void OnApplicationQuit()
{
IsApplicationQuit = true;
}
/// <summary>
/// Finds the BindingContext in parent
/// </summary>
[ContextMenu("Find BindingContext")]
public void FindContext()
{
Context = BindingProxy == null
? gameObject.FindInParent<BindingContext>()
: BindingProxy.FindInParent<BindingContext>();
if (BindingProxy != null && Context == null)
Debug.LogError("Invalid BindingProxy. Please bind to a BindingContext or its child.");
}
[ContextMenu("Debug Info")]
public virtual void DebugInfo()
{
Debug.Log("Context : " + Context);
Debug.Log("Model : " + (Model == null ? "null" : Model.ToString()));
Debug.Log("Bindings");
foreach (var info in GetBindingInfos())
{
Debug.Log("Member : " + info.MemberName + ", " + info.BindingName);
}
}
#endregion
#region protected
/// <summary>
/// helper. Calls the GetValue method on the Model
/// </summary>
protected object GetValue(string memberName)
{
if (Model == null)
{
Debug.LogWarning("Model is null ! " + gameObject.name + " " + GetType());
return null;
}
return Model.GetValue(memberName);
}
/// <summary>
/// helper. Calls the GetValue method on the Model
/// </summary>
protected object GetValue(string memberName, object argument)
{
if (Model == null)
{
Debug.LogWarning("Model is null ! " + gameObject.name + " " + GetType());
return null;
}
return Model.GetValue(memberName);
}
/// <summary>
/// helper. Calls the SetValue method on the model
/// </summary>
/// <param name="memberName"></param>
/// <param name="argument"></param>
protected void SetValue(string memberName, object argument)
{
if (!enabled)
return;
if (IsApplicationQuit)
return;
if (string.IsNullOrEmpty(memberName))
return;
if (Model == null)
{
// Debug.LogWarning("Model is null ! " + gameObject.name + " " + GetType() + GetInstanceID() + " / " + gameObject.transform.GetInstanceID());
// Debug.LogWarning("Where is this behavior ?");
return;
}
if (argument == null)
{
Model.Command(memberName);
}
else
{
Model.Command(memberName, argument);
}
}
#endregion
#region virtual
/// <summary>
/// Handle all change notification here
/// </summary>
/// <param name="m"></param>
public virtual void OnBindingMessage(ObservableMessage m)
{
// ignore if editor
if (!Application.isPlaying)
return;
if (Model == null)
return;
if (!enabled)
return;
var bindings = GetBindingInfos().Where(o => o.MemberName == m.Name && o.Action != null).ToArray();
foreach (var binding in bindings)
{
if (binding.Action != null)
binding.Action(m.Value);
}
}
/// <summary>
/// Any cleanup logic goes here
/// </summary>
protected virtual void BeforeModelChanged()
{
}
/// <summary>
/// Any setup logic for the model goes here
/// </summary>
protected virtual void OnModelChanged()
{
// ignore if editor
if (!Application.isPlaying)
return;
if (Model == null)
return;
if (!enabled)
return;
foreach (var binding in GetBindingInfos())
{
if (string.IsNullOrEmpty(binding.MemberName))
continue;
if (binding.Action == null)
continue;
binding.Action(GetValue(binding.MemberName));
}
}
public void OnBindingRefresh()
{
OnModelChanged();
}
/// <summary>
/// And setup logic here
/// </summary>
/// <remarks>
/// Add Bindings
/// </remarks>
public abstract void Init();
protected BindingInfo[] _infoCache;
/// <summary>
/// Returns binding listeners
/// </summary>
/// <returns></returns>
public BindingInfo[] GetBindingInfos()
{
#if UNITY_EDITOR
return GetType().GetFields()
.Where(o => o.FieldType == typeof (BindingInfo))
.Select(o => o.GetValue(this))
.Cast<BindingInfo>()
.ToArray();
#elif UNITY_WSA
if(_infoCache == null)
_infoCache = GetType().GetRuntimeFields()
.Where(o => o.FieldType == typeof(BindingInfo))
.Select(o => o.GetValue(this))
.Cast<BindingInfo>()
.ToArray();
return _infoCache;
#else
if (_infoCache == null)
_infoCache = GetType().GetFields()
.Where(o => o.FieldType == typeof(BindingInfo))
.Select(o => o.GetValue(this))
.Cast<BindingInfo>()
.ToArray();
return _infoCache;
#endif
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
using System;
namespace MIGAZ.Models.ARM
{
public class Extension : Resource
{
public Extension()
{
type = "extensions";
apiVersion = "2015-06-15";
}
}
public class Extension_Properties
{
public string publisher;
public string type;
public string typeHandlerVersion;
public bool autoUpgradeMinorVersion;
public Dictionary<string, string> settings;
}
public class VirtualNetworkGateway : Resource
{
public VirtualNetworkGateway()
{
type = "Microsoft.Network/virtualNetworkGateways";
apiVersion = "2015-06-15";
}
}
public class VirtualNetworkGateway_Properties
{
public List<IpConfiguration> ipConfigurations;
public VirtualNetworkGateway_Sku sku;
public string gatewayType; // VPN or ER
public string vpnType; // RouteBased or PolicyBased
public string enableBgp = "false";
public VPNClientConfiguration vpnClientConfiguration;
}
public class VirtualNetworkGateway_Sku
{
public string name;
public string tier;
}
public class LocalNetworkGateway : Resource
{
public LocalNetworkGateway()
{
type = "Microsoft.Network/localNetworkGateways";
apiVersion = "2015-06-15";
}
}
public class LocalNetworkGateway_Properties
{
public AddressSpace localNetworkAddressSpace;
public string gatewayIpAddress;
}
public class GatewayConnection : Resource
{
public GatewayConnection()
{
type = "Microsoft.Network/connections";
apiVersion = "2015-06-15";
}
}
public class GatewayConnection_Properties
{
public Reference virtualNetworkGateway1;
public Reference localNetworkGateway2;
public string connectionType;
public long routingWeight = 10;
public string sharedKey;
}
public class VPNClientConfiguration
{
public AddressSpace vpnClientAddressPool;
public List<VPNClientCertificate> vpnClientRootCertificates;
public List<VPNClientCertificate> vpnClientRevokedCertificates;
}
public class VPNClientCertificate
{
public string name;
public VPNClientCertificate_Properties properties;
}
public class VPNClientCertificate_Properties
{
public string PublicCertData;
public string Thumbprint;
}
public class RouteTable : Resource
{
public RouteTable()
{
type = "Microsoft.Network/routeTables";
apiVersion = "2015-06-15";
}
}
public class RouteTable_Properties
{
public List<Route> routes;
}
public class Route
{
public string name;
public Route_Properties properties;
}
public class Route_Properties
{
public string addressPrefix;
public string nextHopType;
public string nextHopIpAddress;
}
public class NetworkSecurityGroup : Resource
{
public NetworkSecurityGroup()
{
type = "Microsoft.Network/networkSecurityGroups";
apiVersion = "2015-06-15";
}
}
public class NetworkSecurityGroup_Properties
{
public List<SecurityRule> securityRules;
}
public class SecurityRule
{
public string name;
public SecurityRule_Properties properties;
}
public class SecurityRule_Properties
{
public string description;
public string protocol;
public string sourcePortRange;
public string destinationPortRange;
public string sourceAddressPrefix;
public string destinationAddressPrefix;
public string access;
public long priority;
public string direction;
}
public class VirtualNetwork : Resource
{
public VirtualNetwork()
{
type = "Microsoft.Network/virtualNetworks";
apiVersion = "2015-06-15";
}
}
public class AddressSpace
{
public List<string> addressPrefixes;
}
public class VirtualNetwork_Properties
{
public AddressSpace addressSpace;
public List<Subnet> subnets;
public VirtualNetwork_dhcpOptions dhcpOptions;
}
public class Subnet
{
public string name;
public Subnet_Properties properties;
}
public class Subnet_Properties
{
public string addressPrefix;
public Reference networkSecurityGroup;
public Reference routeTable;
}
public class VirtualNetwork_dhcpOptions
{
public List<string> dnsServers;
}
public class StorageAccount : Resource
{
public StorageAccount()
{
type = "Microsoft.Storage/storageAccounts";
apiVersion = "2015-06-15";
}
}
public class StorageAccount_Properties
{
public string accountType;
}
public class LoadBalancer : Resource
{
public LoadBalancer()
{
type = "Microsoft.Network/loadBalancers";
apiVersion = "2015-06-15";
}
}
public class LoadBalancer_Properties
{
public List<FrontendIPConfiguration> frontendIPConfigurations;
public List<Hashtable> backendAddressPools;
public List<InboundNatRule> inboundNatRules;
public List<LoadBalancingRule> loadBalancingRules;
public List<Probe> probes;
}
public class FrontendIPConfiguration
{
public string name = "default";
public FrontendIPConfiguration_Properties properties;
}
public class FrontendIPConfiguration_Properties
{
public Reference publicIPAddress;
public string privateIPAllocationMethod;
public string privateIPAddress;
public Reference subnet;
}
public class InboundNatRule
{
public string name;
public InboundNatRule_Properties properties;
}
public class InboundNatRule_Properties
{
public long frontendPort;
public long backendPort;
public string protocol;
public Reference frontendIPConfiguration;
}
public class LoadBalancingRule
{
public string name;
public LoadBalancingRule_Properties properties;
}
public class LoadBalancingRule_Properties
{
public Reference frontendIPConfiguration;
public Reference backendAddressPool;
public Reference probe;
public string protocol;
public long frontendPort;
public long backendPort;
public long idleTimeoutInMinutes = 15;
public string loadDistribution = "SourceIP";
public bool enableFloatingIP = false;
}
public class Probe
{
public string name;
public Probe_Properties properties;
}
public class Probe_Properties
{
public string protocol;
public long port;
public long intervalInSeconds = 15;
public long numberOfProbes = 2;
public string requestPath;
}
public class PublicIPAddress : Resource
{
public PublicIPAddress()
{
type = "Microsoft.Network/publicIPAddresses";
apiVersion = "2015-06-15";
}
}
public class PublicIPAddress_Properties
{
public string publicIPAllocationMethod = "Dynamic";
public Hashtable dnsSettings;
}
public class NetworkInterface : Resource
{
public NetworkInterface()
{
type = "Microsoft.Network/networkInterfaces";
apiVersion = "2015-06-15";
}
}
public class NetworkInterface_Properties
{
public List<IpConfiguration> ipConfigurations;
public bool enableIPForwarding = false;
public Reference NetworkSecurityGroup;
}
public class IpConfiguration
{
public string name;
public IpConfiguration_Properties properties;
}
public class IpConfiguration_Properties
{
public string privateIPAllocationMethod = "Dynamic";
public string privateIPAddress;
public Reference publicIPAddress;
public Reference subnet;
public List<Reference> loadBalancerBackendAddressPools;
public List<Reference> loadBalancerInboundNatRules;
}
public class AvailabilitySet : Resource
{
public AvailabilitySet()
{
type = "Microsoft.Compute/availabilitySets";
apiVersion = "2015-06-15";
}
}
public class VirtualMachine : Resource
{
public List<Resource> resources;
public VirtualMachine()
{
type = "Microsoft.Compute/virtualMachines";
apiVersion = "2015-06-15";
}
}
public class VirtualMachine_Properties
{
public HardwareProfile hardwareProfile;
public Reference availabilitySet;
public OsProfile osProfile;
public StorageProfile storageProfile;
public NetworkProfile networkProfile;
public DiagnosticsProfile diagnosticsProfile;
}
public class HardwareProfile
{
public string vmSize;
}
public class OsProfile
{
public string computerName;
public string adminUsername;
public string adminPassword;
}
public class StorageProfile
{
public ImageReference imageReference;
public OsDisk osDisk;
public List<DataDisk> dataDisks;
}
public class ImageReference
{
public string publisher;
public string offer;
public string sku;
public string version;
}
public class OsDisk
{
public string name;
public string osType;
public Vhd vhd;
public string caching;
public string createOption;
}
public class DataDisk
{
public string name;
public Vhd vhd;
public string caching;
public string createOption;
public long diskSizeGB;
public long lun;
}
public class Vhd
{
public string uri;
}
public class NetworkProfile
{
public List<NetworkProfile_NetworkInterface> networkInterfaces;
}
public class NetworkProfile_NetworkInterface
{
public string id;
public NetworkProfile_NetworkInterface_Properties properties;
}
public class NetworkProfile_NetworkInterface_Properties
{
public bool primary = true;
}
public class DiagnosticsProfile
{
public BootDiagnostics bootDiagnostics;
}
public class BootDiagnostics
{
public bool enabled;
public string storageUri;
}
public class Reference
{
public string id;
}
public class Resource
{
public string type;
public string apiVersion;
public string name;
public string location = "[resourceGroup().location]";
public Dictionary<string, string> tags;
public List<string> dependsOn;
public object properties;
public Resource()
{
if (app.Default.AllowTag)
{
tags = new Dictionary<string, string>();
tags.Add("migAz", app.Default.ExecutionId);
}
}
}
public class Parameter
{
public string type;
}
public class Template
{
public string schemalink = "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#";
public string contentVersion = "1.0.0.0";
public Dictionary<string, Parameter> parameters;
public Dictionary<string, string> variables;
public List<Resource> resources;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Internal.Runtime.InteropServices.WindowsRuntime;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
#region class StreamOperationAsyncResult
internal abstract partial class StreamOperationAsyncResult : IAsyncResult
{
private AsyncCallback _userCompletionCallback = null;
private object _userAsyncStateInfo = null;
private IAsyncInfo _asyncStreamOperation = null;
private volatile bool _completed = false;
private volatile bool _callbackInvoked = false;
private volatile ManualResetEvent _waitHandle = null;
private long _bytesCompleted = 0;
private ExceptionDispatchInfo _errorInfo = null;
private readonly bool _processCompletedOperationInCallback;
private IAsyncInfo _completedOperation = null;
protected internal StreamOperationAsyncResult(IAsyncInfo asyncStreamOperation,
AsyncCallback userCompletionCallback, object userAsyncStateInfo,
bool processCompletedOperationInCallback)
{
if (asyncStreamOperation == null)
throw new ArgumentNullException("asyncReadOperation");
_userCompletionCallback = userCompletionCallback;
_userAsyncStateInfo = userAsyncStateInfo;
_asyncStreamOperation = asyncStreamOperation;
_completed = false;
_callbackInvoked = false;
_bytesCompleted = 0;
_errorInfo = null;
_processCompletedOperationInCallback = processCompletedOperationInCallback;
}
public object AsyncState
{
get { return _userAsyncStateInfo; }
}
internal bool ProcessCompletedOperationInCallback
{
get { return _processCompletedOperationInCallback; }
}
public WaitHandle AsyncWaitHandle
{
get
{
ManualResetEvent wh = _waitHandle;
if (wh != null)
return wh;
// What if someone calls this public property and decides to wait on it?
// > Use 'completed' in the ctor - this way the handle wait will return as appropriate.
wh = new ManualResetEvent(_completed);
ManualResetEvent otherHandle = Interlocked.CompareExchange(ref _waitHandle, wh, null);
// We lost the race. Dispose OUR handle and return OTHER handle:
if (otherHandle != null)
{
wh.Dispose();
return otherHandle;
}
// We won the race. Return OUR new handle:
return wh;
}
}
public bool CompletedSynchronously
{
get { return false; }
}
public bool IsCompleted
{
get { return _completed; }
}
internal void Wait()
{
if (_completed)
return;
WaitHandle wh = AsyncWaitHandle;
while (_completed == false)
wh.WaitOne();
}
internal long BytesCompleted
{
get { return _bytesCompleted; }
}
internal bool HasError
{
get { return _errorInfo != null; }
}
internal void ThrowCachedError()
{
if (_errorInfo == null)
return;
_errorInfo.Throw();
}
internal bool CancelStreamOperation()
{
if (_callbackInvoked)
return false;
if (_asyncStreamOperation != null)
{
_asyncStreamOperation.Cancel();
_asyncStreamOperation = null;
}
return true;
}
internal void CloseStreamOperation()
{
try
{
if (_asyncStreamOperation != null)
_asyncStreamOperation.Close();
}
catch { }
_asyncStreamOperation = null;
}
~StreamOperationAsyncResult()
{
// This finalisation is not critical, but we can still make an effort to notify the underlying WinRT stream
// that we are not any longer interested in the results:
CancelStreamOperation();
}
internal abstract void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted);
private static void ProcessCompletedOperation_InvalidOperationThrowHelper(ExceptionDispatchInfo errInfo, string errMsg)
{
Exception errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
if (errInfoSrc == null)
throw new InvalidOperationException(errMsg);
else
throw new InvalidOperationException(errMsg, errInfoSrc);
}
internal void ProcessCompletedOperation()
{
// The error handling is slightly tricky here:
// Before processing the IO results, we are verifying some basic assumptions and if they do not hold, we are
// throwing InvalidOperation. However, by the time this method is called, we might have already stored something
// into errorInfo, e.g. if an error occurred in StreamOperationCompletedCallback. If that is the case, then that
// previous exception might include some important info relevant for detecting the problem. So, we take that
// previous exception and attach it as the inner exception to the InvalidOperationException being thrown.
// In cases where we have a good understanding of the previously saved errorInfo, and we know for sure that it
// the immediate reason for the state validation to fail, we can avoid throwing InvalidOperation altogether
// and only rethrow the errorInfo.
if (!_callbackInvoked)
ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_CannotCallThisMethodInCurrentState);
if (!_processCompletedOperationInCallback && !_completed)
ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_CannotCallThisMethodInCurrentState);
if (_completedOperation == null)
{
ExceptionDispatchInfo errInfo = _errorInfo;
Exception errInfoSrc = (errInfo == null) ? null : errInfo.SourceException;
// See if errorInfo is set because we observed completedOperation == null previously (being slow is Ok on error path):
if (errInfoSrc != null && errInfoSrc is NullReferenceException
&& SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo.Equals(errInfoSrc.Message))
{
errInfo.Throw();
}
else
{
throw new InvalidOperationException(SR.InvalidOperation_CannotCallThisMethodInCurrentState);
}
}
if (_completedOperation.Id != _asyncStreamOperation.Id)
ProcessCompletedOperation_InvalidOperationThrowHelper(_errorInfo, SR.InvalidOperation_UnexpectedAsyncOperationID);
if (_completedOperation.Status == AsyncStatus.Error)
{
_bytesCompleted = 0;
ThrowWithIOExceptionDispatchInfo(_completedOperation.ErrorCode);
}
ProcessConcreteCompletedOperation(_completedOperation, out _bytesCompleted);
}
internal void StreamOperationCompletedCallback(IAsyncInfo completedOperation, AsyncStatus unusedCompletionStatus)
{
try
{
if (_callbackInvoked)
throw new InvalidOperationException(SR.InvalidOperation_MultipleIOCompletionCallbackInvocation);
_callbackInvoked = true;
// This happens in rare stress cases in Console mode and the WinRT folks said they are unlikely to fix this in Dev11.
// Moreover, this can happen if the underlying WinRT stream has a faulty user implementation.
// If we did not do this check, we would either get the same exception without the explaining message when dereferencing
// completedOperation later, or we will get an InvalidOperation when processing the Op. With the check, they will be
// aggregated and the user will know what went wrong.
if (completedOperation == null)
throw new NullReferenceException(SR.NullReference_IOCompletionCallbackCannotProcessNullAsyncInfo);
_completedOperation = completedOperation;
// processCompletedOperationInCallback == false indicates that the stream is doing a blocking wait on the waitHandle of this IAsyncResult.
// In that case calls on completedOperation may deadlock if completedOperation is not free threaded.
// By setting processCompletedOperationInCallback to false the stream that created this IAsyncResult indicated that it
// will call ProcessCompletedOperation after the waitHandle is signalled to fetch the results.
if (_processCompletedOperationInCallback)
ProcessCompletedOperation();
}
catch (Exception ex)
{
_bytesCompleted = 0;
_errorInfo = ExceptionDispatchInfo.Capture(ex);
}
finally
{
_completed = true;
Interlocked.MemoryBarrier();
// From this point on, AsyncWaitHandle would create a handle that is readily set,
// so we do not need to check if it is being produced asynchronously.
if (_waitHandle != null)
_waitHandle.Set();
}
if (_userCompletionCallback != null)
_userCompletionCallback(this);
}
private void ThrowWithIOExceptionDispatchInfo(Exception e)
{
WinRtIOHelper.NativeExceptionToIOExceptionInfo(ExceptionSupport.AttachRestrictedErrorInfo(_completedOperation.ErrorCode)).Throw();
}
} // class StreamOperationAsyncResult
#endregion class StreamOperationAsyncResult
#region class StreamReadAsyncResult
internal class StreamReadAsyncResult : StreamOperationAsyncResult
{
private IBuffer _userBuffer = null;
internal StreamReadAsyncResult(IAsyncOperationWithProgress<IBuffer, uint> asyncStreamReadOperation, IBuffer buffer,
AsyncCallback userCompletionCallback, object userAsyncStateInfo,
bool processCompletedOperationInCallback)
: base(asyncStreamReadOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
_userBuffer = buffer;
asyncStreamReadOperation.Completed = this.StreamOperationCompletedCallback;
}
internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted)
{
ProcessConcreteCompletedOperation((IAsyncOperationWithProgress<IBuffer, uint>)completedOperation, out bytesCompleted);
}
private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress<IBuffer, uint> completedOperation, out long bytesCompleted)
{
IBuffer resultBuffer = completedOperation.GetResults();
Debug.Assert(resultBuffer != null);
WinRtIOHelper.EnsureResultsInUserBuffer(_userBuffer, resultBuffer);
bytesCompleted = _userBuffer.Length;
}
} // class StreamReadAsyncResult
#endregion class StreamReadAsyncResult
#region class StreamWriteAsyncResult
internal class StreamWriteAsyncResult : StreamOperationAsyncResult
{
internal StreamWriteAsyncResult(IAsyncOperationWithProgress<uint, uint> asyncStreamWriteOperation,
AsyncCallback userCompletionCallback, object userAsyncStateInfo,
bool processCompletedOperationInCallback)
: base(asyncStreamWriteOperation, userCompletionCallback, userAsyncStateInfo, processCompletedOperationInCallback)
{
asyncStreamWriteOperation.Completed = this.StreamOperationCompletedCallback;
}
internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted)
{
ProcessConcreteCompletedOperation((IAsyncOperationWithProgress<uint, uint>)completedOperation, out bytesCompleted);
}
private void ProcessConcreteCompletedOperation(IAsyncOperationWithProgress<uint, uint> completedOperation, out long bytesCompleted)
{
uint bytesWritten = completedOperation.GetResults();
bytesCompleted = bytesWritten;
}
} // class StreamWriteAsyncResult
#endregion class StreamWriteAsyncResult
#region class StreamFlushAsyncResult
internal class StreamFlushAsyncResult : StreamOperationAsyncResult
{
internal StreamFlushAsyncResult(IAsyncOperation<bool> asyncStreamFlushOperation, bool processCompletedOperationInCallback)
: base(asyncStreamFlushOperation, null, null, processCompletedOperationInCallback)
{
asyncStreamFlushOperation.Completed = this.StreamOperationCompletedCallback;
}
internal override void ProcessConcreteCompletedOperation(IAsyncInfo completedOperation, out long bytesCompleted)
{
ProcessConcreteCompletedOperation((IAsyncOperation<bool>)completedOperation, out bytesCompleted);
}
private void ProcessConcreteCompletedOperation(IAsyncOperation<bool> completedOperation, out long bytesCompleted)
{
bool success = completedOperation.GetResults();
bytesCompleted = (success ? 0 : -1);
}
} // class StreamFlushAsyncResult
#endregion class StreamFlushAsyncResult
} // namespace
// StreamOperationAsyncResult.cs
| |
using System;
using System.Collections.Generic;
/// <summary>
/// System.Collections.Generic.IDictionary.Item(TKey)
/// </summary>
public class IDictionaryItem
{
private int c_MINI_STRING_LENGTH = 1;
private int c_MAX_STRING_LENGTH = 20;
public static int Main(string[] args)
{
IDictionaryItem testObj = new IDictionaryItem();
TestLibrary.TestFramework.BeginTestCase("Testing for Property: System.Collections.Generic.IDictionary.Item(TKey)");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Netativ]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Using Dictionary<TKey,TValue> which implemented the item property in IDictionay<TKey,TValue> and TKey is int...";
const string c_TEST_ID = "P001";
Dictionary<int, int> dictionary = new Dictionary<int, int>();
int key = TestLibrary.Generator.GetInt32(-55);
int value = TestLibrary.Generator.GetInt32(-55);
int newValue = TestLibrary.Generator.GetInt32(-55);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IDictionary<int, int>)dictionary)[key] = value;
if (((IDictionary<int, int>)dictionary)[key] != value)
{
string errorDesc = "Value is not " + value + " as expected: Actual(" + dictionary[key] + ")";
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
((IDictionary<int, int>)dictionary)[key] = newValue;
if (((IDictionary<int, int>)dictionary)[key] != newValue)
{
string errorDesc = "Value is not " + newValue + " as expected: Actual(" + dictionary[key] + ")";
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Using Dictionary<TKey,TValue> which implemented the item property in IDictionay<TKey,TValue> and TKey is String...";
const string c_TEST_ID = "P002";
Dictionary<String, String> dictionary = new Dictionary<String, String>();
String key = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
String value = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
dictionary.Add(key, value);
String newValue = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (((IDictionary<String, String>)dictionary)[key] != value)
{
string errorDesc = "Value is not " + value + " as expected: Actual(" + dictionary[key] + ")";
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
((IDictionary<String, String>)dictionary)[key] = newValue;
if (((IDictionary<String, String>)dictionary)[key] != newValue)
{
string errorDesc = "Value is not " + newValue + " as expected: Actual(" + dictionary[key] + ")";
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3: Using Dictionary<TKey,TValue> which implemented the item property in IDictionay<TKey,TValue> and TKey is customer class...";
const string c_TEST_ID = "P003";
Dictionary<MyClass, int> dictionary = new Dictionary<MyClass, int>();
MyClass key = new MyClass();
int value = TestLibrary.Generator.GetInt32(-55);
dictionary.Add(key, value);
int newValue = TestLibrary.Generator.GetInt32(-55);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (((IDictionary<MyClass, int>)dictionary)[key] != value)
{
string errorDesc = "Value is not " + value + " as expected: Actual(" + dictionary[key] + ")";
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
((IDictionary<MyClass, int>)dictionary)[key] = newValue;
if (((IDictionary<MyClass, int>)dictionary)[key] != newValue)
{
string errorDesc = "Value is not " + newValue + " as expected: Actual(" + dictionary[key] + ")";
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("009", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4: Using customer class which implemented the item property in IDictionay<TKey,TValue>...";
const string c_TEST_ID = "P004";
MyDictionary<int, int> dictionary = new MyDictionary<int, int>();
int key = TestLibrary.Generator.GetInt32(-55);
int value = TestLibrary.Generator.GetInt32(-55);
int newValue = TestLibrary.Generator.GetInt32(-55);
dictionary.Add(key, value);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
if (((IDictionary<int, int>)dictionary)[key] != value)
{
string errorDesc = "Value is not " + value + " as expected: Actual(" + dictionary[key] + ")";
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
((IDictionary<int, int>)dictionary)[key] = newValue;
if (((IDictionary<int, int>)dictionary)[key] != newValue)
{
string errorDesc = "Value is not " + newValue + " as expected: Actual(" + dictionary[key] + ")";
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unecpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: Using Dictionary<TKey,TValue> which implemented the item property in IDictionay<TKey,TValue> and Key is a null reference...";
const string c_TEST_ID = "N001";
Dictionary<String, int> dictionary = new Dictionary<String, int>();
String key = null;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
int value = ((IDictionary<String, int>)dictionary)[key];
TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "The ArgumentNullException was not thrown as expected");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest2: Using Dictionary<TKey,TValue> which implemented the item property in IDictionay<TKey,TValue> and Key is a null reference...";
const string c_TEST_ID = "N002";
Dictionary<String, int> dictionary = new Dictionary<String, int>();
String key = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
int value = ((IDictionary<String, int>)dictionary)[key];
TestLibrary.TestFramework.LogError("015" + "TestId-" + c_TEST_ID, "The KeyNotFoundException was not thrown as expected");
retVal = false;
}
catch (KeyNotFoundException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest3: Using user-defined class which implemented the add method in IDictionay<TKey,TValue> and ReadOnly is true";
const string c_TEST_ID = "N003";
MyDictionary<String, int> dictionary = new MyDictionary<String, int>();
String key = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
int value = TestLibrary.Generator.GetInt32(-55);
int newValue = TestLibrary.Generator.GetInt32(-55);
dictionary.Add(key, value);
dictionary.readOnly = true;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
((IDictionary<String, int>)dictionary)[key] = newValue;
TestLibrary.TestFramework.LogError("017" + " TestId-" + c_TEST_ID, "The NotSupportedException was not thrown as expected");
retVal = false;
}
catch (NotSupportedException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region Help Class
public class MyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private int count;
private int capacity = 10;
public bool readOnly = false;
private KeyValuePair<TKey, TValue>[] keyvaluePair;
public MyDictionary()
{
count = 0;
keyvaluePair = new KeyValuePair<TKey, TValue>[capacity];
}
#region IDictionary<TKey,TValue> Members
public void Add(TKey key, TValue value)
{
if (readOnly)
throw new NotSupportedException();
if (ContainsKey(key))
throw new ArgumentException();
try
{
KeyValuePair<TKey, TValue> pair = new KeyValuePair<TKey, TValue>(key, value);
keyvaluePair[count] = pair;
count++;
}
catch (Exception en)
{
throw en;
}
}
public bool ContainsKey(TKey key)
{
bool exist = false;
if (key == null)
throw new ArgumentNullException();
foreach (KeyValuePair<TKey, TValue> pair in keyvaluePair)
{
if (pair.Key != null && pair.Key.Equals(key))
{
exist = true;
}
}
return exist;
}
public ICollection<TKey> Keys
{
get { throw new Exception("The method or operation is not implemented."); }
}
public bool Remove(TKey key)
{
throw new Exception("The method or operation is not implemented.");
}
public bool TryGetValue(TKey key, out TValue value)
{
throw new Exception("The method or operation is not implemented.");
}
public ICollection<TValue> Values
{
get { throw new Exception("The method or operation is not implemented."); }
}
public TValue this[TKey key]
{
get
{
if (!ContainsKey(key))
throw new KeyNotFoundException();
int index = -1;
for (int j = 0; j < count; j++)
{
KeyValuePair<TKey, TValue> pair = keyvaluePair[j];
if (pair.Key.Equals(key))
{
index = j;
break;
}
}
return keyvaluePair[index].Value;
}
set
{
if (readOnly)
throw new NotSupportedException();
if (ContainsKey(key))
{
int index = -1;
for (int j = 0; j < count; j++)
{
KeyValuePair<TKey, TValue> pair = keyvaluePair[j];
if (pair.Key.Equals(key))
{
index = j;
break;
}
}
KeyValuePair<TKey, TValue> newpair = new KeyValuePair<TKey, TValue>(key, value);
keyvaluePair[index] = newpair;
}
else
{
KeyValuePair<TKey, TValue> pair = new KeyValuePair<TKey, TValue>(key, value);
keyvaluePair[count] = pair;
count++;
}
}
}
#endregion
#region ICollection<KeyValuePair<TKey,TValue>> Members
public void Add(KeyValuePair<TKey, TValue> item)
{
throw new Exception("The method or operation is not implemented.");
}
public void Clear()
{
throw new Exception("The method or operation is not implemented.");
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
throw new Exception("The method or operation is not implemented.");
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
throw new Exception("The method or operation is not implemented.");
}
public int Count
{
get { return count; }
}
public bool IsReadOnly
{
get { throw new Exception("The method or operation is not implemented."); }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IEnumerable<KeyValuePair<TKey,TValue>> Members
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
public class MyClass
{ }
#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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void XorSingle()
{
var test = new SimpleBinaryOpTest__XorSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorSingle
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Single);
private const int Op2ElementCount = VectorSize / sizeof(Single);
private const int RetElementCount = VectorSize / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector256<Single> _clsVar1;
private static Vector256<Single> _clsVar2;
private Vector256<Single> _fld1;
private Vector256<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static SimpleBinaryOpTest__XorSingle()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__XorSingle()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.Xor(
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.Xor(
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.Xor(
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Xor), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Single>>(_dataTable.inArray2Ptr);
var result = Avx.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Single*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Single*)(_dataTable.inArray2Ptr));
var result = Avx.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorSingle();
var result = Avx.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Single> left, Vector256<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
if ((BitConverter.SingleToInt32Bits(left[0]) ^ BitConverter.SingleToInt32Bits(right[0])) != BitConverter.SingleToInt32Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((BitConverter.SingleToInt32Bits(left[i]) ^ BitConverter.SingleToInt32Bits(right[i])) != BitConverter.SingleToInt32Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Xor)}<Single>(Vector256<Single>, Vector256<Single>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using UnityEngine;
using System.Collections;
public class PerlinNoise
{
const int B = 256;
int[] m_perm = new int[B+B];
Texture2D m_permTex;
public PerlinNoise(int seed)
{
UnityEngine.Random.seed = seed;
int i, j, k;
for (i = 0 ; i < B ; i++)
{
m_perm[i] = i;
}
while (--i != 0)
{
k = m_perm[i];
j = UnityEngine.Random.Range(0, B);
m_perm[i] = m_perm[j];
m_perm[j] = k;
}
for (i = 0 ; i < B; i++)
{
m_perm[B + i] = m_perm[i];
}
}
float FADE(float t) { return t * t * t * ( t * ( t * 6.0f - 15.0f ) + 10.0f ); }
float LERP(float t, float a, float b) { return (a) + (t)*((b)-(a)); }
float GRAD1(int hash, float x )
{
//This method uses the mod operator which is slower
//than bitwise operations but is included out of interest
// int h = hash % 16;
// float grad = 1.0f + (h % 8);
// if((h%8) < 4) grad = -grad;
// return ( grad * x );
int h = hash & 15;
float grad = 1.0f + (h & 7);
if ((h&8) != 0) grad = -grad;
return ( grad * x );
}
float GRAD2(int hash, float x, float y)
{
//This method uses the mod operator which is slower
//than bitwise operations but is included out of interest
// int h = hash % 16;
// float u = h<4 ? x : y;
// float v = h<4 ? y : x;
// int hn = h%2;
// int hm = (h/2)%2;
// return ((hn != 0) ? -u : u) + ((hm != 0) ? -2.0f*v : 2.0f*v);
int h = hash & 7;
float u = h<4 ? x : y;
float v = h<4 ? y : x;
return (((h&1) != 0)? -u : u) + (((h&2) != 0) ? -2.0f*v : 2.0f*v);
}
float GRAD3(int hash, float x, float y , float z)
{
//This method uses the mod operator which is slower
//than bitwise operations but is included out of interest
// int h = hash % 16;
// float u = (h<8) ? x : y;
// float v = (h<4) ? y : (h==12||h==14) ? x : z;
// int hn = h%2;
// int hm = (h/2)%2;
// return ((hn != 0) ? -u : u) + ((hm != 0) ? -v : v);
int h = hash & 15;
float u = h<8 ? x : y;
float v = (h<4) ? y : (h==12 || h==14) ? x : z;
return (((h&1) != 0)? -u : u) + (((h&2) != 0)? -v : v);
}
float Noise1D( float x )
{
//returns a noise value between -0.5 and 0.5
int ix0, ix1;
float fx0, fx1;
float s, n0, n1;
ix0 = (int)Mathf.Floor(x); // Integer part of x
fx0 = x - ix0; // Fractional part of x
fx1 = fx0 - 1.0f;
ix1 = ( ix0+1 ) & 0xff;
ix0 = ix0 & 0xff; // Wrap to 0..255
s = FADE(fx0);
n0 = GRAD1(m_perm[ix0], fx0);
n1 = GRAD1(m_perm[ix1], fx1);
return 0.188f * LERP( s, n0, n1);
}
float Noise2D( float x, float y )
{
//returns a noise value between -0.75 and 0.75
int ix0, iy0, ix1, iy1;
float fx0, fy0, fx1, fy1, s, t, nx0, nx1, n0, n1;
ix0 = (int)Mathf.Floor(x); // Integer part of x
iy0 = (int)Mathf.Floor(y); // Integer part of y
fx0 = x - ix0; // Fractional part of x
fy0 = y - iy0; // Fractional part of y
fx1 = fx0 - 1.0f;
fy1 = fy0 - 1.0f;
ix1 = (ix0 + 1) & 0xff; // Wrap to 0..255
iy1 = (iy0 + 1) & 0xff;
ix0 = ix0 & 0xff;
iy0 = iy0 & 0xff;
t = FADE( fy0 );
s = FADE( fx0 );
nx0 = GRAD2(m_perm[ix0 + m_perm[iy0]], fx0, fy0);
nx1 = GRAD2(m_perm[ix0 + m_perm[iy1]], fx0, fy1);
n0 = LERP( t, nx0, nx1 );
nx0 = GRAD2(m_perm[ix1 + m_perm[iy0]], fx1, fy0);
nx1 = GRAD2(m_perm[ix1 + m_perm[iy1]], fx1, fy1);
n1 = LERP(t, nx0, nx1);
return 0.507f * LERP( s, n0, n1 );
}
float Noise3D( float x, float y, float z )
{
//returns a noise value between -1.5 and 1.5
int ix0, iy0, ix1, iy1, iz0, iz1;
float fx0, fy0, fz0, fx1, fy1, fz1;
float s, t, r;
float nxy0, nxy1, nx0, nx1, n0, n1;
ix0 = (int)Mathf.Floor( x ); // Integer part of x
iy0 = (int)Mathf.Floor( y ); // Integer part of y
iz0 = (int)Mathf.Floor( z ); // Integer part of z
fx0 = x - ix0; // Fractional part of x
fy0 = y - iy0; // Fractional part of y
fz0 = z - iz0; // Fractional part of z
fx1 = fx0 - 1.0f;
fy1 = fy0 - 1.0f;
fz1 = fz0 - 1.0f;
ix1 = ( ix0 + 1 ) & 0xff; // Wrap to 0..255
iy1 = ( iy0 + 1 ) & 0xff;
iz1 = ( iz0 + 1 ) & 0xff;
ix0 = ix0 & 0xff;
iy0 = iy0 & 0xff;
iz0 = iz0 & 0xff;
r = FADE( fz0 );
t = FADE( fy0 );
s = FADE( fx0 );
nxy0 = GRAD3(m_perm[ix0 + m_perm[iy0 + m_perm[iz0]]], fx0, fy0, fz0);
nxy1 = GRAD3(m_perm[ix0 + m_perm[iy0 + m_perm[iz1]]], fx0, fy0, fz1);
nx0 = LERP( r, nxy0, nxy1 );
nxy0 = GRAD3(m_perm[ix0 + m_perm[iy1 + m_perm[iz0]]], fx0, fy1, fz0);
nxy1 = GRAD3(m_perm[ix0 + m_perm[iy1 + m_perm[iz1]]], fx0, fy1, fz1);
nx1 = LERP( r, nxy0, nxy1 );
n0 = LERP( t, nx0, nx1 );
nxy0 = GRAD3(m_perm[ix1 + m_perm[iy0 + m_perm[iz0]]], fx1, fy0, fz0);
nxy1 = GRAD3(m_perm[ix1 + m_perm[iy0 + m_perm[iz1]]], fx1, fy0, fz1);
nx0 = LERP( r, nxy0, nxy1 );
nxy0 = GRAD3(m_perm[ix1 + m_perm[iy1 + m_perm[iz0]]], fx1, fy1, fz0);
nxy1 = GRAD3(m_perm[ix1 + m_perm[iy1 + m_perm[iz1]]], fx1, fy1, fz1);
nx1 = LERP( r, nxy0, nxy1 );
n1 = LERP( t, nx0, nx1 );
return 0.936f * LERP( s, n0, n1 );
}
public float FractalNoise1D(float x, int octNum, float frq, float amp)
{
float gain = 1.0f;
float sum = 0.0f;
for(int i = 0; i < octNum; i++)
{
sum += Noise1D(x*gain/frq) * amp/gain;
gain *= 2.0f;
}
return sum;
}
public float FractalNoise2D(float x, float y, int octNum, float frq, float amp)
{
float gain = 1.0f;
float sum = 0.0f;
for(int i = 0; i < octNum; i++)
{
sum += Noise2D(x*gain/frq, y*gain/frq) * amp/gain;
gain *= 2.0f;
}
return sum;
}
public float FractalNoise3D(float x, float y, float z, int octNum, float frq, float amp)
{
float gain = 1.0f;
float sum = 0.0f;
for(int i = 0; i < octNum; i++)
{
sum += Noise3D(x*gain/frq, y*gain/frq, z*gain/frq) * amp/gain;
gain *= 2.0f;
}
return sum;
}
public void LoadPermTableIntoTexture()
{
m_permTex = new Texture2D(256, 1, TextureFormat.Alpha8, false);
m_permTex.filterMode = FilterMode.Point;
m_permTex.wrapMode = TextureWrapMode.Clamp;
for(int i = 0; i < 256; i++)
{
float v = (float)m_perm[i] / 255.0f;
m_permTex.SetPixel(i, 0, new Color(0,0,0,v));
}
m_permTex.Apply();
}
public void RenderIntoTexture(Shader shader, RenderTexture renderTex, int octNum, float frq, float amp)
{
if(!m_permTex) LoadPermTableIntoTexture();
Material mat = new Material(shader);
mat.SetFloat("_Frq", frq);
mat.SetFloat("_Amp", amp);
mat.SetVector("_TexSize", new Vector4(renderTex.width-1.0f, renderTex.height-1.0f, 0, 0));
mat.SetTexture("_Perm", m_permTex);
float gain = 1.0f;
for(int i = 0; i < octNum; i++)
{
mat.SetFloat("_Gain", gain);
Graphics.Blit(null, renderTex, mat);
gain *= 2.0f;
}
}
}
| |
using System;
using System.Collections;
using Alachisoft.NCache.Common.Net;
namespace Alachisoft.NGroups
{
/// <remarks>
/// Coupled with an <c>ArrayList</c>, this class extends its facilites and adds
/// extra constraints
/// </remarks>
/// <summary>
/// Used by the GMS to store the current members in the group
/// <p><b>Author:</b> Chris Koiak, Bela Ban</p>
/// <p><b>Date:</b> 12/03/2003</p>
/// </summary>
internal class Membership
{
/// <summary>
/// List of current members
/// </summary>
private ArrayList members = null;
/// <summary>
/// Constructor: Initialises with no initial members
/// </summary>
public Membership()
{
members = new ArrayList(11);
members = ArrayList.Synchronized(members);
}
/// <summary>
/// Constructor: Initialises with the specified initial members
/// </summary>
/// <param name="initial_members">Initial members of the membership</param>
public Membership(ArrayList initial_members)
{
members=new ArrayList();
if(initial_members != null)
members = (ArrayList)initial_members.Clone();
members = ArrayList.Synchronized(members);
}
/// <summary> returns a copy (clone) of the members in this membership.
/// the vector returned is immutable in reference to this object.
/// ie, modifying the vector that is being returned in this method
/// will not modify this membership object.
///
/// </summary>
/// <returns> a list of members,
/// </returns>
virtual public System.Collections.ArrayList Members
{
get
{
/*clone so that this objects members can not be manipulated from the outside*/
return (ArrayList)members.Clone();
}
}
/// <summary>
/// Sets the members to the specified list
/// </summary>
/// <param name="membrs">The current members</param>
public void setMembers(ArrayList membrs)
{
members = membrs;
}
/// <remarks>
/// If the member already exists then the member will
/// not be added to the membership
/// </remarks>
/// <summary>
/// Adds a new member to this membership.
/// </summary>
/// <param name="new_member"></param>
public void add(Address new_member)
{
if(new_member != null && !members.Contains(new_member))
{
members.Add(new_member);
}
}
/// <summary>
/// Adds a number of members to this membership
/// </summary>
/// <param name="v"></param>
public void add(ArrayList v)
{
if(v != null)
{
for(int i=0; i < v.Count; i++)
{
add((Address)v[i]);
}
}
}
/// <summary>
/// Removes the specified member
/// </summary>
/// <param name="old_member">Member that has left the group</param>
public void remove(Address old_member)
{
if(old_member != null)
{
members.Remove(old_member);
}
}
/// <summary> merges membership with the new members and removes suspects
/// The Merge method will remove all the suspects and add in the new members.
/// It will do it in the order
/// 1. Remove suspects
/// 2. Add new members
/// the order is very important to notice.
///
/// </summary>
/// <param name="new_mems">- a vector containing a list of members (Address) to be added to this membership
/// </param>
/// <param name="suspects">- a vector containing a list of members (Address) to be removed from this membership
/// </param>
public virtual void merge(System.Collections.ArrayList new_mems, System.Collections.ArrayList suspects)
{
lock (this)
{
remove(suspects);
add(new_mems);
}
}
/* Simple inefficient bubble sort, but not used very often (only when merging) */
public virtual void sort()
{
lock (this)
{
members.Sort();
}
}
/// <summary>
/// Removes a number of members from the membership
/// </summary>
/// <param name="v"></param>
public void remove(ArrayList v)
{
if(v != null)
{
for(int i=0; i < v.Count; i++)
{
remove((Address)v[i]);
}
}
}
/// <summary>
/// Removes all members
/// </summary>
public void clear()
{
members.Clear();
}
/// <summary>
/// Sets the membership to the members present in the list
/// </summary>
/// <param name="v">New list of members</param>
public void set(ArrayList v)
{
clear();
if (v != null)
{
add(v);
}
}
/// <summary>
/// Sets the membership to the specified membership
/// </summary>
/// <param name="m">New membership</param>
public void set(Membership m)
{
clear();
if (m != null)
{
add(m.Members);
}
}
/// <summary>
/// Returns true if the provided member belongs to this membership
/// </summary>
/// <param name="member">Member to check</param>
/// <returns>True if the provided member belongs to this membership, otherwise false</returns>
public bool contains(Address member)
{
if(member == null)
return false;
return members.Contains(member);
}
/// <summary>
/// Returns a copy of this membership.
/// </summary>
/// <returns>A copy of this membership</returns>
public Membership copy()
{
return (Membership)this.Clone();
}
/// <summary>
/// Determines the seniority between two given nodes. Seniority is based on
/// the joining time. If n1 has joined before than n2, n1 will be considered
/// senior.
/// </summary>
/// <param name="n1">node 1</param>
/// <param name="n2">node 2</param>
/// <returns>senior node</returns>
public Address DetermineSeniority(Address n1, Address n2)
{
int indexofn1 = members.IndexOf(n1);
int indexofn2 = members.IndexOf(n2);
if (indexofn1 == -1) indexofn1 = int.MaxValue;
if (indexofn2 == -1) indexofn2 = int.MaxValue;
//smaller the index of a node means that this node has joined first.
return indexofn1 <= indexofn2 ? n1 : n2;
}
/// <summary>
/// Clones the membership
/// </summary>
/// <returns>A clone of the membership</returns>
public Object Clone()
{
Membership m;
m = new Membership();
m.setMembers((ArrayList)members.Clone());
return(m);
}
/// <summary>
/// The number of members in the membership
/// </summary>
/// <returns>Number of members in the membership</returns>
public int size()
{
return members.Count;
}
/// <summary>
/// Gets a member at a specified index
/// </summary>
/// <param name="index">Index of member</param>
/// <returns>Address of member</returns>
public Address elementAt(int index)
{
if(index<members.Count)
return (Address)members[index];
else
return null;
}
/// <summary>
/// String representation of the Membership object
/// </summary>
/// <returns>String representation of the Membership object</returns>
public String toString()
{
return members.ToString();
}
public override bool Equals(object obj)
{
bool equal = true;
Membership membership = obj as Membership;
if (membership != null && this.size() == membership.size())
{
foreach (Address address in membership.members)
{
if (!this.contains(address))
{
equal = false;
break;
}
}
}
else
{
equal = false;
}
return equal;
}
public bool ContainsIP(Address address)
{
if (address == null)
return false;
bool contains = false;
foreach (Address add in members)
{
if (add.IpAddress.Equals(address.IpAddress))
{
contains = true;
}
}
return contains;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using SQLite;
namespace BAC_Tracker
{
//NM: Class is currently private. Will likely make it public and static
public static class DataBaseManager
{
/***********************************************Database***************************************/
//Create Database
public void CreateDB()
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "BAC.db");
var db = new SQLiteConnection(dbPath);
}
/***********************************************Person Table***************************************/
public void CreatePersonTable()
{
try
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "BAC.db");
var db = new SQLiteConnection(dbPath);
db.CreateTable<Person>();
}
catch (Exception ex)
{
Console.WriteLine("error creating Person table" + ex.Message);
}
}
//Add record
public void InsertRecord(string gender, int weight)
{
try
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "BAC.db");
var db = new SQLiteConnection(dbPath);
Person settings = new Person();
settings.Gender = gender;
settings.Weight = weight;
db.Insert(settings);
}
catch (Exception ex)
{
Console.WriteLine("error inserting record" + ex.Message);
}
}
//Retrieve Gender
public string RetrieveGender()
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "BAC.db");
var db = new SQLiteConnection(dbPath);
Person person = new Person();
var item = db.Get<Person>(1);
return item.Gender;
}
//Retrieve Weight
public double RetreiveWeight()
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "BAC.db");
var db = new SQLiteConnection(dbPath);
Person person = new Person();
var item = db.Get<Person>(1);
return item.Weight;
}
//Update settings
public void UpdateRecord(int id, string gender, int weight)
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "BAC.db");
var db = new SQLiteConnection(dbPath);
var item = db.Get<Person>(id);
item.Gender = gender;
item.Weight = weight;
db.Update(item);
}
//Create table
public void CreateDrinkTable()
{
try
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "BAC.db");
var db = new SQLiteConnection(dbPath);
db.CreateTable<Beverage>();
}
catch (Exception ex)
{
Console.WriteLine("error creating Drink table" + ex.Message);
}
}
//Add record (10 attributes)
public void InsertRecord(int id, DateTime startTime, DateTime finishTime, string type, double amount, double completed_percentage, double alcohol_percentage, string make, string model, double volume_percentage_completed)
{
try
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "BAC.db");
var db = new SQLiteConnection(dbPath);
Beverage drink = new Beverage();
drink.Id = id;
drink.startTime = startTime;
drink.finishTime = finishTime;
drink.type = type;
drink.Amount = amount;
drink.Completed_Percentage = completed_percentage;
drink.Alcohol_percentage = alcohol_percentage;
drink.Make = make;
drink.Model = model;
drink.Volume_percentage_completed = volume_percentage_completed;
db.Insert(drink);
}
catch (Exception ex)
{
Console.WriteLine("error Inserting record into beverage table" + ex.Message);
}
}
//Retrieve all data by event_id (foreign key to Beverage table)
//Still working on how to get an Event to display with the foreignkey constraint. Will test this this upcoming week.
public string RetrieveEvent(int event_id)
{
string output = "";
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "BAC.db");
var db = new SQLiteConnection(dbPath);
var item = db.Get<Beverage>(event_id);
var query = db.Query<Beverage>("Select event_id, created_at FROM Beverage, Event where Id=eventid");
foreach (var Event in query)
{
output += Event.ToString();
}
return output;
}
//Will ask group if this is needed.
//Update settings
public void UpdateRecord(int id, DateTime startTime, DateTime finishTime, string type, double amount, double completed_percentage, double alcohol_percentage, string make, string model, double volume_percentage_completed)
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "BAC.db");
var db = new SQLiteConnection(dbPath);
var item = db.Get<Beverage>(id);
db.Update(item);
}
/******************************************************Event Table**************************************************/
//Create table
public void CreateEventTable()
{
try
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "BAC.db");
var db = new SQLiteConnection(dbPath);
db.CreateTable<Event>();
}
catch (Exception ex)
{
Console.WriteLine("error creating Event table" + ex.Message);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Web;
using NServiceKit.Common;
using NServiceKit.MiniProfiler.UI;
using NServiceKit.ServiceHost;
using NServiceKit.Text;
using NServiceKit.WebHost.Endpoints.Extensions;
using NServiceKit.WebHost.Endpoints.Support;
using HttpRequestWrapper = NServiceKit.WebHost.Endpoints.Extensions.HttpRequestWrapper;
namespace NServiceKit.WebHost.Endpoints
{
/// <summary>A service kit HTTP handler factory.</summary>
public class NServiceKitHttpHandlerFactory
: IHttpHandlerFactory
{
static readonly List<string> WebHostRootFileNames = new List<string>();
static private readonly string WebHostPhysicalPath = null;
static private readonly string DefaultRootFileName = null;
static private string ApplicationBaseUrl = null;
static private readonly IHttpHandler DefaultHttpHandler = null;
static private readonly RedirectHttpHandler NonRootModeDefaultHttpHandler = null;
static private readonly IHttpHandler ForbiddenHttpHandler = null;
static private readonly IHttpHandler NotFoundHttpHandler = null;
static private readonly IHttpHandler StaticFileHandler = new StaticFileHandler();
private static readonly bool IsIntegratedPipeline = false;
private static readonly bool ServeDefaultHandler = false;
private static readonly bool AutoRedirectsDirs = false;
private static Func<IHttpRequest, IHttpHandler>[] RawHttpHandlers;
/// <summary>The debug last handler arguments.</summary>
[ThreadStatic]
public static string DebugLastHandlerArgs;
static NServiceKitHttpHandlerFactory()
{
//MONO doesn't implement this property
var pi = typeof(HttpRuntime).GetProperty("UsingIntegratedPipeline");
if (pi != null)
{
IsIntegratedPipeline = (bool)pi.GetGetMethod().Invoke(null, new object[0]);
}
var config = EndpointHost.Config;
if (config == null)
{
throw new ConfigurationErrorsException(
"NServiceKit: AppHost does not exist or has not been initialized. "
+ "Make sure you have created an AppHost and started it with 'new AppHost().Init();' in your Global.asax Application_Start()",
new ArgumentNullException("EndpointHost.Config"));
}
var isAspNetHost = HttpListenerBase.Instance == null || HttpContext.Current != null;
WebHostPhysicalPath = config.WebHostPhysicalPath;
AutoRedirectsDirs = isAspNetHost && !Env.IsMono;
//Apache+mod_mono treats path="NServiceKit*" as path="*" so takes over root path, so we need to serve matching resources
var hostedAtRootPath = config.NServiceKitHandlerFactoryPath == null;
//DefaultHttpHandler not supported in IntegratedPipeline mode
if (!IsIntegratedPipeline && isAspNetHost && !hostedAtRootPath && !Env.IsMono)
DefaultHttpHandler = new DefaultHttpHandler();
ServeDefaultHandler = hostedAtRootPath || Env.IsMono;
if (ServeDefaultHandler)
{
foreach (var filePath in Directory.GetFiles(WebHostPhysicalPath))
{
var fileNameLower = Path.GetFileName(filePath).ToLower();
if (DefaultRootFileName == null && config.DefaultDocuments.Contains(fileNameLower))
{
//Can't serve Default.aspx pages when hostedAtRootPath so ignore and allow for next default document
if (!(hostedAtRootPath && fileNameLower.EndsWith(".aspx")))
{
DefaultRootFileName = fileNameLower;
((StaticFileHandler)StaticFileHandler).SetDefaultFile(filePath);
if (DefaultHttpHandler == null)
DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = DefaultRootFileName };
}
}
WebHostRootFileNames.Add(Path.GetFileName(fileNameLower));
}
foreach (var dirName in Directory.GetDirectories(WebHostPhysicalPath))
{
var dirNameLower = Path.GetFileName(dirName).ToLower();
WebHostRootFileNames.Add(Path.GetFileName(dirNameLower));
}
}
if (!string.IsNullOrEmpty(config.DefaultRedirectPath))
DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.DefaultRedirectPath };
if (DefaultHttpHandler == null && !string.IsNullOrEmpty(config.MetadataRedirectPath))
DefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.MetadataRedirectPath };
if (!string.IsNullOrEmpty(config.MetadataRedirectPath))
NonRootModeDefaultHttpHandler = new RedirectHttpHandler { RelativeUrl = config.MetadataRedirectPath };
if (DefaultHttpHandler == null)
DefaultHttpHandler = NotFoundHttpHandler;
var defaultRedirectHanlder = DefaultHttpHandler as RedirectHttpHandler;
var debugDefaultHandler = defaultRedirectHanlder != null
? defaultRedirectHanlder.RelativeUrl
: typeof(DefaultHttpHandler).Name;
SetApplicationBaseUrl(config.WebHostUrl);
ForbiddenHttpHandler = config.GetCustomErrorHttpHandler(HttpStatusCode.Forbidden);
if (ForbiddenHttpHandler == null)
{
ForbiddenHttpHandler = new ForbiddenHttpHandler
{
IsIntegratedPipeline = IsIntegratedPipeline,
WebHostPhysicalPath = WebHostPhysicalPath,
WebHostRootFileNames = WebHostRootFileNames,
ApplicationBaseUrl = ApplicationBaseUrl,
DefaultRootFileName = DefaultRootFileName,
DefaultHandler = debugDefaultHandler,
};
}
NotFoundHttpHandler = config.GetCustomErrorHttpHandler(HttpStatusCode.NotFound);
if (NotFoundHttpHandler == null)
{
NotFoundHttpHandler = new NotFoundHttpHandler
{
IsIntegratedPipeline = IsIntegratedPipeline,
WebHostPhysicalPath = WebHostPhysicalPath,
WebHostRootFileNames = WebHostRootFileNames,
ApplicationBaseUrl = ApplicationBaseUrl,
DefaultRootFileName = DefaultRootFileName,
DefaultHandler = debugDefaultHandler,
};
}
var rawHandlers = config.RawHttpHandlers;
rawHandlers.Add(ReturnRequestInfo);
rawHandlers.Add(MiniProfilerHandler.MatchesRequest);
RawHttpHandlers = rawHandlers.ToArray();
}
/// <summary>Entry point for ASP.NET.</summary>
///
/// <param name="context"> An instance of the <see cref="T:System.Web.HttpContext" /> class that provides references to intrinsic server objects (for example, Request, Response, Session, and
/// Server) used to service HTTP requests.
/// </param>
/// <param name="requestType"> The HTTP data transfer method (GET or POST) that the client uses.</param>
/// <param name="url"> The <see cref="P:System.Web.HttpRequest.RawUrl" /> of the requested resource.</param>
/// <param name="pathTranslated">The <see cref="P:System.Web.HttpRequest.PhysicalApplicationPath" /> to the requested resource.</param>
///
/// <returns>The handler.</returns>
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
DebugLastHandlerArgs = requestType + "|" + url + "|" + pathTranslated;
var httpReq = new HttpRequestWrapper(pathTranslated, context.Request);
foreach (var rawHttpHandler in RawHttpHandlers)
{
var reqInfo = rawHttpHandler(httpReq);
if (reqInfo != null) return reqInfo;
}
var mode = EndpointHost.Config.NServiceKitHandlerFactoryPath;
var pathInfo = context.Request.GetPathInfo();
//WebDev Server auto requests '/default.aspx' so recorrect path to different default document
if (mode == null && (url == "/default.aspx" || url == "/Default.aspx"))
pathInfo = "/";
//Default Request /
if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/")
{
//Exception calling context.Request.Url on Apache+mod_mono
if (ApplicationBaseUrl == null)
{
var absoluteUrl = Env.IsMono ? url.ToParentPath() : context.Request.GetApplicationUrl();
SetApplicationBaseUrl(absoluteUrl);
}
//e.g. CatchAllHandler to Process Markdown files
var catchAllHandler = GetCatchAllHandlerIfAny(httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath());
if (catchAllHandler != null) return catchAllHandler;
return ServeDefaultHandler ? DefaultHttpHandler : NonRootModeDefaultHttpHandler;
}
if (mode != null && pathInfo.EndsWith(mode))
{
var requestPath = context.Request.Path.ToLower();
if (requestPath == "/" + mode
|| requestPath == mode
|| requestPath == mode + "/")
{
if (context.Request.PhysicalPath != WebHostPhysicalPath
|| !File.Exists(Path.Combine(context.Request.PhysicalPath, DefaultRootFileName ?? "")))
{
return new IndexPageHttpHandler();
}
}
var okToServe = ShouldAllow(context.Request.FilePath);
return okToServe ? DefaultHttpHandler : ForbiddenHttpHandler;
}
return GetHandlerForPathInfo(
httpReq.HttpMethod, pathInfo, context.Request.FilePath, pathTranslated)
?? NotFoundHttpHandler;
}
private static void SetApplicationBaseUrl(string absoluteUrl)
{
if (absoluteUrl == null) return;
ApplicationBaseUrl = absoluteUrl;
var defaultRedirectUrl = DefaultHttpHandler as RedirectHttpHandler;
if (defaultRedirectUrl != null && defaultRedirectUrl.AbsoluteUrl == null)
defaultRedirectUrl.AbsoluteUrl = ApplicationBaseUrl.CombineWith(
defaultRedirectUrl.RelativeUrl);
if (NonRootModeDefaultHttpHandler != null && NonRootModeDefaultHttpHandler.AbsoluteUrl == null)
NonRootModeDefaultHttpHandler.AbsoluteUrl = ApplicationBaseUrl.CombineWith(
NonRootModeDefaultHttpHandler.RelativeUrl);
}
/// <summary>Gets base URL.</summary>
///
/// <returns>The base URL.</returns>
public static string GetBaseUrl()
{
return EndpointHost.Config.WebHostUrl ?? ApplicationBaseUrl;
}
/// <summary>Entry point for HttpListener.</summary>
///
/// <param name="httpReq">.</param>
///
/// <returns>The handler.</returns>
public static IHttpHandler GetHandler(IHttpRequest httpReq)
{
foreach (var rawHttpHandler in RawHttpHandlers)
{
var reqInfo = rawHttpHandler(httpReq);
if (reqInfo != null) return reqInfo;
}
var mode = EndpointHost.Config.NServiceKitHandlerFactoryPath;
var pathInfo = httpReq.PathInfo;
//Default Request /
if (string.IsNullOrEmpty(pathInfo) || pathInfo == "/")
{
if (ApplicationBaseUrl == null)
SetApplicationBaseUrl(httpReq.GetPathUrl());
//e.g. CatchAllHandler to Process Markdown files
var catchAllHandler = GetCatchAllHandlerIfAny(httpReq.HttpMethod, pathInfo, httpReq.GetPhysicalPath());
if (catchAllHandler != null) return catchAllHandler;
return ServeDefaultHandler ? DefaultHttpHandler : NonRootModeDefaultHttpHandler;
}
if (mode != null && pathInfo.EndsWith(mode))
{
var requestPath = pathInfo;
if (requestPath == "/" + mode
|| requestPath == mode
|| requestPath == mode + "/")
{
//TODO: write test for this
if (httpReq.GetPhysicalPath() != WebHostPhysicalPath
|| !File.Exists(Path.Combine(httpReq.ApplicationFilePath, DefaultRootFileName ?? "")))
{
return new IndexPageHttpHandler();
}
}
var okToServe = ShouldAllow(httpReq.GetPhysicalPath());
return okToServe ? DefaultHttpHandler : ForbiddenHttpHandler;
}
return GetHandlerForPathInfo(httpReq.HttpMethod, pathInfo, pathInfo, httpReq.GetPhysicalPath())
?? NotFoundHttpHandler;
}
/// <summary>
/// If enabled, just returns the Request Info as it understands
/// </summary>
/// <param name="httpReq"></param>
/// <returns></returns>
private static IHttpHandler ReturnRequestInfo(HttpRequest httpReq)
{
if (EndpointHost.Config.DebugOnlyReturnRequestInfo
|| (EndpointHost.DebugMode && httpReq.PathInfo.EndsWith("__requestinfo")))
{
var reqInfo = RequestInfoHandler.GetRequestInfo(
new HttpRequestWrapper(typeof(RequestInfo).Name, httpReq));
reqInfo.Host = EndpointHost.Config.DebugAspNetHostEnvironment + "_v" + Env.NServiceKitVersion + "_" + EndpointHost.Config.ServiceName;
//reqInfo.FactoryUrl = url; //Just RawUrl without QueryString
//reqInfo.FactoryPathTranslated = pathTranslated; //Local path on filesystem
reqInfo.PathInfo = httpReq.PathInfo;
reqInfo.Path = httpReq.Path;
reqInfo.ApplicationPath = httpReq.ApplicationPath;
return new RequestInfoHandler { RequestInfo = reqInfo };
}
return null;
}
private static IHttpHandler ReturnRequestInfo(IHttpRequest httpReq)
{
if (EndpointHost.Config.DebugOnlyReturnRequestInfo
|| (EndpointHost.DebugMode && httpReq.PathInfo.EndsWith("__requestinfo")))
{
var reqInfo = RequestInfoHandler.GetRequestInfo(httpReq);
reqInfo.Host = EndpointHost.Config.DebugHttpListenerHostEnvironment + "_v" + Env.NServiceKitVersion + "_" + EndpointHost.Config.ServiceName;
reqInfo.PathInfo = httpReq.PathInfo;
reqInfo.Path = httpReq.GetPathUrl();
return new RequestInfoHandler { RequestInfo = reqInfo };
}
return null;
}
// no handler registered
// serve the file from the filesystem, restricting to a safelist of extensions
private static bool ShouldAllow(string filePath)
{
var fileExt = Path.GetExtension(filePath);
if (string.IsNullOrEmpty(fileExt)) return false;
return EndpointHost.Config.AllowFileExtensions.Contains(fileExt.Substring(1));
}
/// <summary>Gets handler for path information.</summary>
///
/// <param name="httpMethod"> The HTTP method.</param>
/// <param name="pathInfo"> Information describing the path.</param>
/// <param name="requestPath">Full pathname of the request file.</param>
/// <param name="filePath"> Full pathname of the file.</param>
///
/// <returns>The handler for path information.</returns>
public static IHttpHandler GetHandlerForPathInfo(string httpMethod, string pathInfo, string requestPath, string filePath)
{
var pathParts = pathInfo.TrimStart('/').Split('/');
if (pathParts.Length == 0) return NotFoundHttpHandler;
string contentType;
var restPath = RestHandler.FindMatchingRestPath(httpMethod, pathInfo, out contentType);
if (restPath != null)
return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.Name, ResponseContentType = contentType };
var existingFile = pathParts[0].ToLower();
if (WebHostRootFileNames.Contains(existingFile))
{
var fileExt = Path.GetExtension(filePath);
var isFileRequest = !string.IsNullOrEmpty(fileExt);
if (!isFileRequest && !AutoRedirectsDirs)
{
//If pathInfo is for Directory try again with redirect including '/' suffix
if (!pathInfo.EndsWith("/"))
{
var appFilePath = filePath.Substring(0, filePath.Length - requestPath.Length);
var redirect = Support.StaticFileHandler.DirectoryExists(filePath, appFilePath);
if (redirect)
{
return new RedirectHttpHandler
{
RelativeUrl = pathInfo + "/",
};
}
}
}
//e.g. CatchAllHandler to Process Markdown files
var catchAllHandler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath);
if (catchAllHandler != null) return catchAllHandler;
if (!isFileRequest) return NotFoundHttpHandler;
return ShouldAllow(requestPath) ? StaticFileHandler : ForbiddenHttpHandler;
}
var handler = GetCatchAllHandlerIfAny(httpMethod, pathInfo, filePath);
if (handler != null) return handler;
if (EndpointHost.Config.FallbackRestPath != null)
{
restPath = EndpointHost.Config.FallbackRestPath(httpMethod, pathInfo, filePath);
if (restPath != null)
{
return new RestHandler { RestPath = restPath, RequestName = restPath.RequestType.Name, ResponseContentType = contentType };
}
}
return null;
}
private static IHttpHandler GetCatchAllHandlerIfAny(string httpMethod, string pathInfo, string filePath)
{
if (EndpointHost.CatchAllHandlers != null)
{
foreach (var httpHandlerResolver in EndpointHost.CatchAllHandlers)
{
var httpHandler = httpHandlerResolver(httpMethod, pathInfo, filePath);
if (httpHandler != null)
return httpHandler;
}
}
return null;
}
/// <summary>Enables a factory to reuse an existing handler instance.</summary>
///
/// <param name="handler">The <see cref="T:System.Web.IHttpHandler" /> object to reuse.</param>
public void ReleaseHandler(IHttpHandler handler)
{
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ProtocolsSection.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
//
namespace System.Web.Configuration
{
using System;
using System.Xml;
using System.Configuration;
using System.Web.Configuration;
using System.Collections.Specialized;
using System.Collections;
using System.IO;
using System.Text;
using System.Globalization;
using System.Web.Hosting;
using System.Web.Util;
using System.Security.Permissions;
public sealed class ProtocolsSection : ConfigurationSection
{
private static readonly ConfigurationPropertyCollection _properties;
#region Property Declarations
private static readonly ConfigurationProperty _propProtocols =
new ConfigurationProperty(null, typeof(ProtocolCollection), null, ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsDefaultCollection);
#endregion
static ProtocolsSection()
{
// Property initialization
_properties = new ConfigurationPropertyCollection();
_properties.Add(_propProtocols);
}
public ProtocolsSection()
{
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return _properties;
}
}
[ConfigurationProperty("protocols", IsRequired = true, IsDefaultCollection = true)]
public ProtocolCollection Protocols
{
get
{
return (ProtocolCollection)base[_propProtocols];
}
}
}
[ConfigurationCollection(typeof(ProtocolElement))]
public sealed class ProtocolCollection : ConfigurationElementCollection
{
private static readonly ConfigurationPropertyCollection _properties;
static ProtocolCollection()
{
_properties = new ConfigurationPropertyCollection();
}
public ProtocolCollection()
{
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return _properties;
}
}
public string[] AllKeys
{
get
{
return (string[])BaseGetAllKeys();
}
}
public void Add( ProtocolElement protocolElement )
{
BaseAdd( protocolElement );
}
public void Remove( string name )
{
BaseRemove( name );
}
public void Remove( ProtocolElement protocolElement )
{
BaseRemove( GetElementKey( protocolElement ) );
}
public void RemoveAt( int index )
{
BaseRemoveAt( index );
}
public new ProtocolElement this[ string name ]
{
get
{
return (ProtocolElement)BaseGet( name );
}
}
public ProtocolElement this[ int index ]
{
get
{
return (ProtocolElement)BaseGet( index );
}
set
{
if ( BaseGet( index ) != null)
{
BaseRemoveAt( index );
}
BaseAdd( index, value );
}
}
public void Clear()
{
BaseClear();
}
protected override ConfigurationElement CreateNewElement()
{
return new ProtocolElement();
}
protected override Object GetElementKey( ConfigurationElement element )
{
string name = ((ProtocolElement)element).Name;
if ( string.IsNullOrEmpty( name ) )
{
throw new ArgumentException( SR.GetString(SR.Config_collection_add_element_without_key) );
}
return name;
}
}
public sealed class ProtocolElement : ConfigurationElement
{
private static readonly ConfigurationPropertyCollection _properties;
#region Property Declarations
private static readonly ConfigurationProperty _propName =
new ConfigurationProperty( "name",
typeof( string ),
null,
null,
StdValidatorsAndConverters.NonEmptyStringValidator,
ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey );
private static readonly ConfigurationProperty _propProcessHandlerType =
new ConfigurationProperty( "processHandlerType",
typeof( string ),
null);
private static readonly ConfigurationProperty _propAppDomainHandlerType =
new ConfigurationProperty( "appDomainHandlerType",
typeof( string ),
null);
private static readonly ConfigurationProperty _propValidate =
new ConfigurationProperty( "validate",
typeof( bool ),
false);
#endregion
static ProtocolElement()
{
_properties = new ConfigurationPropertyCollection();
_properties.Add( _propName );
_properties.Add( _propProcessHandlerType );
_properties.Add( _propAppDomainHandlerType );
_properties.Add( _propValidate );
}
public ProtocolElement( string name )
{
if ( string.IsNullOrEmpty( name ) )
{
throw ExceptionUtil.ParameterNullOrEmpty("name");
}
base[ _propName ] = name;
}
public ProtocolElement()
{
}
protected override ConfigurationPropertyCollection Properties
{
get
{
return _properties;
}
}
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
[StringValidator(MinLength = 1)]
public string Name
{
get
{
return (string)base[ _propName ];
}
set
{
base[ _propName ] = value;
}
}
[ConfigurationProperty("processHandlerType")]
public string ProcessHandlerType
{
get
{
return (string)base[ _propProcessHandlerType ];
}
set
{
base[ _propProcessHandlerType ] = value;
}
}
[ConfigurationProperty("appDomainHandlerType")]
public string AppDomainHandlerType
{
get
{
return (string)base[ _propAppDomainHandlerType ];
}
set
{
base[ _propAppDomainHandlerType ] = value;
}
}
[ConfigurationProperty("validate", DefaultValue = false)]
public bool Validate
{
get
{
return (bool)base[ _propValidate ];
}
set
{
base[ _propValidate ] = value;
}
}
private void ValidateTypes() {
// check process protocol handler
Type processHandlerType;
try {
processHandlerType = Type.GetType(ProcessHandlerType, true /*throwOnError*/);
}
catch (Exception e) {
throw new ConfigurationErrorsException(
e.Message,
e,
this.ElementInformation.Properties["ProcessHandlerType"].Source,
this.ElementInformation.Properties["ProcessHandlerType"].LineNumber);
}
ConfigUtil.CheckAssignableType( typeof(ProcessProtocolHandler), processHandlerType, this, "ProcessHandlerType");
// check app domain protocol handler
Type appDomainHandlerType;
try {
appDomainHandlerType = Type.GetType(AppDomainHandlerType, true /*throwOnError*/);
}
catch (Exception e) {
throw new ConfigurationErrorsException(
e.Message,
e,
this.ElementInformation.Properties["AppDomainHandlerType"].Source,
this.ElementInformation.Properties["AppDomainHandlerType"].LineNumber);
}
ConfigUtil.CheckAssignableType( typeof(AppDomainProtocolHandler), appDomainHandlerType, this, "AppDomainHandlerType");
}
protected override void PostDeserialize()
{
if (Validate) {
ValidateTypes();
}
}
}
}
| |
/*
Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.VectorMath;
using MIConvexHull;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MatterHackers.PolygonMesh
{
public static class MeshConvexHull
{
public static string ConvexHullMesh => nameof(ConvexHullMesh);
public static string CreatingConvexHullMesh => nameof(CreatingConvexHullMesh);
public static Mesh GetConvexHull(this Mesh mesh, bool generateAsync)
{
// currently disabling async as it has some threading issues
generateAsync = false;
if (mesh.Faces.Count < 4)
{
return null;
}
// build the convex hull for faster bounding calculations
// we have a mesh so don't recurse into children
object meshData;
mesh.PropertyBag.TryGetValue(ConvexHullMesh, out meshData);
if (meshData is Mesh convexHullMesh)
{
return convexHullMesh;
}
else
{
object creatingHullData;
mesh.PropertyBag.TryGetValue(CreatingConvexHullMesh, out creatingHullData);
bool currentlyCreatingHull = creatingHullData is CreatingHullFlag;
if (!currentlyCreatingHull)
{
// set the marker that we are creating the data
if (generateAsync)
{
mesh.PropertyBag.Add(CreatingConvexHullMesh, new CreatingHullFlag());
Task.Run(() =>
{
CreateHullMesh(mesh);
if (mesh.PropertyBag.ContainsKey(CreatingConvexHullMesh))
{
mesh.PropertyBag.Remove(CreatingConvexHullMesh);
}
});
}
else
{
return CreateHullMesh(mesh);
}
}
else if (!generateAsync)
{
var count = 0;
// we need to wait for the data to be ready and return it
while (currentlyCreatingHull && count < 1000)
{
Thread.Sleep(1);
mesh.PropertyBag.TryGetValue(CreatingConvexHullMesh, out creatingHullData);
currentlyCreatingHull = creatingHullData is CreatingHullFlag;
count++;
}
return CreateHullMesh(mesh);
}
}
return null;
}
private static Mesh CreateHullMesh(Mesh mesh)
{
var bounds = AxisAlignedBoundingBox.Empty();
// Get the convex hull for the mesh
var cHVertexList = new List<CHVertex>();
foreach (var position in mesh.Vertices.Distinct().ToArray())
{
cHVertexList.Add(new CHVertex(position));
bounds.ExpandToInclude(position);
}
var tollerance = .01;
if (cHVertexList.Count == 0
|| bounds.XSize <= tollerance
|| bounds.YSize <= tollerance
|| bounds.ZSize <= tollerance
|| double.IsNaN(cHVertexList.First().Position[0]))
{
return mesh;
}
var convexHull = ConvexHull.Create<CHVertex, CHFace>(cHVertexList, tollerance);
if (convexHull?.Result != null)
{
// create the mesh from the hull data
Mesh hullMesh = new Mesh();
foreach (var face in convexHull.Result.Faces)
{
int vertexCount = hullMesh.Vertices.Count;
foreach (var vertex in face.Vertices)
{
hullMesh.Vertices.Add(new Vector3(vertex.Position[0], vertex.Position[1], vertex.Position[2]));
}
hullMesh.Faces.Add(vertexCount, vertexCount + 1, vertexCount + 2, hullMesh.Vertices);
}
try
{
// make sure there is not currently a convex hull on this object
if (mesh.PropertyBag.ContainsKey(ConvexHullMesh))
{
mesh.PropertyBag.Remove(ConvexHullMesh);
}
// add the new hull
mesh.PropertyBag.Add(ConvexHullMesh, hullMesh);
// make sure we remove this hull if the mesh changes
mesh.Changed += MeshChanged_RemoveConvexHull;
// remove the marker that says we are building the hull
if (mesh.PropertyBag.ContainsKey(CreatingConvexHullMesh))
{
mesh.PropertyBag.Remove(CreatingConvexHullMesh);
}
return hullMesh;
}
catch
{
mesh.PropertyBag.Remove(CreatingConvexHullMesh);
}
}
return null;
}
private static void MeshChanged_RemoveConvexHull(object sender, EventArgs e)
{
if (sender is Mesh mesh)
{
mesh.Changed -= MeshChanged_RemoveConvexHull;
// remove any cached hull as it is no longer valid (the mesh changed)
if (mesh.PropertyBag.ContainsKey(ConvexHullMesh))
{
mesh.PropertyBag.Remove(ConvexHullMesh);
}
// remove the marker that says we are building the hull
if (mesh.PropertyBag.ContainsKey(CreatingConvexHullMesh))
{
mesh.PropertyBag.Remove(CreatingConvexHullMesh);
}
}
}
internal class CHFace : ConvexFace<CHVertex, CHFace>
{
}
internal class CHVertex : MIConvexHull.IVertex
{
private double[] position;
internal CHVertex(Vector3 position)
{
this.position = position.ToArray();
}
internal CHVertex(Vector3Float position)
{
this.position = new double[] { position.X, position.Y, position.Z };
}
public double[] Position => position;
}
internal class CreatingHullFlag
{
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.UI;
public class TwitchComponentHandle : MonoBehaviour
{
public enum Direction
{
Up,
Down,
Left,
Right
}
#region Public Fields
public TwitchMessage messagePrefab = null;
public Image unsupportedPrefab = null;
public Image idBannerPrefab = null;
public CanvasGroup canvasGroup = null;
public CanvasGroup highlightGroup = null;
public CanvasGroup canvasGroupMultiDecker = null;
public Text headerText = null;
public Text idText = null;
public Text idTextMultiDecker = null;
public ScrollRect messageScroll = null;
public GameObject messageScrollContents = null;
public Image upArrow = null;
public Image downArrow = null;
public Image leftArrow = null;
public Image rightArrow = null;
public Image upArrowHighlight = null;
public Image downArrowHighlight = null;
public Image leftArrowHighlight = null;
public Image rightArrowHighlight = null;
public Color claimedBackgroundColour = new Color(255, 0, 0);
public Color solvedBackgroundColor = new Color(0,128,0);
public Color markedBackgroundColor = new Color(0, 0, 0);
public AudioSource takeModuleSound = null;
[HideInInspector]
public IRCConnection ircConnection = null;
[HideInInspector]
public BombCommander bombCommander = null;
[HideInInspector]
public MonoBehaviour bombComponent = null;
[HideInInspector]
public ComponentTypeEnum componentType = ComponentTypeEnum.Empty;
[HideInInspector]
public Vector3 basePosition = Vector3.zero;
[HideInInspector]
public Vector3 idealHandlePositionOffset = Vector3.zero;
[HideInInspector]
public Direction direction = Direction.Up;
[HideInInspector]
public CoroutineQueue coroutineQueue = null;
[HideInInspector]
public CoroutineCanceller coroutineCanceller = null;
[HideInInspector]
public Leaderboard leaderboard = null;
[HideInInspector]
public bool claimed { get { return (playerName != null); } }
[HideInInspector]
public int bombID;
#endregion
#region Private Fields
private string _code = null;
private ComponentSolver _solver = null;
private Color unclaimedBackgroundColor = new Color(0, 0, 0);
private string playerName = null;
private bool _solved = false;
#endregion
#region Private Statics
private static List<TwitchComponentHandle> _unsupportedComponents = new List<TwitchComponentHandle>();
private static List<BombCommander> _bombCommanders = new List<BombCommander>();
private static int _nextID = 0;
private static int GetNewID()
{
return ++_nextID;
}
#endregion
#region Unity Lifecycle
private void Awake()
{
_code = GetNewID().ToString();
}
private void Start()
{
if (bombComponent != null)
{
headerText.text = (string)CommonReflectedTypeInfo.ModuleDisplayNameField.Invoke(bombComponent, null);
}
idText.text = string.Format("!{0}", _code);
idTextMultiDecker.text = _code;
canvasGroup.alpha = 0.0f;
highlightGroup.alpha = 0.0f;
canvasGroupMultiDecker.alpha = bombCommander.multiDecker ? 1.0f : 0.0f;
unclaimedBackgroundColor = idBannerPrefab.GetComponent<Image>().color;
try
{
_solver = ComponentSolverFactory.CreateSolver(bombCommander, bombComponent, componentType, ircConnection, coroutineCanceller);
if (_solver != null)
{
_solver.Code = _code;
_solver.ComponentHandle = this;
Vector3 pos = canvasGroupMultiDecker.transform.localPosition;
canvasGroupMultiDecker.transform.localPosition = new Vector3(_solver.modInfo.statusLightLeft ? -pos.x : pos.x, pos.y, _solver.modInfo.statusLightDown ? -pos.z : pos.z);
/*Vector3 angle = canvasGroupMultiDecker.transform.eulerAngles;
canvasGroupMultiDecker.transform.localEulerAngles = new Vector3(angle.x, _solver.modInfo.chatRotation, angle.z);
angle = canvasGroupMultiDecker.transform.localEulerAngles;
canvasGroup.transform.localEulerAngles = new Vector3(angle.x, _solver.modInfo.chatRotation, angle.z);
switch ((int) _solver.modInfo.chatRotation)
{
case 90:
case -270:
switch (direction)
{
case Direction.Up:
direction = Direction.Left;
break;
case Direction.Left:
direction = Direction.Down;
break;
case Direction.Down:
direction = Direction.Right;
break;
case Direction.Right:
direction = Direction.Up;
break;
}
break;
case 180:
case -180:
switch (direction)
{
case Direction.Up:
direction = Direction.Down;
break;
case Direction.Left:
direction = Direction.Right;
break;
case Direction.Down:
direction = Direction.Up;
break;
case Direction.Right:
direction = Direction.Left;
break;
}
break;
case 270:
case -90:
switch (direction)
{
case Direction.Up:
direction = Direction.Right;
break;
case Direction.Left:
direction = Direction.Up;
break;
case Direction.Down:
direction = Direction.Left;
break;
case Direction.Right:
direction = Direction.Down;
break;
}
break;
}*/
}
}
catch (Exception e)
{
Debug.Log(e.Message);
unsupportedPrefab.gameObject.SetActive(true);
idBannerPrefab.gameObject.SetActive(false);
canvasGroupMultiDecker.alpha = 0.0f;
_unsupportedComponents.Add(this);
if (TwitchPlaySettings.data.EnableTwitchPlaysMode && !TwitchPlaySettings.data.EnableInteractiveMode)
{
Debug.Log("[TwitchPlays] An unimplemented module was added to a bomb, solving module.");
}
}
if (!_bombCommanders.Contains(bombCommander))
{
_bombCommanders.Add(bombCommander);
}
Arrow.gameObject.SetActive(true);
HighlightArrow.gameObject.SetActive(true);
}
public static bool SolveUnsupportedModules()
{
bool result = _unsupportedComponents.Count > 0;
foreach (TwitchComponentHandle handle in _unsupportedComponents)
{
CommonReflectedTypeInfo.HandlePassMethod.Invoke(handle.bombComponent, null);
}
if (result)
{
RemoveSolveBasedModules();
}
_unsupportedComponents.Clear();
return result;
}
public static void RemoveSolveBasedModules()
{
foreach (BombCommander commander in _bombCommanders)
{
commander.RemoveSolveBasedModules();
}
_bombCommanders.Clear();
}
public static void ClearUnsupportedModules()
{
_bombCommanders.Clear();
_unsupportedComponents.Clear();
}
private void LateUpdate()
{
if (!bombCommander.multiDecker)
{
Vector3 cameraForward = Camera.main.transform.forward;
Vector3 componentForward = transform.up;
float angle = Vector3.Angle(cameraForward, -componentForward);
float lerpAmount = Mathf.InverseLerp(60.0f, 20.0f, angle);
lerpAmount = Mathf.Lerp(canvasGroup.alpha, lerpAmount, Time.deltaTime * 5.0f);
canvasGroup.alpha = lerpAmount;
transform.localPosition = basePosition + Vector3.Lerp(Vector3.zero, idealHandlePositionOffset, Mathf.SmoothStep(0.0f, 1.0f, lerpAmount));
messageScroll.verticalNormalizedPosition = 0.0f;
}
}
public void OnPass()
{
canvasGroupMultiDecker.alpha = 0.0f;
_solved = true;
if (playerName != null)
{
ClaimedList.Remove(playerName);
}
if (TakeInProgress != null)
{
StopCoroutine(TakeInProgress);
TakeInProgress = null;
}
}
public static void ResetId()
{
_nextID = 0;
}
#endregion
public IEnumerator TakeModule(string userNickName, string targetModule)
{
if (takeModuleSound != null)
{
takeModuleSound.time = 0.0f;
takeModuleSound.Play();
}
yield return new WaitForSecondsRealtime(60.0f);
SetBannerColor(unclaimedBackgroundColor);
if (playerName != null)
{
ircConnection.SendMessage(string.Format("/me {1} has released Module {0} ({2}).", targetModule, playerName, headerText.text));
ClaimedList.Remove(playerName);
playerName = null;
TakeInProgress = null;
}
}
public IEnumerator ReleaseModule(string player, string userNickName)
{
if (_solved)
{
yield break;
}
if (!UserAccess.HasAccess(userNickName, AccessLevel.Mod))
{
yield return new WaitForSeconds(TwitchPlaySettings.data.ClaimCooldownTime);
}
if(!_solved)
{
ClaimedList.Remove(player);
}
}
public string ClaimModule(string userNickName, string targetModule)
{
if (playerName == null)
{
if (ClaimedList.Count(nick => nick.Equals(userNickName)) >= TwitchPlaySettings.data.ModuleClaimLimit && !_solved)
{
return string.Format(TwitchPlaySettings.data.TooManyClaimed, userNickName, TwitchPlaySettings.data.ModuleClaimLimit);
}
else
{
if (!_solved)
{
ClaimedList.Add(userNickName);
}
SetBannerColor(claimedBackgroundColour);
playerName = userNickName;
return string.Format("/me {1} has claimed Module {0} ({2}).", targetModule, playerName, headerText.text);
}
}
return null;
}
public IEnumerator TakeInProgress = null;
public static List<string> ClaimedList = new List<string>();
#region Message Interface
public IEnumerator OnMessageReceived(string userNickName, string userColor, string text)
{
Match match = Regex.Match(text, string.Format("^!({0}) (.+)", _code), RegexOptions.IgnoreCase);
if (!match.Success)
{
return null;
}
string targetModule = match.Groups[1].Value;
string internalCommand = match.Groups[2].Value;
string messageOut = null;
if ((internalCommand.StartsWith("manual", StringComparison.InvariantCultureIgnoreCase)) || (internalCommand.Equals("help", StringComparison.InvariantCultureIgnoreCase)))
{
string manualText = null;
string manualType = "html";
if ( (internalCommand.Length > 7) && (internalCommand.Substring(7) == "pdf") )
{
manualType = "pdf";
}
if (string.IsNullOrEmpty(_solver.modInfo.manualCode)) {
manualText = headerText.text;
}
else {
manualText = _solver.modInfo.manualCode;
}
if (manualText.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) ||
manualText.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase))
{
messageOut = string.Format("{0} : {1} : {2}", headerText.text, _solver.modInfo.helpText, manualText);
}
else
{
//messageOut = string.Format("{0}: {1}", headerText.text, TwitchPlaysService.urlHelper.ManualFor(manualText, manualType));
messageOut = string.Format("{0} : {1} : {2}", headerText.text, _solver.modInfo.helpText, TwitchPlaysService.urlHelper.ManualFor(manualText, manualType));
}
}
else if (Regex.IsMatch(internalCommand, "^(bomb|queue) (turn( a?round)?|flip|spin)$", RegexOptions.IgnoreCase) && !_solved)
{
if (!_solver._turnQueued)
{
_solver._turnQueued = true;
StartCoroutine(_solver.TurnBombOnSolve());
}
messageOut = string.Format("/me Turning to the other side when Module {0} ({1}) is solved", targetModule, headerText.text);
}
else if (Regex.IsMatch(internalCommand, "^cancel (bomb|queue) (turn( a?round)?|flip|spin)$", RegexOptions.IgnoreCase) && !_solved)
{
_solver._turnQueued = false;
messageOut = string.Format("/me Bomb turn on Module {0} ({1}) solve cancelled", targetModule, headerText.text);
}
else if (internalCommand.Equals("claim", StringComparison.InvariantCultureIgnoreCase))
{
messageOut = ClaimModule(userNickName, targetModule);
}
else if (internalCommand.Equals("unclaim", StringComparison.InvariantCultureIgnoreCase))
{
if (((playerName != null) && (playerName == userNickName)) || (UserAccess.HasAccess(userNickName, AccessLevel.Mod)))
{
if (TakeInProgress != null)
{
StopCoroutine(TakeInProgress);
TakeInProgress = null;
}
StartCoroutine(ReleaseModule(playerName, userNickName));
SetBannerColor(unclaimedBackgroundColor);
messageOut = string.Format("/me {1} has released Module {0} ({2}).", targetModule, playerName, headerText.text);
playerName = null;
}
}
else if (internalCommand.Equals("solved", StringComparison.InvariantCultureIgnoreCase))
{
if (UserAccess.HasAccess(userNickName, AccessLevel.Mod))
{
SetBannerColor(solvedBackgroundColor);
playerName = null;
messageOut = string.Format("/me {1} says module {0} ({2}) is ready to be submitted", targetModule, userNickName, headerText.text);
}
}
else if (internalCommand.StartsWith("assign", StringComparison.InvariantCultureIgnoreCase))
{
if (UserAccess.HasAccess(userNickName, AccessLevel.Mod))
{
if (playerName != null && !_solved)
{
ClaimedList.Remove(playerName);
}
string newplayerName = internalCommand.Remove(0, 7).Trim();
playerName = newplayerName;
if(!_solved)
{
ClaimedList.Add(playerName);
}
SetBannerColor(claimedBackgroundColour);
messageOut = string.Format("/me Module {0} ({3}) assigned to {1} by {2}", targetModule, playerName, userNickName, headerText.text);
}
}
else if (internalCommand.Equals("take", StringComparison.InvariantCultureIgnoreCase))
{
if ((playerName != null) && (userNickName != playerName) && (TakeInProgress == null))
{
if (!_solved)
{
messageOut = string.Format("/me {0}, {1} wishes to take Module {2} ({3}). It will be freed up in one minute unless you type !{2} mine.", playerName, userNickName, targetModule, headerText.text);
TakeInProgress = TakeModule(userNickName, targetModule);
StartCoroutine(TakeInProgress);
}
}
else if ((playerName != null) && (userNickName != playerName))
{
messageOut = string.Format("/me Sorry @{0}, There is already a takeover attempt for Module {1} ({2}) in progress.", userNickName, targetModule, headerText.text);
}
}
else if (internalCommand.Equals("mine", StringComparison.InvariantCultureIgnoreCase))
{
if (playerName == userNickName)
{
messageOut = string.Format("/me {0} confirms he/she is still working on {1} ({2})", playerName, targetModule, headerText.text);
if (TakeInProgress != null)
{
StopCoroutine(TakeInProgress);
TakeInProgress = null;
}
}
else if (playerName == null)
{
messageOut = ClaimModule(userNickName, targetModule);
}
}
else if (internalCommand.Equals("mark", StringComparison.InvariantCultureIgnoreCase))
{
if (UserAccess.HasAccess(userNickName, AccessLevel.Mod))
{
SetBannerColor(markedBackgroundColor);
return null;
}
}
else if (internalCommand.Equals("player", StringComparison.InvariantCultureIgnoreCase))
{
if (playerName != null)
{
messageOut = string.Format("/me Module {0} ({2}) was claimed by {1}", targetModule, playerName, headerText.text);
}
}
if (!string.IsNullOrEmpty(messageOut))
{
ircConnection.SendMessage(string.Format(messageOut, _code, headerText.text));
return null;
}
TwitchMessage message = (TwitchMessage)Instantiate(messagePrefab, messageScrollContents.transform, false);
message.leaderboard = leaderboard;
message.userName = userNickName;
if (string.IsNullOrEmpty(userColor))
{
message.SetMessage(string.Format("<b>{0}</b>: {1}", userNickName, internalCommand));
message.userColor = new Color(0.31f, 0.31f, 0.31f);
}
else
{
message.SetMessage(string.Format("<b><color={2}>{0}</color></b>: {1}", userNickName, internalCommand, userColor));
if (!ColorUtility.TryParseHtmlString(userColor, out message.userColor))
{
message.userColor = new Color(0.31f, 0.31f, 0.31f);
}
}
if (_solver != null)
{
if ((bombCommander.CurrentTimer > 60.0f) && (playerName != null) && (playerName != userNickName) && (!(internalCommand.Equals("take", StringComparison.InvariantCultureIgnoreCase))))
{
ircConnection.SendMessage(string.Format("/me Sorry @{2}, Module {0} ({3}) is currently claimed by {1}. If you think they have abandoned it, you may type !{0} take to free it up.", targetModule, playerName, userNickName, headerText.text));
return null;
}
else
{
return RespondToCommandCoroutine(userNickName, internalCommand, message);
}
}
else
{
return null;
}
}
#endregion
#region Private Methods
private IEnumerator RespondToCommandCoroutine(string userNickName, string internalCommand, ICommandResponseNotifier message, float fadeDuration = 0.1f)
{
float time = Time.time;
while (Time.time - time < fadeDuration)
{
float lerp = (Time.time - time) / fadeDuration;
highlightGroup.alpha = Mathf.Lerp(0.0f, 1.0f, lerp);
yield return null;
}
highlightGroup.alpha = 1.0f;
if (_solver != null)
{
IEnumerator commandResponseCoroutine = _solver.RespondToCommand(userNickName, internalCommand, message, ircConnection);
while (commandResponseCoroutine.MoveNext())
{
yield return commandResponseCoroutine.Current;
}
}
time = Time.time;
while (Time.time - time < fadeDuration)
{
float lerp = (Time.time - time) / fadeDuration;
highlightGroup.alpha = Mathf.Lerp(1.0f, 0.0f, lerp);
yield return null;
}
highlightGroup.alpha = 0.0f;
}
private void SetBannerColor(Color color)
{
idBannerPrefab.GetComponent<Image>().color = color;
canvasGroupMultiDecker.GetComponent<Image>().color = color;
}
#endregion
#region Private Properties
private Image Arrow
{
get
{
switch (direction)
{
case Direction.Up:
return upArrow;
case Direction.Down:
return downArrow;
case Direction.Left:
return leftArrow;
case Direction.Right:
return rightArrow;
default:
return null;
}
}
}
private Image HighlightArrow
{
get
{
switch (direction)
{
case Direction.Up:
return upArrowHighlight;
case Direction.Down:
return downArrowHighlight;
case Direction.Left:
return leftArrowHighlight;
case Direction.Right:
return rightArrowHighlight;
default:
return null;
}
}
}
#endregion
}
| |
using System;
using System.Collections;
using T = GuruComponents.CodeEditor.CodeEditor.Syntax.UndoBlockCollection;
namespace GuruComponents.CodeEditor.CodeEditor.Syntax
{
/// <summary>
///
/// </summary>
public sealed class UndoBuffer : ICollection, IList, IEnumerable, ICloneable
{
#region PUBLIC PROPERTY MAXSIZE
private int _MaxSize = 1000;
public int MaxSize
{
get { return _MaxSize; }
set { _MaxSize = value; }
}
#endregion
private const int DefaultMinimumCapacity = 16;
private T[] m_array = new T[DefaultMinimumCapacity];
private int m_count = 0;
private int m_version = 0;
// Construction
/// <summary>
///
/// </summary>
public UndoBuffer()
{
}
/// <summary>
///
/// </summary>
/// <param name="collection"></param>
public UndoBuffer(UndoBuffer collection)
{
AddRange(collection);
}
/// <summary>
///
/// </summary>
/// <param name="array"></param>
public UndoBuffer(T[] array)
{
AddRange(array);
}
// Operations (type-safe ICollection)
/// <summary>
///
/// </summary>
public int Count
{
get { return m_count; }
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
/// <param name="count"></param>
public void RemoveRange(int index, int count)
{
for (int i = 0; i < count; i++)
{
if (i < this.Count)
this.RemoveAt(index);
else
break;
}
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
public void ClearFrom(int index)
{
while (index <= this.Count - 1)
this.RemoveAt(index);
}
/// <summary>
///
/// </summary>
/// <param name="array"></param>
public void CopyTo(T[] array)
{
this.CopyTo(array, 0);
}
/// <summary>
///
/// </summary>
/// <param name="array"></param>
/// <param name="start"></param>
public void CopyTo(T[] array, int start)
{
if (m_count > array.GetUpperBound(0) + 1 - start)
throw new ArgumentException("Destination array was not long enough.");
// for (int i=0; i < m_count; ++i) array[start+i] = m_array[i];
Array.Copy(m_array, 0, array, start, m_count);
}
// Operations (type-safe IList)
/// <summary>
///
/// </summary>
public T this[int index]
{
get
{
ValidateIndex(index); // throws
return m_array[index];
}
set
{
ValidateIndex(index); // throws
++m_version;
m_array[index] = value;
}
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public int Add(T item)
{
if (NeedsGrowth())
Grow();
++m_version;
m_array[m_count] = item;
m_count++;
while (this.Count > this.MaxSize)
{
this.RemoveAt(0);
}
return m_count;
}
/// <summary>
///
/// </summary>
public void Clear()
{
++m_version;
m_array = new T[DefaultMinimumCapacity];
m_count = 0;
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Contains(T item)
{
return ((IndexOf(item) == -1) ? false : true);
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public int IndexOf(T item)
{
for (int i = 0; i < m_count; ++i)
if (m_array[i] == (item))
return i;
return -1;
}
/// <summary>
///
/// </summary>
/// <param name="position"></param>
/// <param name="item"></param>
public void Insert(int position, T item)
{
ValidateIndex(position, true); // throws
if (NeedsGrowth())
Grow();
++m_version;
// for (int i=m_count; i > position; --i) m_array[i] = m_array[i-1];
Array.Copy(m_array, position, m_array, position + 1, m_count - position);
m_array[position] = item;
m_count++;
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
public void Remove(T item)
{
int index = IndexOf(item);
if (index < 0)
throw new ArgumentException("Cannot remove the specified item because it was not found in the specified Collection.");
RemoveAt(index);
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
public void RemoveAt(int index)
{
ValidateIndex(index); // throws
++m_version;
m_count--;
// for (int i=index; i < m_count; ++i) m_array[i] = m_array[i+1];
Array.Copy(m_array, index + 1, m_array, index, m_count - index);
if (NeedsTrimming())
Trim();
}
// Operations (type-safe IEnumerable)
/// <summary>
///
/// </summary>
/// <returns></returns>
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
// Operations (type-safe ICloneable)
/// <summary>
///
/// </summary>
/// <returns></returns>
public UndoBuffer Clone()
{
UndoBuffer tc = new UndoBuffer();
tc.AddRange(this);
tc.Capacity = this.m_array.Length;
tc.m_version = this.m_version;
return tc;
}
// Public helpers (just to mimic some nice features of ArrayList)
/// <summary>
///
/// </summary>
public int Capacity
{
get { return m_array.Length; }
set
{
if (value < m_count) value = m_count;
if (value < DefaultMinimumCapacity) value = DefaultMinimumCapacity;
if (m_array.Length == value) return;
++m_version;
T[] temp = new T[value];
// for (int i=0; i < m_count; ++i) temp[i] = m_array[i];
Array.Copy(m_array, 0, temp, 0, m_count);
m_array = temp;
}
}
/// <summary>
///
/// </summary>
/// <param name="collection"></param>
public void AddRange(UndoBuffer collection)
{
// for (int i=0; i < collection.Count; ++i) Add(collection[i]);
++m_version;
Capacity += collection.Count;
Array.Copy(collection.m_array, 0, this.m_array, m_count, collection.m_count);
m_count += collection.Count;
}
/// <summary>
///
/// </summary>
/// <param name="array"></param>
public void AddRange(T[] array)
{
// for (int i=0; i < array.Length; ++i) Add(array[i]);
++m_version;
Capacity += array.Length;
Array.Copy(array, 0, this.m_array, m_count, array.Length);
m_count += array.Length;
}
// Implementation (helpers)
private void ValidateIndex(int index)
{
ValidateIndex(index, false);
}
private void ValidateIndex(int index, bool allowEqualEnd)
{
int max = (allowEqualEnd) ? (m_count) : (m_count - 1);
if (index < 0 || index > max)
throw new ArgumentOutOfRangeException("Index was out of range. Must be non-negative and less than the size of the collection.", (object) index, "Specified argument was out of the range of valid values.");
}
private bool NeedsGrowth()
{
return (m_count >= Capacity);
}
private void Grow()
{
if (NeedsGrowth())
Capacity = m_count*2;
}
private bool NeedsTrimming()
{
return (m_count <= Capacity/2);
}
private void Trim()
{
if (NeedsTrimming())
Capacity = m_count;
}
// Implementation (ICollection)
/* redundant w/ type-safe method
int ICollection.Count
{
get
{ return m_count; }
}
*/
bool ICollection.IsSynchronized
{
get { return m_array.IsSynchronized; }
}
object ICollection.SyncRoot
{
get { return m_array.SyncRoot; }
}
void ICollection.CopyTo(Array array, int start)
{
this.CopyTo((T[]) array, start);
}
// Implementation (IList)
bool IList.IsFixedSize
{
get { return false; }
}
bool IList.IsReadOnly
{
get { return false; }
}
object IList.this[int index]
{
get { return (object) this[index]; }
set { this[index] = (T) value; }
}
int IList.Add(object item)
{
return this.Add((T) item);
}
/* redundant w/ type-safe method
void IList.Clear()
{
this.Clear();
}
*/
bool IList.Contains(object item)
{
return this.Contains((T) item);
}
int IList.IndexOf(object item)
{
return this.IndexOf((T) item);
}
void IList.Insert(int position, object item)
{
this.Insert(position, (T) item);
}
void IList.Remove(object item)
{
this.Remove((T) item);
}
/* redundant w/ type-safe method
void IList.RemoveAt(int index)
{
this.RemoveAt(index);
}
*/
// Implementation (IEnumerable)
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) (this.GetEnumerator());
}
// Implementation (ICloneable)
object ICloneable.Clone()
{
return (object) (this.Clone());
}
// Nested enumerator class
/// <summary>
///
/// </summary>
public class Enumerator : IEnumerator
{
private UndoBuffer m_collection;
private int m_index;
private int m_version;
// Construction
public Enumerator(UndoBuffer tc)
{
m_collection = tc;
m_index = -1;
m_version = tc.m_version;
}
// Operations (type-safe IEnumerator)
/// <summary>
///
/// </summary>
public T Current
{
get { return m_collection[m_index]; }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool MoveNext()
{
if (m_version != m_collection.m_version)
throw new InvalidOperationException("Collection was modified; enumeration operation may not execute.");
++m_index;
return (m_index < m_collection.Count) ? true : false;
}
/// <summary>
///
/// </summary>
public void Reset()
{
if (m_version != m_collection.m_version)
throw new InvalidOperationException("Collection was modified; enumeration operation may not execute.");
m_index = -1;
}
// Implementation (IEnumerator)
object IEnumerator.Current
{
get { return (object) (this.Current); }
}
/* redundant w/ type-safe method
bool IEnumerator.MoveNext()
{
return this.MoveNext();
}
*/
/* redundant w/ type-safe method
void IEnumerator.Reset()
{
this.Reset();
}
*/
}
}
}
| |
/*
* Copyright (c) 2012 Stephen A. Pratt
*
* 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 UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using org.critterai.nav;
using org.critterai.u3d.editor;
/// <summary>
/// <see cref="CAINavEditorSettings"/> editor.
/// </summary>
/// <exclude />
[CustomEditor(typeof(CAINavEditorSettings))]
public sealed class CAINavEditorSettingsEditor
: Editor
{
/// <summary>
/// A control GUI suitable for selecting an area based on its well known name.
/// </summary>
public class AreaGUIControl
{
private List<string> mNamesAll = new List<string>(Navmesh.MaxArea + 1);
private string[] mNamesShort;
private string mLabel;
internal AreaGUIControl(string label, string[] areaNames)
{
mLabel = label;
for (int i = 0; i < areaNames.Length; i++)
{
if (areaNames[i] != CAINavEditorSettings.Undefined)
mNamesAll.Add(areaNames[i]);
}
mNamesAll.Add(CAINavEditorSettings.Undefined);
mNamesShort = mNamesAll.ToArray();
mNamesAll.Clear();
mNamesAll.AddRange(areaNames);
}
/// <summary>
/// Displays the area selector.
/// </summary>
/// <param name="currentArea">The current area.</param>
/// <returns>The selected area.</returns>
public byte OnGUI(byte currentArea)
{
return OnGUI(mLabel, currentArea);
}
/// <summary>
/// Displays the area selector with a custom label.
/// </summary>
/// <param name="labelOverride">The custom label.</param>
/// <param name="currentArea">The current area.</param>
/// <returns>The selected area.</returns>
public byte OnGUI(string labelOverride, byte currentArea)
{
string name = mNamesAll[currentArea];
int undef = mNamesShort.Length - 1;
int i = undef;
for (;i >= 0; i--)
{
if (name == mNamesShort[i])
break;
}
if (i == undef)
mNamesShort[undef] = currentArea + " " + mNamesShort[undef];
int ni = EditorGUILayout.Popup(labelOverride, i, mNamesShort);
mNamesShort[undef] = CAINavEditorSettings.Undefined;
if (i == ni || ni == undef)
return currentArea;
return (byte)mNamesAll.IndexOf(mNamesShort[ni]);
}
}
private const string AddAreaName = "AddArea";
private static bool mShowAreas = true;
private static bool mShowFlags = true;
private static bool mShowAvoidance = true;
private static byte mNewArea = Navmesh.NullArea;
private static bool mFocusNew = false;
/// <summary>
/// Creates a control useful for assigning area values.
/// </summary>
/// <param name="label">The default label for the control.</param>
/// <returns></returns>
public static AreaGUIControl CreateAreaControl(string label)
{
CAINavEditorSettings settings = EditorUtil.GetGlobalAsset<CAINavEditorSettings>();
return new AreaGUIControl(label, (string[])settings.areaNames.Clone());
}
/// <summary>
/// Gets a clone of the global well know flag names.
/// </summary>
/// <returns>A clone of the flag names.</returns>
public static string[] GetFlagNames()
{
CAINavEditorSettings settings = EditorUtil.GetGlobalAsset<CAINavEditorSettings>();
return (string[])settings.flagNames.Clone();
}
/// <summary>
/// Gets a clone of the global well known avoidance type names.
/// </summary>
/// <returns>A clone of the well known avoidance type names.</returns>
public static string[] GetAvoidanceNames()
{
CAINavEditorSettings settings = EditorUtil.GetGlobalAsset<CAINavEditorSettings>();
return (string[])settings.avoidanceNames.Clone();
}
void OnEnable()
{
mNewArea = NextUndefinedArea();
}
/// <summary>
/// Controls behavior of the inspector.
/// </summary>
public override void OnInspectorGUI()
{
EditorGUIUtility.LookLikeControls(80);
EditorGUILayout.Separator();
mShowAreas = EditorGUILayout.Foldout(mShowAreas, "Area Names");
if (mShowAreas)
OnGUIAreas();
EditorGUILayout.Separator();
mShowFlags = EditorGUILayout.Foldout(mShowFlags, "Flag Names");
if (mShowFlags)
OnGUIFlags();
EditorGUILayout.Separator();
mShowAvoidance = EditorGUILayout.Foldout(mShowAvoidance, "Crowd Avoidance Names");
if (mShowAvoidance)
OnGUIAvoidance();
EditorGUILayout.Separator();
if (GUI.changed)
EditorUtility.SetDirty(target);
}
private byte NextUndefinedArea()
{
CAINavEditorSettings targ = (CAINavEditorSettings)target;
string[] areaNames = targ.areaNames;
for (int i = 1; i < areaNames.Length; i++)
{
if (areaNames[i] == CAINavEditorSettings.Undefined)
return (byte)i;
}
return 0;
}
private void OnGUIAreas()
{
CAINavEditorSettings targ = (CAINavEditorSettings)target;
string[] areaNames = targ.areaNames;
EditorGUILayout.Separator();
for (int i = 0; i < areaNames.Length; i++)
{
if (areaNames[i] == CAINavEditorSettings.Undefined)
continue;
EditorGUILayout.BeginHorizontal();
GUI.enabled = (i != Navmesh.NullArea);
string areaName = EditorGUILayout.TextField(i.ToString(), areaNames[i]);
// Note: Extra checks reduce the need to run the last check, which is more expensive.
if (areaName.Length > 0
&& areaName != areaNames[i]
&& areaName != CAINavEditorSettings.NotWalkable // Quick check.
&& areaName != CAINavEditorSettings.Undefined // This check is important.
&& targ.GetArea(areaName) == CAINavEditorSettings.UnknownArea)
{
areaNames[i] = areaName;
}
GUI.enabled = !(i == Navmesh.NullArea || i == Navmesh.MaxArea);
if (GUILayout.Button("X", GUILayout.Width(30)))
{
areaNames[i] = CAINavEditorSettings.Undefined;
mNewArea = NextUndefinedArea();
mFocusNew = true; // Prevents off GUI behavior.
GUI.changed = true;
}
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.Separator();
EditorGUILayout.BeginHorizontal();
GUI.SetNextControlName(AddAreaName);
mNewArea = NavUtil.ClampArea(EditorGUILayout.IntField(mNewArea, GUILayout.Width(80)));
if (mFocusNew)
{
GUI.FocusControl(AddAreaName);
mFocusNew = false;
}
GUI.enabled = (areaNames[mNewArea] == CAINavEditorSettings.Undefined);
if (GUILayout.Button("Add", GUILayout.Width(80)))
{
areaNames[mNewArea] = "Area " + mNewArea;
mNewArea = NextUndefinedArea();
mFocusNew = true;
GUI.changed = true;
}
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
EditorGUILayout.Separator();
EditorGUILayout.LabelField("Maximum allowed area: " + Navmesh.MaxArea
, EditorUtil.HelpStyle, GUILayout.ExpandWidth(true));
}
private void OnGUIFlags()
{
CAINavEditorSettings targ = (CAINavEditorSettings)target;
string[] names = targ.flagNames;
EditorGUILayout.Separator();
for (int i = 0; i < names.Length; i++)
{
string val = EditorGUILayout.TextField(string.Format("0x{0:X}", 1 << i), names[i]);
names[i] = (val.Length == 0 ? names[i] : val);
}
}
private void OnGUIAvoidance()
{
CAINavEditorSettings targ = (CAINavEditorSettings)target;
string[] names = targ.avoidanceNames;
EditorGUILayout.Separator();
for (int i = 0; i < names.Length; i++)
{
string val = EditorGUILayout.TextField(i.ToString(), names[i]);
names[i] = (val.Length == 0 ? names[i] : val);
}
}
[MenuItem(EditorUtil.MainMenu + "Nav Editor Settings", false, EditorUtil.GlobalGroup)]
static void EditSettings()
{
CAINavEditorSettings item = EditorUtil.GetGlobalAsset<CAINavEditorSettings>();
Selection.activeObject = item;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using GalaSoft.MvvmLight.Views;
using Android.Support.V4.App;
using MonocleGiraffe.Android.Fragments;
using Android.Util;
using Android.Support.V4.View;
using Android.Support.Design.Widget;
using Java.Lang;
using Android.Support.V4.Content;
using Android.Support.V7.App;
using Microsoft.Practices.ServiceLocation;
using MonocleGiraffe.Portable.ViewModels;
using MonocleGiraffe.Android.Helpers;
namespace MonocleGiraffe.Android.Activities
{
[Activity(Label = "FrontActivity")]
public class FrontActivity : AppCompatActivity
{
public NavigationService Nav
{
get
{
return (NavigationService)ServiceLocator.Current
.GetInstance<INavigationService>();
}
}
public FrontViewModel Vm { get { return App.Locator.Front; } }
FrontPagerAdapter pagerAdapter;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.AddFlags(WindowManagerFlags.DrawsSystemBarBackgrounds);
SetContentView(Resource.Layout.Front);
//Utils.SetPaddingForStatusBar(this, MainToolbar);
pagerAdapter = new FrontPagerAdapter(SupportFragmentManager);
var pager = FindViewById<ViewPager>(Resource.Id.MainPager);
var tabLayout = FindViewById<TabLayout>(Resource.Id.Tabs);
tabLayout.SetupWithViewPager(pager);
pager.OffscreenPageLimit = 3;
pager.Adapter = pagerAdapter;
pager.PageSelected += Pager_PageSelected;
SetTabContent(tabLayout);
SetSupportActionBar(MainToolbar);
tabLayout.TabSelected += TabLayout_TabSelected;
tabLayout.TabUnselected += TabLayout_TabUnselected;
//Launch setup
int currentIndex = pager.CurrentItem;
var selectedTab = tabLayout.GetTabAt(currentIndex);
var imageView = selectedTab.CustomView as ImageView;
imageView.SetColorFilter(new global::Android.Graphics.Color(ContextCompat.GetColor(this, Resource.Color.TabSelected)));
var title = pagerAdapter.GetTitle(currentIndex);
SupportActionBar.Title = title;
AnalyticsHelper.SendView(title);
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.main_menu, menu);
return true;
}
public override bool OnOptionsItemSelected(IMenuItem item)
{
var itemId = item.ItemId;
switch (itemId)
{
case Resource.Id.SettingsMenuItem:
StartActivity(new Intent(this, typeof(SettingsActivity)));
break;
//TODO: Uncomment this after downloads are implemented
//case Resource.Id.DownloadsMenuItem:
// break;
case Resource.Id.FeedbackMenuItem:
LaunchFeedbackEmail();
break;
}
return true;
}
private void LaunchFeedbackEmail()
{
var emailIntent = new Intent(Intent.ActionSend);
emailIntent.SetType("plain/text");
emailIntent.PutExtra(Intent.ExtraEmail, new string[] { "akshay2000+mg@hotmail.com" });
emailIntent.PutExtra(Intent.ExtraSubject, "Monocle Giraffe for Android");
emailIntent.PutExtra(Intent.ExtraText, "Write your feedback below\n_________________________");
StartActivity(Intent.CreateChooser(emailIntent, "Send Feedback"));
}
private void Pager_PageSelected(object sender, ViewPager.PageSelectedEventArgs e)
{
var title = pagerAdapter.GetTitle(e.Position);
SupportActionBar.Title = title;
AnalyticsHelper.SendView(title);
}
private global::Android.Support.V7.Widget.Toolbar mainToolbar;
public global::Android.Support.V7.Widget.Toolbar MainToolbar
{
get
{
mainToolbar = mainToolbar ?? FindViewById<global::Android.Support.V7.Widget.Toolbar>(Resource.Id.MainToolbar);
return mainToolbar;
}
}
private void TabLayout_TabUnselected(object sender, TabLayout.TabUnselectedEventArgs e)
{
var resolved = ContextCompat.GetColor(this, Resource.Color.TabUnselected);
var tab = e.Tab;
var imageView = tab.CustomView as ImageView;
imageView.SetColorFilter(new global::Android.Graphics.Color(resolved));
}
private void TabLayout_TabSelected(object sender, TabLayout.TabSelectedEventArgs e)
{
var resolved = ContextCompat.GetColor(this, Resource.Color.TabSelected);
var tab = e.Tab;
var imageView = tab.CustomView as ImageView;
imageView.SetColorFilter(new global::Android.Graphics.Color(resolved));
}
private void SetTabContent(TabLayout layout)
{
for (int i = 0; i < layout.TabCount; i++)
{
layout.GetTabAt(i).SetCustomView(pagerAdapter.GetTabView(i, LayoutInflater));
}
}
}
public class FrontPagerAdapter : FragmentPagerAdapter
{
public FrontPagerAdapter(global::Android.Support.V4.App.FragmentManager f) : base(f) { }
public override int Count { get { return 3; } }
public override global::Android.Support.V4.App.Fragment GetItem(int position)
{
switch (position)
{
case 0:
return Gallery;
case 1:
return Reddits;
case 2:
return Search;
case 3:
return Account;
}
Log.Debug("FrontActivity", $"position was {position}");
return null;
}
private int[] tabIcons = new int[] { Resource.Drawable.home, Resource.Drawable.reddit, Resource.Drawable.search };
public View GetTabView(int index, LayoutInflater inflater)
{
View view = inflater.Inflate(Resource.Layout.Ctrl_Tab, null);
var image = view.FindViewById<ImageView>(Resource.Id.TabIcon);
image.SetImageResource(tabIcons[index]);
return view;
}
private string[] titles = new string[] { "Gallery", "Subreddits", "Search", "Account" };
public string GetTitle(int index) => titles[index];
private GalleryFragment gallery;
private GalleryFragment Gallery
{
get
{
gallery = gallery ?? new GalleryFragment();
return gallery;
}
}
private RedditFragment reddits;
private RedditFragment Reddits
{
get
{
reddits = reddits ?? new RedditFragment();
return reddits;
}
}
private SearchFragment search;
private SearchFragment Search
{
get
{
search = search ?? new SearchFragment();
return search;
}
}
private AccountFragment account;
public AccountFragment Account
{
get
{
account = account ?? new AccountFragment();
return account;
}
}
}
}
| |
/*
* Copyright 2011 The Poderosa Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* $Id: PipePlugin.cs,v 1.2 2011/10/27 23:21:56 kzmi Exp $
*/
using System;
using System.Diagnostics;
using System.Windows.Forms;
using Poderosa;
using Poderosa.Commands;
using Poderosa.Forms;
using Poderosa.MacroEngine;
using Poderosa.Plugins;
using Poderosa.Protocols;
using Poderosa.Terminal;
using Poderosa.Sessions;
using Poderosa.Serializing;
[assembly: PluginDeclaration(typeof(Poderosa.Pipe.PipePlugin))]
namespace Poderosa.Pipe {
/// <summary>
/// Pipe plugin
///
/// <para>This plugin provides the connections which is using the pipe.</para>
///
/// <para>There are two connection types, "Process" and "Named Pipe".</para>
///
/// <para>Process type connection :
/// Launches an application whose standard input, standard output, and standard error were conneced to Poderosa with pipes.
/// The text input on a terminal in Poderosa are transmitted to the application's standard input through a pipe.
/// And the text output from application's standard output or standard error are received through a pipe and are displayed on a terminal in Poderosa.
/// </para>
///
/// <para>Named pipe type connection :
/// Opens one or two existing named pipe for the communication.
/// You can use one bidirectional named pipe for input and output,
/// and can also use two named pipes; one is for input and another is for output.
/// </para>
///
/// <para>When you use the process type connection, note that some applications use console APIs for its input and output.
/// If the application doesn't use standard input or standard output but use console APIs,
/// no text will be displayed on Poderosa or the application doesn't accept your key input.
/// </para>
/// </summary>
[PluginInfo(ID = PipePlugin.PLUGIN_ID,
Version = VersionInfo.PODEROSA_VERSION,
Author = VersionInfo.PROJECT_NAME,
Dependencies = "org.poderosa.terminalsessions;org.poderosa.terminalemulator;org.poderosa.core.serializing")]
internal class PipePlugin : PluginBase {
public const string PLUGIN_ID = "org.poderosa.pipe";
private static PipePlugin _instance;
private StringResource _stringResource;
private OpenPipeCommand _openPipeCommand;
private ITerminalSessionsService _terminalSessionsService;
private ITerminalEmulatorService _terminalEmulatorService;
private IAdapterManager _adapterManager;
private ICoreServices _coreServices;
private IMacroEngine _macroEngine;
private ISerializeService _serializeService;
/// <summary>
/// Get plugin's instance
/// </summary>
internal static PipePlugin Instance {
get {
return _instance;
}
}
/// <summary>
/// Get plugin's string resources
/// </summary>
internal StringResource Strings {
get {
return _stringResource;
}
}
/// <summary>
/// Get implementation of ITerminalSessionsService
/// </summary>
internal ITerminalSessionsService TerminalSessionsService {
get {
return _terminalSessionsService;
}
}
/// <summary>
/// Get implementation of ITerminalEmulatorService
/// </summary>
internal ITerminalEmulatorService TerminalEmulatorService {
get {
return _terminalEmulatorService;
}
}
/// <summary>
/// Get implementation of IAdapterManager
/// </summary>
internal IAdapterManager AdapterManager {
get {
return _adapterManager;
}
}
/// <summary>
/// Get implementation of ICommandManager
/// </summary>
internal ICommandManager CommandManager {
get {
return _coreServices.CommandManager;
}
}
/// <summary>
/// Get implementation of IMacroEngine
/// </summary>
public IMacroEngine MacroEngine {
get {
if (_macroEngine == null) {
_macroEngine = _poderosaWorld.PluginManager.FindPlugin("org.poderosa.macro", typeof(IMacroEngine)) as IMacroEngine;
}
return _macroEngine;
}
}
/// <summary>
/// Get implementation of ISerializeService
/// </summary>
public ISerializeService SerializeService {
get {
return _serializeService;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="poderosa">an instance of PoderosaWorld</param>
public override void InitializePlugin(IPoderosaWorld poderosa) {
base.InitializePlugin(poderosa);
_instance = this;
_poderosaWorld = poderosa;
_adapterManager = poderosa.AdapterManager;
_coreServices = (ICoreServices)poderosa.GetAdapter(typeof(ICoreServices));
_stringResource = new StringResource("Poderosa.Pipe.strings", typeof(PipePlugin).Assembly);
poderosa.Culture.AddChangeListener(_stringResource);
_terminalSessionsService = poderosa.PluginManager.FindPlugin("org.poderosa.terminalsessions", typeof(ITerminalSessionsService)) as ITerminalSessionsService;
_terminalEmulatorService = poderosa.PluginManager.FindPlugin("org.poderosa.terminalemulator", typeof(ITerminalEmulatorService)) as ITerminalEmulatorService;
_serializeService = poderosa.PluginManager.FindPlugin("org.poderosa.core.serializing", typeof(ISerializeService)) as ISerializeService;
IExtensionPoint extSer = _coreServices.SerializerExtensionPoint;
extSer.RegisterExtension(new PipeTerminalParameterSerializer());
extSer.RegisterExtension(new PipeTerminalSettingsSerializer());
_openPipeCommand = new OpenPipeCommand();
IPluginManager pm = poderosa.PluginManager;
pm.FindExtensionPoint("org.poderosa.menu.file").RegisterExtension(new PipeMenuGroup(_openPipeCommand));
// Toolbar button has not been added yet
//pm.FindExtensionPoint("org.poderosa.core.window.toolbar").RegisterExtension(new PipeToolBarComponent());
pm.FindExtensionPoint("org.poderosa.termianlsessions.terminalConnectionFactory").RegisterExtension(new PipeConnectionFactory());
}
}
/// <summary>
/// Menu group
/// </summary>
internal class PipeMenuGroup : PoderosaMenuGroupImpl {
/// <summary>
/// Constructor
/// </summary>
public PipeMenuGroup(IPoderosaCommand command)
: base(new PipeMenuItem(command)) {
_positionType = PositionType.DontCare;
}
}
/// <summary>
/// Menu item
/// </summary>
internal class PipeMenuItem : PoderosaMenuItemImpl {
/// <summary>
/// Constructor
/// </summary>
public PipeMenuItem(IPoderosaCommand command)
: base(command, PipePlugin.Instance.Strings, "Menu.OpenPipe") {
}
}
/// <summary>
/// Open pipe command
/// </summary>
internal class OpenPipeCommand : GeneralCommandImpl {
/// <summary>
/// Constructor
/// </summary>
public OpenPipeCommand()
: base("org.poderosa.session.openpipe", PipePlugin.Instance.Strings, "Command.OpenPipe", PipePlugin.Instance.TerminalSessionsService.ConnectCommandCategory) {
}
/// <summary>
/// Command execution
/// </summary>
public override CommandResult InternalExecute(ICommandTarget target, params IAdaptable[] args) {
PipeTerminalParameter paramInit = null;
PipeTerminalSettings settingsInit = null;
IExtensionPoint ext = PipePlugin.Instance.PoderosaWorld.PluginManager.FindExtensionPoint("org.poderosa.terminalsessions.loginDialogUISupport");
if (ext != null && ext.ExtensionInterface == typeof(ILoginDialogUISupport)) {
foreach (ILoginDialogUISupport sup in ext.GetExtensions()) {
ITerminalParameter terminalParam;
ITerminalSettings terminalSettings;
sup.FillTopDestination(typeof(PipeTerminalParameter), out terminalParam, out terminalSettings);
PipeTerminalParameter paramTemp = terminalParam as PipeTerminalParameter;
PipeTerminalSettings settingsTemp = terminalSettings as PipeTerminalSettings;
if (paramInit == null)
paramInit = paramTemp;
if (settingsInit == null)
settingsInit = settingsTemp;
}
}
if (paramInit == null)
paramInit = new PipeTerminalParameter();
if (settingsInit == null)
settingsInit = new PipeTerminalSettings();
IPoderosaMainWindow window = (IPoderosaMainWindow)target.GetAdapter(typeof(IPoderosaMainWindow));
CommandResult commandResult = CommandResult.Failed;
using (OpenPipeDialog dialog = new OpenPipeDialog()) {
dialog.OpenPipe =
delegate(PipeTerminalParameter param, PipeTerminalSettings settings) {
PipeTerminalConnection connection = PipeCreator.CreateNewPipeTerminalConnection(param, settings);
commandResult = PipePlugin.Instance.CommandManager.Execute(
PipePlugin.Instance.TerminalSessionsService.TerminalSessionStartCommand,
window, connection, settings);
return (commandResult == CommandResult.Succeeded);
};
dialog.ApplyParams(paramInit, settingsInit);
DialogResult dialogResult = dialog.ShowDialog(window != null ? window.AsForm() : null);
if (dialogResult == DialogResult.Cancel)
commandResult = CommandResult.Cancelled;
}
return commandResult;
}
}
/// <summary>
/// Implementation of ITerminalConnectionFactory
/// </summary>
internal class PipeConnectionFactory : ITerminalConnectionFactory {
public bool IsSupporting(ITerminalParameter param, ITerminalSettings settings) {
return (param is PipeTerminalParameter) && (settings is PipeTerminalSettings);
}
public ITerminalConnection EstablishConnection(IPoderosaMainWindow window, ITerminalParameter param, ITerminalSettings settings) {
PipeTerminalParameter tp = param as PipeTerminalParameter;
PipeTerminalSettings ts = settings as PipeTerminalSettings;
Debug.Assert(tp != null && ts != null);
return PipeCreator.CreateNewPipeTerminalConnection(tp, ts);
}
}
}
| |
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 IdentityServer4Tests.ApiResource.Areas.HelpPage.ModelDescriptions;
using IdentityServer4Tests.ApiResource.Areas.HelpPage.Models;
namespace IdentityServer4Tests.ApiResource.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);
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: TextEditorCharacters.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: A component of TextEditor supporting character formatting commands
//
//---------------------------------------------------------------------------
namespace System.Windows.Documents
{
using MS.Internal;
using System.Globalization;
using System.Threading;
using System.ComponentModel;
using System.Text;
using System.Collections; // ArrayList
using System.Runtime.InteropServices;
using System.Windows.Threading;
using System.Windows.Input;
using System.Windows.Controls; // ScrollChangedEventArgs
using System.Windows.Controls.Primitives; // CharacterCasing, TextBoxBase
using System.Windows.Media;
using System.Windows.Markup;
using MS.Utility;
using MS.Win32;
using MS.Internal.Documents;
using MS.Internal.Commands; // CommandHelpers
/// <summary>
/// Text editing service for controls.
/// </summary>
internal static class TextEditorCharacters
{
//------------------------------------------------------
//
// Class Internal Methods
//
//------------------------------------------------------
#region Class Internal Methods
// Registers all text editing command handlers for a given control type
internal static void _RegisterClassHandlers(Type controlType, bool registerEventListeners)
{
var onQueryStatusNYI = new CanExecuteRoutedEventHandler(OnQueryStatusNYI);
// Editing Commands: Character Editing
// -----------------------------------
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ResetFormat , new ExecutedRoutedEventHandler(OnResetFormat) , onQueryStatusNYI, SRID.KeyResetFormat, SRID.KeyResetFormatDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ToggleBold , new ExecutedRoutedEventHandler(OnToggleBold) , onQueryStatusNYI, SRID.KeyToggleBold, SRID.KeyToggleBoldDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ToggleItalic , new ExecutedRoutedEventHandler(OnToggleItalic) , onQueryStatusNYI, SRID.KeyToggleItalic, SRID.KeyToggleItalicDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ToggleUnderline , new ExecutedRoutedEventHandler(OnToggleUnderline) , onQueryStatusNYI, SRID.KeyToggleUnderline, SRID.KeyToggleUnderlineDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ToggleSubscript , new ExecutedRoutedEventHandler(OnToggleSubscript) , onQueryStatusNYI, SRID.KeyToggleSubscript, SRID.KeyToggleSubscriptDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ToggleSuperscript , new ExecutedRoutedEventHandler(OnToggleSuperscript) , onQueryStatusNYI, SRID.KeyToggleSuperscript, SRID.KeyToggleSuperscriptDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.IncreaseFontSize , new ExecutedRoutedEventHandler(OnIncreaseFontSize) , onQueryStatusNYI, SRID.KeyIncreaseFontSize, SRID.KeyIncreaseFontSizeDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.DecreaseFontSize , new ExecutedRoutedEventHandler(OnDecreaseFontSize) , onQueryStatusNYI, SRID.KeyDecreaseFontSize, SRID.KeyDecreaseFontSizeDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ApplyFontSize , new ExecutedRoutedEventHandler(OnApplyFontSize) , onQueryStatusNYI, SRID.KeyApplyFontSize, SRID.KeyApplyFontSizeDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ApplyFontFamily , new ExecutedRoutedEventHandler(OnApplyFontFamily) , onQueryStatusNYI, SRID.KeyApplyFontFamily, SRID.KeyApplyFontFamilyDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ApplyForeground , new ExecutedRoutedEventHandler(OnApplyForeground) , onQueryStatusNYI, SRID.KeyApplyForeground, SRID.KeyApplyForegroundDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ApplyBackground , new ExecutedRoutedEventHandler(OnApplyBackground) , onQueryStatusNYI, SRID.KeyApplyBackground, SRID.KeyApplyBackgroundDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ToggleSpellCheck , new ExecutedRoutedEventHandler(OnToggleSpellCheck) , onQueryStatusNYI, SRID.KeyToggleSpellCheck, SRID.KeyToggleSpellCheckDisplayString);
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ApplyInlineFlowDirectionRTL , new ExecutedRoutedEventHandler(OnApplyInlineFlowDirectionRTL), new CanExecuteRoutedEventHandler(OnQueryStatusNYI));
CommandHelpers.RegisterCommandHandler(controlType, EditingCommands.ApplyInlineFlowDirectionLTR , new ExecutedRoutedEventHandler(OnApplyInlineFlowDirectionLTR), new CanExecuteRoutedEventHandler(OnQueryStatusNYI));
}
// A common method for all formatting commands.
// Applies a property to current selection.
// Takes care of toggling operations (like bold/italic).
// Creates undo unit for this action.
internal static void _OnApplyProperty(TextEditor This, DependencyProperty formattingProperty, object propertyValue)
{
_OnApplyProperty(This, formattingProperty, propertyValue, /*applyToParagraphs*/false, PropertyValueAction.SetValue);
}
internal static void _OnApplyProperty(TextEditor This, DependencyProperty formattingProperty, object propertyValue, bool applyToParagraphs)
{
_OnApplyProperty(This, formattingProperty, propertyValue, applyToParagraphs, PropertyValueAction.SetValue);
}
internal static void _OnApplyProperty(TextEditor This, DependencyProperty formattingProperty, object propertyValue, bool applyToParagraphs, PropertyValueAction propertyValueAction)
{
if (This == null || !This._IsEnabled || This.IsReadOnly || !This.AcceptsRichContent || !(This.Selection is TextSelection))
{
return;
}
// Check whether the property is known
if (!TextSchema.IsParagraphProperty(formattingProperty) && !TextSchema.IsCharacterProperty(formattingProperty))
{
Invariant.Assert(false, "The property '" + formattingProperty.Name + "' is unknown to TextEditor");
return;
}
TextSelection selection = (TextSelection)This.Selection;
if (TextSchema.IsStructuralCharacterProperty(formattingProperty) &&
!TextRangeEdit.CanApplyStructuralInlineProperty(selection.Start, selection.End))
{
// Ignore structural commands fires in inappropriate context.
return;
}
TextEditorTyping._FlushPendingInputItems(This);
// Forget previously suggested horizontal position
TextEditorSelection._ClearSuggestedX(This);
// Break merged typing sequence
TextEditorTyping._BreakTypingSequence(This);
// Apply property
selection.ApplyPropertyValue(formattingProperty, propertyValue, applyToParagraphs, propertyValueAction);
}
#endregion Class Internal Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
// ................................................................
//
// Editing Commands: Character Editing
//
// ................................................................
private static void OnResetFormat(object target, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled || This.IsReadOnly || !This.AcceptsRichContent || !(This.Selection.Start is TextPointer))
{
return;
}
TextEditorTyping._FlushPendingInputItems(This);
using (This.Selection.DeclareChangeBlock())
{
// Positions to clear all inline formatting properties
TextPointer startResetFormatPosition = (TextPointer)This.Selection.Start;
TextPointer endResetFormatPosition = (TextPointer)This.Selection.End;
if (This.Selection.IsEmpty)
{
TextSegment autoWordRange = TextRangeBase.GetAutoWord(This.Selection);
if (autoWordRange.IsNull)
{
// Clear springloaded formatting
((TextSelection)This.Selection).ClearSpringloadFormatting();
return;
}
else
{
// If we have a word, apply reset format to it
startResetFormatPosition = (TextPointer)autoWordRange.Start;
endResetFormatPosition = (TextPointer)autoWordRange.End;
}
}
// Forget previously suggested horizontal position
TextEditorSelection._ClearSuggestedX(This);
// Clear all inline formattings
TextRangeEdit.CharacterResetFormatting(startResetFormatPosition, endResetFormatPosition);
}
}
/// <summary>
/// ToggleBold command event handler.
/// </summary>
private static void OnToggleBold(object target, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled || This.IsReadOnly || !This.AcceptsRichContent || !(This.Selection is TextSelection))
{
return;
}
TextEditorTyping._FlushPendingInputItems(This);
object propertyValue = ((TextSelection)This.Selection).GetCurrentValue(TextElement.FontWeightProperty);
FontWeight fontWeight = (propertyValue != DependencyProperty.UnsetValue && (FontWeight)propertyValue == FontWeights.Bold) ? FontWeights.Normal : FontWeights.Bold;
TextEditorCharacters._OnApplyProperty(This, TextElement.FontWeightProperty, fontWeight);
}
/// <summary>
/// ToggleItalic command event handler.
/// </summary>
private static void OnToggleItalic(object target, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled || This.IsReadOnly || !This.AcceptsRichContent || !(This.Selection is TextSelection))
{
return;
}
TextEditorTyping._FlushPendingInputItems(This);
object propertyValue = ((TextSelection)This.Selection).GetCurrentValue(TextElement.FontStyleProperty);
FontStyle fontStyle = (propertyValue != DependencyProperty.UnsetValue && (FontStyle)propertyValue == FontStyles.Italic) ? FontStyles.Normal : FontStyles.Italic;
TextEditorCharacters._OnApplyProperty(This, TextElement.FontStyleProperty, fontStyle);
// Update the caret to show it as italic or normal caret.
This.Selection.RefreshCaret();
}
/// <summary>
/// ToggleUnderline command event handler.
/// </summary>
private static void OnToggleUnderline(object target, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled || This.IsReadOnly || !This.AcceptsRichContent || !(This.Selection is TextSelection))
{
return;
}
TextEditorTyping._FlushPendingInputItems(This);
object propertyValue = ((TextSelection)This.Selection).GetCurrentValue(Inline.TextDecorationsProperty);
TextDecorationCollection textDecorations = propertyValue != DependencyProperty.UnsetValue ? (TextDecorationCollection)propertyValue : null;
if (!TextSchema.HasTextDecorations(textDecorations))
{
textDecorations = TextDecorations.Underline;
}
else
{
textDecorations = new TextDecorationCollection(); // empty collection - no underline
}
TextEditorCharacters._OnApplyProperty(This, Inline.TextDecorationsProperty, textDecorations);
}
// Command handler for Ctrl+"+" key (non-numpad)
private static void OnToggleSubscript(object sender, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(sender);
if (This == null || !This._IsEnabled || This.IsReadOnly || !This.AcceptsRichContent || !(This.Selection is TextSelection))
{
return;
}
TextEditorTyping._FlushPendingInputItems(This);
FontVariants fontVariants = (FontVariants)((TextSelection)This.Selection).GetCurrentValue(Typography.VariantsProperty);
fontVariants = fontVariants == FontVariants.Subscript ? FontVariants.Normal : FontVariants.Subscript;
TextEditorCharacters._OnApplyProperty(This, Typography.VariantsProperty, fontVariants);
}
// Command handler fro Ctrl+Shift+"+" (non-numpad)
private static void OnToggleSuperscript(object sender, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(sender);
if (This == null || !This._IsEnabled || This.IsReadOnly || !This.AcceptsRichContent || !(This.Selection is TextSelection))
{
return;
}
TextEditorTyping._FlushPendingInputItems(This);
FontVariants fontVariants = (FontVariants)((TextSelection)This.Selection).GetCurrentValue(Typography.VariantsProperty);
fontVariants = fontVariants == FontVariants.Superscript ? FontVariants.Normal : FontVariants.Superscript;
TextEditorCharacters._OnApplyProperty(This, Typography.VariantsProperty, fontVariants);
}
// Used in IncreaseFontSize and DecreaseFontSize commands
internal const double OneFontPoint = 72.0 / 96.0;
// The limiting constant is taken from Word UI - it suggests to choose font size from a range between 1 and 1638.
//
internal const double MaxFontPoint = 1638.0;
/// <summary>
/// IncreaseFontSize command event handler
/// </summary>
private static void OnIncreaseFontSize(object target, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled || This.IsReadOnly || !This.AcceptsRichContent || !(This.Selection is TextSelection))
{
return;
}
TextEditorTyping._FlushPendingInputItems(This);
if (This.Selection.IsEmpty)
{
// Springload an increased font size
double fontSize = (double)((TextSelection)This.Selection).GetCurrentValue(TextElement.FontSizeProperty);
if (fontSize == 0.0)
{
return; // no characters available for font operation
}
if (fontSize < TextEditorCharacters.MaxFontPoint)
{
fontSize += TextEditorCharacters.OneFontPoint;
if (fontSize > TextEditorCharacters.MaxFontPoint)
{
fontSize = TextEditorCharacters.MaxFontPoint;
}
// The limiting constant is taken from Word UI - it suggests to choose font size from a range between 1 and 1638.
TextEditorCharacters._OnApplyProperty(This, TextElement.FontSizeProperty, fontSize);
}
}
else
{
// Apply font size in incremental mode to a nonempty selection
TextEditorCharacters._OnApplyProperty(This, TextElement.FontSizeProperty, OneFontPoint, /*applyToParagraphs:*/false, PropertyValueAction.IncreaseByAbsoluteValue);
}
}
/// <summary>
/// DecreaseFontSize command event handler
/// </summary>
private static void OnDecreaseFontSize(object target, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled || This.IsReadOnly || !This.AcceptsRichContent || !(This.Selection is TextSelection))
{
return;
}
TextEditorTyping._FlushPendingInputItems(This);
if (This.Selection.IsEmpty)
{
// Springload a decreased font size
double fontSize = (double)((TextSelection)This.Selection).GetCurrentValue(TextElement.FontSizeProperty);
if (fontSize == 0.0)
{
return; // no characters available for font operation
}
if (fontSize > TextEditorCharacters.OneFontPoint)
{
fontSize -= TextEditorCharacters.OneFontPoint;
if (fontSize < TextEditorCharacters.OneFontPoint)
{
fontSize = TextEditorCharacters.OneFontPoint;
}
TextEditorCharacters._OnApplyProperty(This, TextElement.FontSizeProperty, fontSize);
}
}
else
{
// Apply font size in decremental mode to a nonempty selection
TextEditorCharacters._OnApplyProperty(This, TextElement.FontSizeProperty, OneFontPoint, /*applyToParagraphs:*/false, PropertyValueAction.DecreaseByAbsoluteValue);
}
}
/// <summary>
/// ApplyFontSize command event handler.
/// </summary>
private static void OnApplyFontSize(object target, ExecutedRoutedEventArgs args)
{
if (args.Parameter == null)
{
return; // Ignore the command if no argument provided
}
TextEditor This = TextEditor._GetTextEditor(target);
TextEditorCharacters._OnApplyProperty(This, TextElement.FontSizeProperty, args.Parameter);
}
/// <summary>
/// ApplyFontFamily command event handler.
/// </summary>
private static void OnApplyFontFamily(object target, ExecutedRoutedEventArgs args)
{
if (args.Parameter == null)
{
return; // Ignore the command if no argument provided
}
TextEditor This = TextEditor._GetTextEditor(target);
TextEditorCharacters._OnApplyProperty(This, TextElement.FontFamilyProperty, args.Parameter);
}
/// <summary>
/// ApplyForeground command event handler.
/// </summary>
private static void OnApplyForeground(object target, ExecutedRoutedEventArgs args)
{
if (args.Parameter == null)
{
return; // Ignore the command if no argument provided
}
TextEditor This = TextEditor._GetTextEditor(target);
TextEditorCharacters._OnApplyProperty(This, TextElement.ForegroundProperty, args.Parameter);
}
/// <summary>
/// ApplyBackground command event handler.
/// </summary>
private static void OnApplyBackground(object target, ExecutedRoutedEventArgs args)
{
if (args.Parameter == null)
{
return; // Ignore the command if no argument provided
}
TextEditor This = TextEditor._GetTextEditor(target);
TextEditorCharacters._OnApplyProperty(This, TextElement.BackgroundProperty, args.Parameter);
}
/// <summary>
/// ToggleSpellCheck command event handler.
/// </summary>
private static void OnToggleSpellCheck(object target, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null || !This._IsEnabled || This.IsReadOnly)
{
return;
}
This.IsSpellCheckEnabled = !This.IsSpellCheckEnabled;
}
/// <summary>
/// ApplyInlineFlowDirectionRTL command event handler.
/// </summary>
private static void OnApplyInlineFlowDirectionRTL(object target, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
TextEditorCharacters._OnApplyProperty(This, Inline.FlowDirectionProperty, FlowDirection.RightToLeft);
}
/// <summary>
/// ApplyInlineFlowDirectionLTR command event handler.
/// </summary>
private static void OnApplyInlineFlowDirectionLTR(object target, ExecutedRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
TextEditorCharacters._OnApplyProperty(This, Inline.FlowDirectionProperty, FlowDirection.LeftToRight);
}
// ----------------------------------------------------------
//
// Misceleneous Commands
//
// ----------------------------------------------------------
#region Misceleneous Commands
/// <summary>
/// StartInputCorrection command QueryStatus handler
/// </summary>
private static void OnQueryStatusNYI(object target, CanExecuteRoutedEventArgs args)
{
TextEditor This = TextEditor._GetTextEditor(target);
if (This == null)
{
return;
}
args.CanExecute = true;
}
#endregion Misceleneous Commands
#endregion Private Methods
}
}
| |
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Util;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using IBits = Lucene.Net.Util.IBits;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
/// <summary>
/// A query that generates the union of documents produced by its subqueries, and that scores each document with the maximum
/// score for that document as produced by any subquery, plus a tie breaking increment for any additional matching subqueries.
/// This is useful when searching for a word in multiple fields with different boost factors (so that the fields cannot be
/// combined equivalently into a single search field). We want the primary score to be the one associated with the highest boost,
/// not the sum of the field scores (as <see cref="BooleanQuery"/> would give).
/// <para/>
/// If the query is "albino elephant" this ensures that "albino" matching one field and "elephant" matching
/// another gets a higher score than "albino" matching both fields.
/// <para/>
/// To get this result, use both <see cref="BooleanQuery"/> and <see cref="DisjunctionMaxQuery"/>: for each term a <see cref="DisjunctionMaxQuery"/> searches for it in
/// each field, while the set of these <see cref="DisjunctionMaxQuery"/>'s is combined into a <see cref="BooleanQuery"/>.
/// The tie breaker capability allows results that include the same term in multiple fields to be judged better than results that
/// include this term in only the best of those multiple fields, without confusing this with the better case of two different terms
/// in the multiple fields.
/// <para/>
/// Collection initializer note: To create and populate a <see cref="DisjunctionMaxQuery"/>
/// in a single statement, you can use the following example as a guide:
///
/// <code>
/// var disjunctionMaxQuery = new DisjunctionMaxQuery(0.1f) {
/// new TermQuery(new Term("field1", "albino")),
/// new TermQuery(new Term("field2", "elephant"))
/// };
/// </code>
/// </summary>
public class DisjunctionMaxQuery : Query, IEnumerable<Query>
{
/// <summary>
/// The subqueries
/// </summary>
private IList<Query> disjuncts = new JCG.List<Query>();
/// <summary>
/// Multiple of the non-max disjunct scores added into our final score. Non-zero values support tie-breaking.
/// </summary>
private readonly float tieBreakerMultiplier = 0.0f;
/// <summary>
/// Creates a new empty <see cref="DisjunctionMaxQuery"/>. Use <see cref="Add(Query)"/> to add the subqueries. </summary>
/// <param name="tieBreakerMultiplier"> The score of each non-maximum disjunct for a document is multiplied by this weight
/// and added into the final score. If non-zero, the value should be small, on the order of 0.1, which says that
/// 10 occurrences of word in a lower-scored field that is also in a higher scored field is just as good as a unique
/// word in the lower scored field (i.e., one that is not in any higher scored field). </param>
public DisjunctionMaxQuery(float tieBreakerMultiplier)
{
this.tieBreakerMultiplier = tieBreakerMultiplier;
}
/// <summary>
/// Creates a new <see cref="DisjunctionMaxQuery"/> </summary>
/// <param name="disjuncts"> A <see cref="T:ICollection{Query}"/> of all the disjuncts to add </param>
/// <param name="tieBreakerMultiplier"> The weight to give to each matching non-maximum disjunct </param>
public DisjunctionMaxQuery(ICollection<Query> disjuncts, float tieBreakerMultiplier)
{
this.tieBreakerMultiplier = tieBreakerMultiplier;
Add(disjuncts);
}
/// <summary>
/// Add a subquery to this disjunction </summary>
/// <param name="query"> The disjunct added </param>
public virtual void Add(Query query)
{
disjuncts.Add(query);
}
/// <summary>
/// Add a collection of disjuncts to this disjunction
/// via <see cref="T:IEnumerable{Query}"/> </summary>
/// <param name="disjuncts"> A collection of queries to add as disjuncts. </param>
public virtual void Add(ICollection<Query> disjuncts)
{
this.disjuncts.AddRange(disjuncts);
}
/// <returns> An <see cref="T:IEnumerator{Query}"/> over the disjuncts </returns>
public virtual IEnumerator<Query> GetEnumerator()
{
return disjuncts.GetEnumerator();
}
// LUCENENET specific
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <returns> The disjuncts. </returns>
public virtual IList<Query> Disjuncts => disjuncts;
/// <returns> Tie breaker value for multiple matches. </returns>
public virtual float TieBreakerMultiplier => tieBreakerMultiplier;
/// <summary>
/// Expert: the Weight for DisjunctionMaxQuery, used to
/// normalize, score and explain these queries.
///
/// <para>NOTE: this API and implementation is subject to
/// change suddenly in the next release.</para>
/// </summary>
protected class DisjunctionMaxWeight : Weight
{
private readonly DisjunctionMaxQuery outerInstance;
/// <summary>
/// The <see cref="Weight"/>s for our subqueries, in 1-1 correspondence with disjuncts </summary>
protected List<Weight> m_weights = new List<Weight>(); // The Weight's for our subqueries, in 1-1 correspondence with disjuncts
/// <summary>
/// Construct the <see cref="Weight"/> for this <see cref="Search.Query"/> searched by <paramref name="searcher"/>. Recursively construct subquery weights. </summary>
public DisjunctionMaxWeight(DisjunctionMaxQuery outerInstance, IndexSearcher searcher)
{
this.outerInstance = outerInstance;
foreach (Query disjunctQuery in outerInstance.disjuncts)
{
m_weights.Add(disjunctQuery.CreateWeight(searcher));
}
}
/// <summary>
/// Return our associated <see cref="DisjunctionMaxQuery"/> </summary>
public override Query Query => outerInstance;
/// <summary>
/// Compute the sub of squared weights of us applied to our subqueries. Used for normalization. </summary>
public override float GetValueForNormalization()
{
float max = 0.0f, sum = 0.0f;
foreach (Weight currentWeight in m_weights)
{
float sub = currentWeight.GetValueForNormalization();
sum += sub;
max = Math.Max(max, sub);
}
float boost = outerInstance.Boost;
return (((sum - max) * outerInstance.tieBreakerMultiplier * outerInstance.tieBreakerMultiplier) + max) * boost * boost;
}
/// <summary>
/// Apply the computed normalization factor to our subqueries </summary>
public override void Normalize(float norm, float topLevelBoost)
{
topLevelBoost *= outerInstance.Boost; // Incorporate our boost
foreach (Weight wt in m_weights)
{
wt.Normalize(norm, topLevelBoost);
}
}
/// <summary>
/// Create the scorer used to score our associated <see cref="DisjunctionMaxQuery"/> </summary>
public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs)
{
IList<Scorer> scorers = new List<Scorer>();
foreach (Weight w in m_weights)
{
// we will advance() subscorers
Scorer subScorer = w.GetScorer(context, acceptDocs);
if (subScorer != null)
{
scorers.Add(subScorer);
}
}
if (scorers.Count == 0)
{
// no sub-scorers had any documents
return null;
}
DisjunctionMaxScorer result = new DisjunctionMaxScorer(this, outerInstance.tieBreakerMultiplier, scorers.ToArray());
return result;
}
/// <summary>
/// Explain the score we computed for doc </summary>
public override Explanation Explain(AtomicReaderContext context, int doc)
{
if (outerInstance.disjuncts.Count == 1)
{
return m_weights[0].Explain(context, doc);
}
ComplexExplanation result = new ComplexExplanation();
float max = 0.0f, sum = 0.0f;
result.Description = outerInstance.tieBreakerMultiplier == 0.0f ? "max of:" : "max plus " + outerInstance.tieBreakerMultiplier + " times others of:";
foreach (Weight wt in m_weights)
{
Explanation e = wt.Explain(context, doc);
if (e.IsMatch)
{
result.Match = true;
result.AddDetail(e);
sum += e.Value;
max = Math.Max(max, e.Value);
}
}
result.Value = max + (sum - max) * outerInstance.tieBreakerMultiplier;
return result;
}
} // end of DisjunctionMaxWeight inner class
/// <summary>
/// Create the <see cref="Weight"/> used to score us </summary>
public override Weight CreateWeight(IndexSearcher searcher)
{
return new DisjunctionMaxWeight(this, searcher);
}
/// <summary>
/// Optimize our representation and our subqueries representations </summary>
/// <param name="reader"> The <see cref="IndexReader"/> we query </param>
/// <returns> An optimized copy of us (which may not be a copy if there is nothing to optimize) </returns>
public override Query Rewrite(IndexReader reader)
{
int numDisjunctions = disjuncts.Count;
if (numDisjunctions == 1)
{
Query singleton = disjuncts[0];
Query result = singleton.Rewrite(reader);
if (Boost != 1.0f)
{
if (result == singleton)
{
result = (Query)result.Clone();
}
result.Boost = Boost * result.Boost;
}
return result;
}
DisjunctionMaxQuery clone = null;
for (int i = 0; i < numDisjunctions; i++)
{
Query clause = disjuncts[i];
Query rewrite = clause.Rewrite(reader);
if (rewrite != clause)
{
if (clone == null)
{
clone = (DisjunctionMaxQuery)this.Clone();
}
clone.disjuncts[i] = rewrite;
}
}
if (clone != null)
{
return clone;
}
else
{
return this;
}
}
/// <summary>
/// Create a shallow copy of us -- used in rewriting if necessary </summary>
/// <returns> A copy of us (but reuse, don't copy, our subqueries) </returns>
public override object Clone()
{
DisjunctionMaxQuery clone = (DisjunctionMaxQuery)base.Clone();
clone.disjuncts = new JCG.List<Query>(this.disjuncts);
return clone;
}
/// <summary>
/// Expert: adds all terms occurring in this query to the terms set. Only
/// works if this query is in its rewritten (<see cref="Rewrite(IndexReader)"/>) form.
/// </summary>
/// <exception cref="InvalidOperationException"> If this query is not yet rewritten </exception>
public override void ExtractTerms(ISet<Term> terms)
{
foreach (Query query in disjuncts)
{
query.ExtractTerms(terms);
}
}
/// <summary>
/// Prettyprint us. </summary>
/// <param name="field"> The field to which we are applied </param>
/// <returns> A string that shows what we do, of the form "(disjunct1 | disjunct2 | ... | disjunctn)^boost" </returns>
public override string ToString(string field)
{
StringBuilder buffer = new StringBuilder();
buffer.Append("(");
int numDisjunctions = disjuncts.Count;
for (int i = 0; i < numDisjunctions; i++)
{
Query subquery = disjuncts[i];
if (subquery is BooleanQuery) // wrap sub-bools in parens
{
buffer.Append("(");
buffer.Append(subquery.ToString(field));
buffer.Append(")");
}
else
{
buffer.Append(subquery.ToString(field));
}
if (i != numDisjunctions - 1)
{
buffer.Append(" | ");
}
}
buffer.Append(")");
if (tieBreakerMultiplier != 0.0f)
{
buffer.Append("~");
buffer.Append(tieBreakerMultiplier);
}
if (Boost != 1.0)
{
buffer.Append("^");
buffer.Append(Boost);
}
return buffer.ToString();
}
/// <summary>
/// Return <c>true</c> if we represent the same query as <paramref name="o"/> </summary>
/// <param name="o"> Another object </param>
/// <returns> <c>true</c> if <paramref name="o"/> is a <see cref="DisjunctionMaxQuery"/> with the same boost and the same subqueries, in the same order, as us </returns>
public override bool Equals(object o)
{
if (!(o is DisjunctionMaxQuery))
{
return false;
}
DisjunctionMaxQuery other = (DisjunctionMaxQuery)o;
return this.Boost == other.Boost
&& this.tieBreakerMultiplier == other.tieBreakerMultiplier
&& this.disjuncts.Equals(other.disjuncts);
}
/// <summary>
/// Compute a hash code for hashing us </summary>
/// <returns> the hash code </returns>
public override int GetHashCode()
{
return J2N.BitConversion.SingleToInt32Bits(Boost)
+ J2N.BitConversion.SingleToInt32Bits(tieBreakerMultiplier)
+ disjuncts.GetHashCode();
}
}
}
| |
// 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.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyFile
{
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 Models;
/// <summary>
/// Files operations.
/// </summary>
public partial class Files : IServiceOperations<AutoRestSwaggerBATFileService>, IFiles
{
/// <summary>
/// Initializes a new instance of the Files class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Files(AutoRestSwaggerBATFileService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestSwaggerBATFileService
/// </summary>
public AutoRestSwaggerBATFileService Client { get; private set; }
/// <summary>
/// Get file
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<System.IO.Stream>> GetFileWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetFile", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/nonempty").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.IO.Stream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get empty file
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<System.IO.Stream>> GetEmptyFileWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetEmptyFile", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "files/stream/empty").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
string _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = _httpRequest;
ex.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.IO.Stream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if !PORTABLE40
#if !(PORTABLE || NET20 || NET35)
using System.Numerics;
#endif
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
#if !(NET20 || PORTABLE40)
using System.Xml.Linq;
#endif
using Newtonsoft.Json.Utilities;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Converters
{
#region XmlNodeWrappers
#if !NETFX_CORE && !PORTABLE && !PORTABLE40
internal class XmlDocumentWrapper : XmlNodeWrapper, IXmlDocument
{
private readonly XmlDocument _document;
public XmlDocumentWrapper(XmlDocument document)
: base(document)
{
_document = document;
}
public IXmlNode CreateComment(string data)
{
return new XmlNodeWrapper(_document.CreateComment(data));
}
public IXmlNode CreateTextNode(string text)
{
return new XmlNodeWrapper(_document.CreateTextNode(text));
}
public IXmlNode CreateCDataSection(string data)
{
return new XmlNodeWrapper(_document.CreateCDataSection(data));
}
public IXmlNode CreateWhitespace(string text)
{
return new XmlNodeWrapper(_document.CreateWhitespace(text));
}
public IXmlNode CreateSignificantWhitespace(string text)
{
return new XmlNodeWrapper(_document.CreateSignificantWhitespace(text));
}
public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone)
{
return new XmlDeclarationWrapper(_document.CreateXmlDeclaration(version, encoding, standalone));
}
public IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset)
{
return new XmlDocumentTypeWrapper(_document.CreateDocumentType(name, publicId, systemId, null));
}
public IXmlNode CreateProcessingInstruction(string target, string data)
{
return new XmlNodeWrapper(_document.CreateProcessingInstruction(target, data));
}
public IXmlElement CreateElement(string elementName)
{
return new XmlElementWrapper(_document.CreateElement(elementName));
}
public IXmlElement CreateElement(string qualifiedName, string namespaceUri)
{
return new XmlElementWrapper(_document.CreateElement(qualifiedName, namespaceUri));
}
public IXmlNode CreateAttribute(string name, string value)
{
XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(name));
attribute.Value = value;
return attribute;
}
public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value)
{
XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(qualifiedName, namespaceUri));
attribute.Value = value;
return attribute;
}
public IXmlElement DocumentElement
{
get
{
if (_document.DocumentElement == null)
return null;
return new XmlElementWrapper(_document.DocumentElement);
}
}
}
internal class XmlElementWrapper : XmlNodeWrapper, IXmlElement
{
private readonly XmlElement _element;
public XmlElementWrapper(XmlElement element)
: base(element)
{
_element = element;
}
public void SetAttributeNode(IXmlNode attribute)
{
XmlNodeWrapper xmlAttributeWrapper = (XmlNodeWrapper)attribute;
_element.SetAttributeNode((XmlAttribute)xmlAttributeWrapper.WrappedNode);
}
public string GetPrefixOfNamespace(string namespaceUri)
{
return _element.GetPrefixOfNamespace(namespaceUri);
}
public bool IsEmpty
{
get { return _element.IsEmpty; }
}
}
internal class XmlDeclarationWrapper : XmlNodeWrapper, IXmlDeclaration
{
private readonly XmlDeclaration _declaration;
public XmlDeclarationWrapper(XmlDeclaration declaration)
: base(declaration)
{
_declaration = declaration;
}
public string Version
{
get { return _declaration.Version; }
}
public string Encoding
{
get { return _declaration.Encoding; }
set { _declaration.Encoding = value; }
}
public string Standalone
{
get { return _declaration.Standalone; }
set { _declaration.Standalone = value; }
}
}
internal class XmlDocumentTypeWrapper : XmlNodeWrapper, IXmlDocumentType
{
private readonly XmlDocumentType _documentType;
public XmlDocumentTypeWrapper(XmlDocumentType documentType)
: base(documentType)
{
_documentType = documentType;
}
public string Name
{
get { return _documentType.Name; }
}
public string System
{
get { return _documentType.SystemId; }
}
public string Public
{
get { return _documentType.PublicId; }
}
public string InternalSubset
{
get { return _documentType.InternalSubset; }
}
public override string LocalName
{
get { return "DOCTYPE"; }
}
}
internal class XmlNodeWrapper : IXmlNode
{
private readonly XmlNode _node;
private IList<IXmlNode> _childNodes;
public XmlNodeWrapper(XmlNode node)
{
_node = node;
}
public object WrappedNode
{
get { return _node; }
}
public XmlNodeType NodeType
{
get { return _node.NodeType; }
}
public virtual string LocalName
{
get { return _node.LocalName; }
}
public IList<IXmlNode> ChildNodes
{
get
{
// childnodes is read multiple times
// cache results to prevent multiple reads which kills perf in large documents
if (_childNodes == null)
_childNodes = _node.ChildNodes.Cast<XmlNode>().Select(WrapNode).ToList();
return _childNodes;
}
}
internal static IXmlNode WrapNode(XmlNode node)
{
switch (node.NodeType)
{
case XmlNodeType.Element:
return new XmlElementWrapper((XmlElement) node);
case XmlNodeType.XmlDeclaration:
return new XmlDeclarationWrapper((XmlDeclaration) node);
case XmlNodeType.DocumentType:
return new XmlDocumentTypeWrapper((XmlDocumentType) node);
default:
return new XmlNodeWrapper(node);
}
}
public IList<IXmlNode> Attributes
{
get
{
if (_node.Attributes == null)
return null;
return _node.Attributes.Cast<XmlAttribute>().Select(WrapNode).ToList();
}
}
public IXmlNode ParentNode
{
get
{
XmlNode node = (_node is XmlAttribute)
? ((XmlAttribute) _node).OwnerElement
: _node.ParentNode;
if (node == null)
return null;
return WrapNode(node);
}
}
public string Value
{
get { return _node.Value; }
set { _node.Value = value; }
}
public IXmlNode AppendChild(IXmlNode newChild)
{
XmlNodeWrapper xmlNodeWrapper = (XmlNodeWrapper) newChild;
_node.AppendChild(xmlNodeWrapper._node);
_childNodes = null;
return newChild;
}
public string NamespaceUri
{
get { return _node.NamespaceURI; }
}
}
#endif
#endregion
#region Interfaces
internal interface IXmlDocument : IXmlNode
{
IXmlNode CreateComment(string text);
IXmlNode CreateTextNode(string text);
IXmlNode CreateCDataSection(string data);
IXmlNode CreateWhitespace(string text);
IXmlNode CreateSignificantWhitespace(string text);
IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone);
IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset);
IXmlNode CreateProcessingInstruction(string target, string data);
IXmlElement CreateElement(string elementName);
IXmlElement CreateElement(string qualifiedName, string namespaceUri);
IXmlNode CreateAttribute(string name, string value);
IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value);
IXmlElement DocumentElement { get; }
}
internal interface IXmlDeclaration : IXmlNode
{
string Version { get; }
string Encoding { get; set; }
string Standalone { get; set; }
}
internal interface IXmlDocumentType : IXmlNode
{
string Name { get; }
string System { get; }
string Public { get; }
string InternalSubset { get; }
}
internal interface IXmlElement : IXmlNode
{
void SetAttributeNode(IXmlNode attribute);
string GetPrefixOfNamespace(string namespaceUri);
bool IsEmpty { get; }
}
internal interface IXmlNode
{
XmlNodeType NodeType { get; }
string LocalName { get; }
IList<IXmlNode> ChildNodes { get; }
IList<IXmlNode> Attributes { get; }
IXmlNode ParentNode { get; }
string Value { get; set; }
IXmlNode AppendChild(IXmlNode newChild);
string NamespaceUri { get; }
object WrappedNode { get; }
}
#endregion
#region XNodeWrappers
#if !NET20
internal class XDeclarationWrapper : XObjectWrapper, IXmlDeclaration
{
internal XDeclaration Declaration { get; private set; }
public XDeclarationWrapper(XDeclaration declaration)
: base(null)
{
Declaration = declaration;
}
public override XmlNodeType NodeType
{
get { return XmlNodeType.XmlDeclaration; }
}
public string Version
{
get { return Declaration.Version; }
}
public string Encoding
{
get { return Declaration.Encoding; }
set { Declaration.Encoding = value; }
}
public string Standalone
{
get { return Declaration.Standalone; }
set { Declaration.Standalone = value; }
}
}
internal class XDocumentTypeWrapper : XObjectWrapper, IXmlDocumentType
{
private readonly XDocumentType _documentType;
public XDocumentTypeWrapper(XDocumentType documentType)
: base(documentType)
{
_documentType = documentType;
}
public string Name
{
get { return _documentType.Name; }
}
public string System
{
get { return _documentType.SystemId; }
}
public string Public
{
get { return _documentType.PublicId; }
}
public string InternalSubset
{
get { return _documentType.InternalSubset; }
}
public override string LocalName
{
get { return "DOCTYPE"; }
}
}
internal class XDocumentWrapper : XContainerWrapper, IXmlDocument
{
private XDocument Document
{
get { return (XDocument)WrappedNode; }
}
public XDocumentWrapper(XDocument document)
: base(document)
{
}
public override IList<IXmlNode> ChildNodes
{
get
{
IList<IXmlNode> childNodes = base.ChildNodes;
if (Document.Declaration != null && childNodes[0].NodeType != XmlNodeType.XmlDeclaration)
childNodes.Insert(0, new XDeclarationWrapper(Document.Declaration));
return childNodes;
}
}
public IXmlNode CreateComment(string text)
{
return new XObjectWrapper(new XComment(text));
}
public IXmlNode CreateTextNode(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateCDataSection(string data)
{
return new XObjectWrapper(new XCData(data));
}
public IXmlNode CreateWhitespace(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateSignificantWhitespace(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone)
{
return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone));
}
public IXmlNode CreateXmlDocumentType(string name, string publicId, string systemId, string internalSubset)
{
return new XDocumentTypeWrapper(new XDocumentType(name, publicId, systemId, internalSubset));
}
public IXmlNode CreateProcessingInstruction(string target, string data)
{
return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data));
}
public IXmlElement CreateElement(string elementName)
{
return new XElementWrapper(new XElement(elementName));
}
public IXmlElement CreateElement(string qualifiedName, string namespaceUri)
{
string localName = MiscellaneousUtils.GetLocalName(qualifiedName);
return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri)));
}
public IXmlNode CreateAttribute(string name, string value)
{
return new XAttributeWrapper(new XAttribute(name, value));
}
public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value)
{
string localName = MiscellaneousUtils.GetLocalName(qualifiedName);
return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value));
}
public IXmlElement DocumentElement
{
get
{
if (Document.Root == null)
return null;
return new XElementWrapper(Document.Root);
}
}
public override IXmlNode AppendChild(IXmlNode newChild)
{
XDeclarationWrapper declarationWrapper = newChild as XDeclarationWrapper;
if (declarationWrapper != null)
{
Document.Declaration = declarationWrapper.Declaration;
return declarationWrapper;
}
else
{
return base.AppendChild(newChild);
}
}
}
internal class XTextWrapper : XObjectWrapper
{
private XText Text
{
get { return (XText)WrappedNode; }
}
public XTextWrapper(XText text)
: base(text)
{
}
public override string Value
{
get { return Text.Value; }
set { Text.Value = value; }
}
public override IXmlNode ParentNode
{
get
{
if (Text.Parent == null)
return null;
return XContainerWrapper.WrapNode(Text.Parent);
}
}
}
internal class XCommentWrapper : XObjectWrapper
{
private XComment Text
{
get { return (XComment)WrappedNode; }
}
public XCommentWrapper(XComment text)
: base(text)
{
}
public override string Value
{
get { return Text.Value; }
set { Text.Value = value; }
}
public override IXmlNode ParentNode
{
get
{
if (Text.Parent == null)
return null;
return XContainerWrapper.WrapNode(Text.Parent);
}
}
}
internal class XProcessingInstructionWrapper : XObjectWrapper
{
private XProcessingInstruction ProcessingInstruction
{
get { return (XProcessingInstruction)WrappedNode; }
}
public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction)
: base(processingInstruction)
{
}
public override string LocalName
{
get { return ProcessingInstruction.Target; }
}
public override string Value
{
get { return ProcessingInstruction.Data; }
set { ProcessingInstruction.Data = value; }
}
}
internal class XContainerWrapper : XObjectWrapper
{
private IList<IXmlNode> _childNodes;
private XContainer Container
{
get { return (XContainer)WrappedNode; }
}
public XContainerWrapper(XContainer container)
: base(container)
{
}
public override IList<IXmlNode> ChildNodes
{
get
{
// childnodes is read multiple times
// cache results to prevent multiple reads which kills perf in large documents
if (_childNodes == null)
_childNodes = Container.Nodes().Select(WrapNode).ToList();
return _childNodes;
}
}
public override IXmlNode ParentNode
{
get
{
if (Container.Parent == null)
return null;
return WrapNode(Container.Parent);
}
}
internal static IXmlNode WrapNode(XObject node)
{
if (node is XDocument)
return new XDocumentWrapper((XDocument)node);
else if (node is XElement)
return new XElementWrapper((XElement)node);
else if (node is XContainer)
return new XContainerWrapper((XContainer)node);
else if (node is XProcessingInstruction)
return new XProcessingInstructionWrapper((XProcessingInstruction)node);
else if (node is XText)
return new XTextWrapper((XText)node);
else if (node is XComment)
return new XCommentWrapper((XComment)node);
else if (node is XAttribute)
return new XAttributeWrapper((XAttribute)node);
else if (node is XDocumentType)
return new XDocumentTypeWrapper((XDocumentType)node);
else
return new XObjectWrapper(node);
}
public override IXmlNode AppendChild(IXmlNode newChild)
{
Container.Add(newChild.WrappedNode);
_childNodes = null;
return newChild;
}
}
internal class XObjectWrapper : IXmlNode
{
private readonly XObject _xmlObject;
public XObjectWrapper(XObject xmlObject)
{
_xmlObject = xmlObject;
}
public object WrappedNode
{
get { return _xmlObject; }
}
public virtual XmlNodeType NodeType
{
get { return _xmlObject.NodeType; }
}
public virtual string LocalName
{
get { return null; }
}
public virtual IList<IXmlNode> ChildNodes
{
get { return new List<IXmlNode>(); }
}
public virtual IList<IXmlNode> Attributes
{
get { return null; }
}
public virtual IXmlNode ParentNode
{
get { return null; }
}
public virtual string Value
{
get { return null; }
set { throw new InvalidOperationException(); }
}
public virtual IXmlNode AppendChild(IXmlNode newChild)
{
throw new InvalidOperationException();
}
public virtual string NamespaceUri
{
get { return null; }
}
}
internal class XAttributeWrapper : XObjectWrapper
{
private XAttribute Attribute
{
get { return (XAttribute)WrappedNode; }
}
public XAttributeWrapper(XAttribute attribute)
: base(attribute)
{
}
public override string Value
{
get { return Attribute.Value; }
set { Attribute.Value = value; }
}
public override string LocalName
{
get { return Attribute.Name.LocalName; }
}
public override string NamespaceUri
{
get { return Attribute.Name.NamespaceName; }
}
public override IXmlNode ParentNode
{
get
{
if (Attribute.Parent == null)
return null;
return XContainerWrapper.WrapNode(Attribute.Parent);
}
}
}
internal class XElementWrapper : XContainerWrapper, IXmlElement
{
private XElement Element
{
get { return (XElement)WrappedNode; }
}
public XElementWrapper(XElement element)
: base(element)
{
}
public void SetAttributeNode(IXmlNode attribute)
{
XObjectWrapper wrapper = (XObjectWrapper)attribute;
Element.Add(wrapper.WrappedNode);
}
public override IList<IXmlNode> Attributes
{
get { return Element.Attributes().Select(a => new XAttributeWrapper(a)).Cast<IXmlNode>().ToList(); }
}
public override string Value
{
get { return Element.Value; }
set { Element.Value = value; }
}
public override string LocalName
{
get { return Element.Name.LocalName; }
}
public override string NamespaceUri
{
get { return Element.Name.NamespaceName; }
}
public string GetPrefixOfNamespace(string namespaceUri)
{
return Element.GetPrefixOfNamespace(namespaceUri);
}
public bool IsEmpty
{
get { return Element.IsEmpty; }
}
}
#endif
#endregion
/// <summary>
/// Converts XML to and from JSON.
/// </summary>
public class XmlNodeConverter : JsonConverter
{
private const string TextName = "#text";
private const string CommentName = "#comment";
private const string CDataName = "#cdata-section";
private const string WhitespaceName = "#whitespace";
private const string SignificantWhitespaceName = "#significant-whitespace";
private const string DeclarationName = "?xml";
private const string JsonNamespaceUri = "http://james.newtonking.com/projects/json";
/// <summary>
/// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produces multiple root elements.
/// </summary>
/// <value>The name of the deserialize root element.</value>
public string DeserializeRootElementName { get; set; }
/// <summary>
/// Gets or sets a flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </summary>
/// <value><c>true</c> if the array attibute is written to the XML; otherwise, <c>false</c>.</value>
public bool WriteArrayAttribute { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to write the root JSON object.
/// </summary>
/// <value><c>true</c> if the JSON root object is omitted; otherwise, <c>false</c>.</value>
public bool OmitRootObject { get; set; }
#region Writing
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="serializer">The calling serializer.</param>
/// <param name="value">The value.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
IXmlNode node = WrapXml(value);
XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
PushParentNamespaces(node, manager);
if (!OmitRootObject)
writer.WriteStartObject();
SerializeNode(writer, node, manager, !OmitRootObject);
if (!OmitRootObject)
writer.WriteEndObject();
}
private IXmlNode WrapXml(object value)
{
#if !NET20
if (value is XObject)
return XContainerWrapper.WrapNode((XObject)value);
#endif
#if !(NETFX_CORE || PORTABLE)
if (value is XmlNode)
return XmlNodeWrapper.WrapNode((XmlNode)value);
#endif
throw new ArgumentException("Value must be an XML object.", "value");
}
private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager)
{
List<IXmlNode> parentElements = null;
IXmlNode parent = node;
while ((parent = parent.ParentNode) != null)
{
if (parent.NodeType == XmlNodeType.Element)
{
if (parentElements == null)
parentElements = new List<IXmlNode>();
parentElements.Add(parent);
}
}
if (parentElements != null)
{
parentElements.Reverse();
foreach (IXmlNode parentElement in parentElements)
{
manager.PushScope();
foreach (IXmlNode attribute in parentElement.Attributes)
{
if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns")
manager.AddNamespace(attribute.LocalName, attribute.Value);
}
}
}
}
private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager)
{
string prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/"))
? null
: manager.LookupPrefix(node.NamespaceUri);
if (!string.IsNullOrEmpty(prefix))
return prefix + ":" + node.LocalName;
else
return node.LocalName;
}
private string GetPropertyName(IXmlNode node, XmlNamespaceManager manager)
{
switch (node.NodeType)
{
case XmlNodeType.Attribute:
if (node.NamespaceUri == JsonNamespaceUri)
return "$" + node.LocalName;
else
return "@" + ResolveFullName(node, manager);
case XmlNodeType.CDATA:
return CDataName;
case XmlNodeType.Comment:
return CommentName;
case XmlNodeType.Element:
return ResolveFullName(node, manager);
case XmlNodeType.ProcessingInstruction:
return "?" + ResolveFullName(node, manager);
case XmlNodeType.DocumentType:
return "!" + ResolveFullName(node, manager);
case XmlNodeType.XmlDeclaration:
return DeclarationName;
case XmlNodeType.SignificantWhitespace:
return SignificantWhitespaceName;
case XmlNodeType.Text:
return TextName;
case XmlNodeType.Whitespace:
return WhitespaceName;
default:
throw new JsonSerializationException("Unexpected XmlNodeType when getting node name: " + node.NodeType);
}
}
private bool IsArray(IXmlNode node)
{
IXmlNode jsonArrayAttribute = (node.Attributes != null)
? node.Attributes.SingleOrDefault(a => a.LocalName == "Array" && a.NamespaceUri == JsonNamespaceUri)
: null;
return (jsonArrayAttribute != null && XmlConvert.ToBoolean(jsonArrayAttribute.Value));
}
private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName)
{
// group nodes together by name
Dictionary<string, List<IXmlNode>> nodesGroupedByName = new Dictionary<string, List<IXmlNode>>();
for (int i = 0; i < node.ChildNodes.Count; i++)
{
IXmlNode childNode = node.ChildNodes[i];
string nodeName = GetPropertyName(childNode, manager);
List<IXmlNode> nodes;
if (!nodesGroupedByName.TryGetValue(nodeName, out nodes))
{
nodes = new List<IXmlNode>();
nodesGroupedByName.Add(nodeName, nodes);
}
nodes.Add(childNode);
}
// loop through grouped nodes. write single name instances as normal,
// write multiple names together in an array
foreach (KeyValuePair<string, List<IXmlNode>> nodeNameGroup in nodesGroupedByName)
{
List<IXmlNode> groupedNodes = nodeNameGroup.Value;
bool writeArray;
if (groupedNodes.Count == 1)
{
writeArray = IsArray(groupedNodes[0]);
}
else
{
writeArray = true;
}
if (!writeArray)
{
SerializeNode(writer, groupedNodes[0], manager, writePropertyName);
}
else
{
string elementNames = nodeNameGroup.Key;
if (writePropertyName)
writer.WritePropertyName(elementNames);
writer.WriteStartArray();
for (int i = 0; i < groupedNodes.Count; i++)
{
SerializeNode(writer, groupedNodes[i], manager, false);
}
writer.WriteEndArray();
}
}
}
private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName)
{
switch (node.NodeType)
{
case XmlNodeType.Document:
case XmlNodeType.DocumentFragment:
SerializeGroupedNodes(writer, node, manager, writePropertyName);
break;
case XmlNodeType.Element:
if (IsArray(node) && node.ChildNodes.All(n => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0)
{
SerializeGroupedNodes(writer, node, manager, false);
}
else
{
manager.PushScope();
foreach (IXmlNode attribute in node.Attributes)
{
if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/")
{
string namespacePrefix = (attribute.LocalName != "xmlns")
? attribute.LocalName
: string.Empty;
string namespaceUri = attribute.Value;
manager.AddNamespace(namespacePrefix, namespaceUri);
}
}
if (writePropertyName)
writer.WritePropertyName(GetPropertyName(node, manager));
if (!ValueAttributes(node.Attributes).Any() && node.ChildNodes.Count == 1
&& node.ChildNodes[0].NodeType == XmlNodeType.Text)
{
// write elements with a single text child as a name value pair
writer.WriteValue(node.ChildNodes[0].Value);
}
else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes))
{
IXmlElement element = (IXmlElement)node;
// empty element
if (element.IsEmpty)
writer.WriteNull();
else
writer.WriteValue(string.Empty);
}
else
{
writer.WriteStartObject();
for (int i = 0; i < node.Attributes.Count; i++)
{
SerializeNode(writer, node.Attributes[i], manager, true);
}
SerializeGroupedNodes(writer, node, manager, true);
writer.WriteEndObject();
}
manager.PopScope();
}
break;
case XmlNodeType.Comment:
if (writePropertyName)
writer.WriteComment(node.Value);
break;
case XmlNodeType.Attribute:
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri)
return;
if (node.NamespaceUri == JsonNamespaceUri)
{
if (node.LocalName == "Array")
return;
}
if (writePropertyName)
writer.WritePropertyName(GetPropertyName(node, manager));
writer.WriteValue(node.Value);
break;
case XmlNodeType.XmlDeclaration:
IXmlDeclaration declaration = (IXmlDeclaration)node;
writer.WritePropertyName(GetPropertyName(node, manager));
writer.WriteStartObject();
if (!string.IsNullOrEmpty(declaration.Version))
{
writer.WritePropertyName("@version");
writer.WriteValue(declaration.Version);
}
if (!string.IsNullOrEmpty(declaration.Encoding))
{
writer.WritePropertyName("@encoding");
writer.WriteValue(declaration.Encoding);
}
if (!string.IsNullOrEmpty(declaration.Standalone))
{
writer.WritePropertyName("@standalone");
writer.WriteValue(declaration.Standalone);
}
writer.WriteEndObject();
break;
case XmlNodeType.DocumentType:
IXmlDocumentType documentType = (IXmlDocumentType)node;
writer.WritePropertyName(GetPropertyName(node, manager));
writer.WriteStartObject();
if (!string.IsNullOrEmpty(documentType.Name))
{
writer.WritePropertyName("@name");
writer.WriteValue(documentType.Name);
}
if (!string.IsNullOrEmpty(documentType.Public))
{
writer.WritePropertyName("@public");
writer.WriteValue(documentType.Public);
}
if (!string.IsNullOrEmpty(documentType.System))
{
writer.WritePropertyName("@system");
writer.WriteValue(documentType.System);
}
if (!string.IsNullOrEmpty(documentType.InternalSubset))
{
writer.WritePropertyName("@internalSubset");
writer.WriteValue(documentType.InternalSubset);
}
writer.WriteEndObject();
break;
default:
throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType);
}
}
#endregion
#region Reading
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
IXmlDocument document = null;
IXmlNode rootNode = null;
#if !NET20
if (typeof(XObject).IsAssignableFrom(objectType))
{
if (objectType != typeof(XDocument) && objectType != typeof(XElement))
throw new JsonSerializationException("XmlNodeConverter only supports deserializing XDocument or XElement.");
XDocument d = new XDocument();
document = new XDocumentWrapper(d);
rootNode = document;
}
#endif
#if !(NETFX_CORE || PORTABLE)
if (typeof(XmlNode).IsAssignableFrom(objectType))
{
if (objectType != typeof(XmlDocument))
throw new JsonSerializationException("XmlNodeConverter only supports deserializing XmlDocuments");
XmlDocument d = new XmlDocument();
// prevent http request when resolving any DTD references
d.XmlResolver = null;
document = new XmlDocumentWrapper(d);
rootNode = document;
}
#endif
if (document == null || rootNode == null)
throw new JsonSerializationException("Unexpected type when converting XML: " + objectType);
if (reader.TokenType != JsonToken.StartObject)
throw new JsonSerializationException("XmlNodeConverter can only convert JSON that begins with an object.");
if (!string.IsNullOrEmpty(DeserializeRootElementName))
{
//rootNode = document.CreateElement(DeserializeRootElementName);
//document.AppendChild(rootNode);
ReadElement(reader, document, rootNode, DeserializeRootElementName, manager);
}
else
{
reader.Read();
DeserializeNode(reader, document, manager, rootNode);
}
#if !NET20
if (objectType == typeof(XElement))
{
XElement element = (XElement)document.DocumentElement.WrappedNode;
element.Remove();
return element;
}
#endif
return document.WrappedNode;
}
private void DeserializeValue(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, string propertyName, IXmlNode currentNode)
{
switch (propertyName)
{
case TextName:
currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString()));
break;
case CDataName:
currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString()));
break;
case WhitespaceName:
currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString()));
break;
case SignificantWhitespaceName:
currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString()));
break;
default:
// processing instructions and the xml declaration start with ?
if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?')
{
CreateInstruction(reader, document, currentNode, propertyName);
}
else if (string.Equals(propertyName, "!DOCTYPE", StringComparison.OrdinalIgnoreCase))
{
CreateDocumentType(reader, document, currentNode);
}
else
{
if (reader.TokenType == JsonToken.StartArray)
{
// handle nested arrays
ReadArrayElements(reader, document, propertyName, currentNode, manager);
return;
}
// have to wait until attributes have been parsed before creating element
// attributes may contain namespace info used by the element
ReadElement(reader, document, currentNode, propertyName, manager);
}
break;
}
}
private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager)
{
if (string.IsNullOrEmpty(propertyName))
throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML.");
Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager);
string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);
if (propertyName.StartsWith('@'))
{
string attributeName = propertyName.Substring(1);
string attributeValue = reader.Value.ToString();
string attributePrefix = MiscellaneousUtils.GetPrefix(attributeName);
IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix))
? document.CreateAttribute(attributeName, manager.LookupNamespace(attributePrefix), attributeValue)
: document.CreateAttribute(attributeName, attributeValue);
((IXmlElement)currentNode).SetAttributeNode(attribute);
}
else
{
IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager);
currentNode.AppendChild(element);
// add attributes to newly created element
foreach (KeyValuePair<string, string> nameValue in attributeNameValues)
{
string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key);
IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix))
? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix) ?? string.Empty, nameValue.Value)
: document.CreateAttribute(nameValue.Key, nameValue.Value);
element.SetAttributeNode(attribute);
}
if (reader.TokenType == JsonToken.String
|| reader.TokenType == JsonToken.Integer
|| reader.TokenType == JsonToken.Float
|| reader.TokenType == JsonToken.Boolean
|| reader.TokenType == JsonToken.Date)
{
element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader)));
}
else if (reader.TokenType == JsonToken.Null)
{
// empty element. do nothing
}
else
{
// finished element will have no children to deserialize
if (reader.TokenType != JsonToken.EndObject)
{
manager.PushScope();
DeserializeNode(reader, document, manager, element);
manager.PopScope();
}
manager.RemoveNamespace(string.Empty, manager.DefaultNamespace);
}
}
}
private string ConvertTokenToXmlValue(JsonReader reader)
{
if (reader.TokenType == JsonToken.String)
{
return reader.Value.ToString();
}
else if (reader.TokenType == JsonToken.Integer)
{
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
if (reader.Value is BigInteger)
return ((BigInteger)reader.Value).ToString(CultureInfo.InvariantCulture);
#endif
return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Float)
{
if (reader.Value is decimal)
return XmlConvert.ToString((decimal)reader.Value);
if (reader.Value is float)
return XmlConvert.ToString((float)reader.Value);
return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Boolean)
{
return XmlConvert.ToString(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Date)
{
#if !NET20
if (reader.Value is DateTimeOffset)
return XmlConvert.ToString((DateTimeOffset)reader.Value);
#endif
DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture);
#if !(NETFX_CORE || PORTABLE)
return XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind));
#else
return XmlConvert.ToString(d);
#endif
}
else if (reader.TokenType == JsonToken.Null)
{
return null;
}
else
{
throw JsonSerializationException.Create(reader, "Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager)
{
string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);
IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager);
currentNode.AppendChild(nestedArrayElement);
int count = 0;
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
DeserializeValue(reader, document, manager, propertyName, nestedArrayElement);
count++;
}
if (WriteArrayAttribute)
{
AddJsonArrayAttribute(nestedArrayElement, document);
}
if (count == 1 && WriteArrayAttribute)
{
IXmlElement arrayElement = nestedArrayElement.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName);
AddJsonArrayAttribute(arrayElement, document);
}
}
private void AddJsonArrayAttribute(IXmlElement element, IXmlDocument document)
{
element.SetAttributeNode(document.CreateAttribute("json:Array", JsonNamespaceUri, "true"));
#if !NET20
// linq to xml doesn't automatically include prefixes via the namespace manager
if (element is XElementWrapper)
{
if (element.GetPrefixOfNamespace(JsonNamespaceUri) == null)
{
element.SetAttributeNode(document.CreateAttribute("xmlns:json", "http://www.w3.org/2000/xmlns/", JsonNamespaceUri));
}
}
#endif
}
private Dictionary<string, string> ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager)
{
Dictionary<string, string> attributeNameValues = new Dictionary<string, string>();
bool finishedAttributes = false;
bool finishedElement = false;
// a string token means the element only has a single text child
if (reader.TokenType != JsonToken.String
&& reader.TokenType != JsonToken.Null
&& reader.TokenType != JsonToken.Boolean
&& reader.TokenType != JsonToken.Integer
&& reader.TokenType != JsonToken.Float
&& reader.TokenType != JsonToken.Date
&& reader.TokenType != JsonToken.StartConstructor)
{
// read properties until first non-attribute is encountered
while (!finishedAttributes && !finishedElement && reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string attributeName = reader.Value.ToString();
if (!string.IsNullOrEmpty(attributeName))
{
char firstChar = attributeName[0];
string attributeValue;
switch (firstChar)
{
case '@':
attributeName = attributeName.Substring(1);
reader.Read();
attributeValue = ConvertTokenToXmlValue(reader);
attributeNameValues.Add(attributeName, attributeValue);
string namespacePrefix;
if (IsNamespaceAttribute(attributeName, out namespacePrefix))
{
manager.AddNamespace(namespacePrefix, attributeValue);
}
break;
case '$':
attributeName = attributeName.Substring(1);
reader.Read();
attributeValue = reader.Value.ToString();
// check that JsonNamespaceUri is in scope
// if it isn't then add it to document and namespace manager
string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri);
if (jsonPrefix == null)
{
// ensure that the prefix used is free
int? i = null;
while (manager.LookupNamespace("json" + i) != null)
{
i = i.GetValueOrDefault() + 1;
}
jsonPrefix = "json" + i;
attributeNameValues.Add("xmlns:" + jsonPrefix, JsonNamespaceUri);
manager.AddNamespace(jsonPrefix, JsonNamespaceUri);
}
attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue);
break;
default:
finishedAttributes = true;
break;
}
}
else
{
finishedAttributes = true;
}
break;
case JsonToken.EndObject:
finishedElement = true;
break;
case JsonToken.Comment:
finishedElement = true;
break;
default:
throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType);
}
}
}
return attributeNameValues;
}
private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName)
{
if (propertyName == DeclarationName)
{
string version = null;
string encoding = null;
string standalone = null;
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
switch (reader.Value.ToString())
{
case "@version":
reader.Read();
version = reader.Value.ToString();
break;
case "@encoding":
reader.Read();
encoding = reader.Value.ToString();
break;
case "@standalone":
reader.Read();
standalone = reader.Value.ToString();
break;
default:
throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value);
}
}
IXmlNode declaration = document.CreateXmlDeclaration(version, encoding, standalone);
currentNode.AppendChild(declaration);
}
else
{
IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString());
currentNode.AppendChild(instruction);
}
}
private void CreateDocumentType(JsonReader reader, IXmlDocument document, IXmlNode currentNode)
{
string name = null;
string publicId = null;
string systemId = null;
string internalSubset = null;
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
switch (reader.Value.ToString())
{
case "@name":
reader.Read();
name = reader.Value.ToString();
break;
case "@public":
reader.Read();
publicId = reader.Value.ToString();
break;
case "@system":
reader.Read();
systemId = reader.Value.ToString();
break;
case "@internalSubset":
reader.Read();
internalSubset = reader.Value.ToString();
break;
default:
throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value);
}
}
IXmlNode documentType = document.CreateXmlDocumentType(name, publicId, systemId, internalSubset);
currentNode.AppendChild(documentType);
}
private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager)
{
string ns = string.IsNullOrEmpty(elementPrefix) ? manager.DefaultNamespace : manager.LookupNamespace(elementPrefix);
IXmlElement element = (!string.IsNullOrEmpty(ns)) ? document.CreateElement(elementName, ns) : document.CreateElement(elementName);
return element;
}
private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode currentNode)
{
do
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null)
throw new JsonSerializationException("JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.");
string propertyName = reader.Value.ToString();
reader.Read();
if (reader.TokenType == JsonToken.StartArray)
{
int count = 0;
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
DeserializeValue(reader, document, manager, propertyName, currentNode);
count++;
}
if (count == 1 && WriteArrayAttribute)
{
IXmlElement arrayElement = currentNode.ChildNodes.OfType<IXmlElement>().Single(n => n.LocalName == propertyName);
AddJsonArrayAttribute(arrayElement, document);
}
}
else
{
DeserializeValue(reader, document, manager, propertyName, currentNode);
}
break;
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
while (reader.Read() && reader.TokenType != JsonToken.EndConstructor)
{
DeserializeValue(reader, document, manager, constructorName, currentNode);
}
break;
case JsonToken.Comment:
currentNode.AppendChild(document.CreateComment((string)reader.Value));
break;
case JsonToken.EndObject:
case JsonToken.EndArray:
return;
default:
throw new JsonSerializationException("Unexpected JsonToken when deserializing node: " + reader.TokenType);
}
} while (reader.TokenType == JsonToken.PropertyName || reader.Read());
// don't read if current token is a property. token was already read when parsing element attributes
}
/// <summary>
/// Checks if the attributeName is a namespace attribute.
/// </summary>
/// <param name="attributeName">Attribute name to test.</param>
/// <param name="prefix">The attribute name prefix if it has one, otherwise an empty string.</param>
/// <returns>True if attribute name is for a namespace attribute, otherwise false.</returns>
private bool IsNamespaceAttribute(string attributeName, out string prefix)
{
if (attributeName.StartsWith("xmlns", StringComparison.Ordinal))
{
if (attributeName.Length == 5)
{
prefix = string.Empty;
return true;
}
else if (attributeName[5] == ':')
{
prefix = attributeName.Substring(6, attributeName.Length - 6);
return true;
}
}
prefix = null;
return false;
}
private IEnumerable<IXmlNode> ValueAttributes(IEnumerable<IXmlNode> c)
{
return c.Where(a => a.NamespaceUri != JsonNamespaceUri);
}
#endregion
/// <summary>
/// Determines whether this instance can convert the specified value type.
/// </summary>
/// <param name="valueType">Type of the value.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type valueType)
{
#if !NET20
if (typeof(XObject).IsAssignableFrom(valueType))
return true;
#endif
#if !(NETFX_CORE || PORTABLE)
if (typeof(XmlNode).IsAssignableFrom(valueType))
return true;
#endif
return false;
}
}
}
#endif
| |
namespace Ioke.Lang {
using System.Collections;
using System.Collections.Generic;
using Ioke.Lang.Util;
public class IokeObject : ITypeChecker {
public Runtime runtime;
string documentation;
IDictionary<string, object> cells;
IList<IokeObject> mimics;
public List<IokeObject> hooks;
IokeData data;
bool frozen = false;
bool marked = false;
public IokeObject(Runtime runtime, string documentation) : this(runtime, documentation, IokeData.None) {
}
public IokeObject(Runtime runtime, string documentation, IokeData data) {
this.runtime = runtime;
this.documentation = documentation;
this.data = data;
this.mimics = new SaneList<IokeObject>();
this.cells = new SaneDictionary<string, object>();
}
public IDictionary<string, object> Cells {
get { return cells; }
}
public IokeData Data {
get { return data; }
set { this.data = value; }
}
public string Documentation {
get { return documentation; }
set { this.documentation = value; }
}
public static IList<IokeObject> GetMimics(object on, IokeObject context) {
return As(on, context).mimics;
}
public IList<IokeObject> GetMimics() {
return mimics;
}
public IokeObject AllocateCopy(IokeObject m, IokeObject context) {
return new IokeObject(runtime, null, data.CloneData(this, m, context));
}
public void MimicsWithoutCheck(IokeObject mimic) {
if(!Contains(this.mimics, mimic)) {
this.mimics.Add(mimic);
}
}
private void CheckFrozen(string modification, IokeObject message, IokeObject context) {
if(frozen) {
IokeObject condition = As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"ModifyOnFrozen"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", this);
condition.SetCell("modification", context.runtime.GetSymbol(modification));
context.runtime.ErrorCondition(condition);
}
}
public static bool Same(object one, object two) {
if((one is IokeObject) && (two is IokeObject)) {
return object.ReferenceEquals(As(one, null).cells, As(two, null).cells);
} else {
return object.ReferenceEquals(one, two);
}
}
public void Become(IokeObject other, IokeObject message, IokeObject context) {
CheckFrozen("become!", message, context);
this.runtime = other.runtime;
this.documentation = other.documentation;
this.cells = other.cells;
this.mimics = other.mimics;
this.data = other.data;
this.frozen = other.frozen;
}
public static void RemoveMimic(object on, object other, IokeObject message, IokeObject context) {
IokeObject me = As(on, context);
me.CheckFrozen("removeMimic!", message, context);
me.mimics.Remove(As(other, context));
if(me.hooks != null) {
Hook.FireMimicsChanged(me, message, context, other);
Hook.FireMimicRemoved(me, message, context, other);
}
}
public static void RemoveAllMimics(object on, IokeObject message, IokeObject context) {
IokeObject me = As(on, context);
me.CheckFrozen("removeAllMimics!", message, context);
List<IokeObject> copy = new SaneList<IokeObject>();
foreach(IokeObject mm in me.mimics) copy.Add(mm);
foreach(IokeObject mm in copy) {
me.mimics.Remove(mm);
Hook.FireMimicsChanged(me, message, context, mm);
Hook.FireMimicRemoved(me, message, context, mm);
}
}
public static bool IsFrozen(object on) {
return (on is IokeObject) && As(on, null).frozen;
}
public static void Freeze(object on) {
if(on is IokeObject) {
As(on,null).frozen = true;
}
}
public static void Thaw(object on) {
if(on is IokeObject) {
As(on, null).frozen = false;
}
}
public static IokeData dataOf(object on) {
return ((IokeObject)on).data;
}
public void SetDocumentation(string docs, IokeObject message, IokeObject context) {
CheckFrozen("documentation=", message, context);
this.documentation = docs;
}
public static object FindCell(object obj, IokeObject m, IokeObject context, string name) {
return As(obj, context).MarkingFindCell(m, context, name);
}
public object FindCell(IokeObject m, IokeObject context, string name) {
return MarkingFindCell(m, context, name);
}
public static void RemoveCell(object on, IokeObject m, IokeObject context, string name) {
((IokeObject)on).RemoveCell(m, context, name);
}
public static void UndefineCell(object on, IokeObject m, IokeObject context, string name) {
((IokeObject)on).UndefineCell(m, context, name);
}
public void RemoveCell(IokeObject m, IokeObject context, string name) {
CheckFrozen("removeCell!", m, context);
if(cells.ContainsKey(name)) {
object prev = cells.Remove(name);
if(hooks != null) {
Hook.FireCellChanged(this, m, context, name, prev);
Hook.FireCellRemoved(this, m, context, name, prev);
}
} else {
IokeObject condition = As(IokeObject.GetCellChain(runtime.Condition,
m,
context,
"Error",
"NoSuchCell"), context).Mimic(m, context);
condition.SetCell("message", m);
condition.SetCell("context", context);
condition.SetCell("receiver", this);
condition.SetCell("cellName", runtime.GetSymbol(name));
runtime.WithReturningRestart("ignore", context, ()=>{runtime.ErrorCondition(condition);});
}
}
public void UndefineCell(IokeObject m, IokeObject context, string name) {
CheckFrozen("undefineCell!", m, context);
object prev = runtime.nil;
if(cells.ContainsKey(name)) {
prev = cells[name];
}
cells[name] = runtime.nul;
if(hooks != null) {
if(prev == null) {
prev = runtime.nil;
}
Hook.FireCellChanged(this, m, context, name, prev);
Hook.FireCellUndefined(this, m, context, name, prev);
}
}
protected virtual object MarkingFindCell(IokeObject m, IokeObject context, string name) {
if(this.marked) {
return runtime.nul;
}
if(cells.ContainsKey(name)) {
return cells[name];
} else {
this.marked = true;
try {
foreach(IokeObject mimic in mimics) {
object cell = mimic.MarkingFindCell(m, context, name);
if(cell != runtime.nul) {
return cell;
}
}
return runtime.nul;
} finally {
this.marked = false;
}
}
}
public static object FindPlace(object obj, string name) {
return As(obj, null).MarkingFindPlace(name);
}
public static object FindPlace(object obj, IokeObject m, IokeObject context, string name) {
object result = FindPlace(obj, name);
if(result == m.runtime.nul) {
IokeObject condition = As(IokeObject.GetCellChain(m.runtime.Condition,
m,
context,
"Error",
"NoSuchCell"), context).Mimic(m, context);
condition.SetCell("message", m);
condition.SetCell("context", context);
condition.SetCell("receiver", obj);
condition.SetCell("cellName", m.runtime.GetSymbol(name));
m.runtime.WithReturningRestart("ignore", context, () => {condition.runtime.ErrorCondition(condition);});
}
return result;
}
/**
* Finds the first object in the chain where name is available as a cell, or nul if nothing can be found.
* findPlace is cycle aware and will not loop in an infinite chain. subclasses should copy this behavior.
*/
public object FindPlace(string name) {
return MarkingFindPlace(name);
}
protected virtual object MarkingFindPlace(string name) {
if(this.marked) {
return runtime.nul;
}
if(cells.ContainsKey(name)) {
if(cells[name] == runtime.nul) {
return runtime.nul;
}
return this;
} else {
this.marked = true;
try {
foreach(IokeObject mimic in mimics) {
object place = mimic.MarkingFindPlace(name);
if(place != runtime.nul) {
return place;
}
}
return runtime.nul;
} finally {
this.marked = false;
}
}
}
public void RegisterMethod(IokeObject m) {
cells[((Method)m.data).Name] = m;
}
public void AliasMethod(string originalName, string newName, IokeObject message, IokeObject context) {
CheckFrozen("aliasMethod", message, context);
IokeObject io = As(FindCell(null, null, originalName), context);
IokeObject newObj = io.Mimic(null, null);
newObj.data = new AliasMethod(newName, io.data, io);
cells[newName] = newObj;
}
public void RegisterCell(string name, object o) {
cells[name] = o;
}
public static void Assign(object on, string name, object value, IokeObject context, IokeObject message) {
As(on, context).Assign(name, value, context, message);
}
public readonly static System.Text.RegularExpressions.Regex SLIGHTLY_BAD_CHARS = new System.Text.RegularExpressions.Regex("[!=\\.\\-\\+&|\\{\\[]");
public virtual void Assign(string name, object value, IokeObject context, IokeObject message) {
CheckFrozen("=", message, context);
if(!SLIGHTLY_BAD_CHARS.Match(name).Success && FindCell(message, context, name + "=") != runtime.nul) {
IokeObject msg = runtime.CreateMessage(new Message(runtime, name + "=", runtime.CreateMessage(Message.Wrap(As(value, context)))));
((Message)IokeObject.dataOf(msg)).SendTo(msg, context, this);
} else {
if(hooks != null) {
bool contains = cells.ContainsKey(name);
object prev = runtime.nil;
if(contains) {
prev = cells[name];
}
cells[name] = value;
if(!contains) {
Hook.FireCellAdded(this, message, context, name);
}
Hook.FireCellChanged(this, message, context, name, prev);
} else {
cells[name] = value;
}
}
}
public static object GetCell(object on, IokeObject m, IokeObject context, string name) {
return ((IokeObject)on).GetCell(m, context, name);
}
public virtual object Self {
get {
if(cells.ContainsKey("self"))
return this.cells["self"];
return null;
}
}
public object GetCell(IokeObject m, IokeObject context, string name) {
object cell = this.FindCell(m, context, name);
while(cell == runtime.nul) {
IokeObject condition = As(IokeObject.GetCellChain(runtime.Condition,
m,
context,
"Error",
"NoSuchCell"), context).Mimic(m, context);
condition.SetCell("message", m);
condition.SetCell("context", context);
condition.SetCell("receiver", this);
condition.SetCell("cellName", runtime.GetSymbol(name));
object[] newCell = new object[]{cell};
runtime.WithRestartReturningArguments(()=>{runtime.ErrorCondition(condition);}, context,
new UseValue(name, newCell),
new StoreValue(name, newCell, this));
cell = newCell[0];
}
return cell;
}
public static void SetCell(object on, string name, object value, IokeObject context) {
As(on, context).SetCell(name, value);
}
public static object SetCell(object on, IokeObject m, IokeObject context, string name, object value) {
((IokeObject)on).SetCell(name, value);
return value;
}
public void SetCell(string name, object o) {
cells[name] = o;
}
public string Kind {
set { cells["kind"] = runtime.NewText(value); }
}
public static object GetRealContext(object o) {
if(o is IokeObject) {
return As(o, null).RealContext;
}
return o;
}
public virtual object RealContext {
get { return this; }
}
public virtual void Init() {
data.Init(this);
}
public IList Arguments {
get { return data.Arguments(this); }
}
public string Name {
get { return data.GetName(this); }
}
public string File {
get { return data.GetFile(this); }
}
public int Line {
get { return data.GetLine(this); }
}
public int Position {
get { return data.GetPosition(this); }
}
public override string ToString() {
return data.ToString(this);
}
public static object Perform(object obj, IokeObject ctx, IokeObject message) {
if(obj is IokeObject) {
return As(obj, ctx).Perform(ctx, message);
}
return null;
}
public static IokeObject As(object on, IokeObject context) {
if(on is IokeObject) {
return ((IokeObject)on);
} else {
return null;
}
}
public static IokeObject Mimic(object on, IokeObject message, IokeObject context) {
return As(on, context).Mimic(message, context);
}
public void Mimics(IokeObject mimic, IokeObject message, IokeObject context) {
CheckFrozen("mimic!", message, context);
mimic.data.CheckMimic(mimic, message, context);
if(!Contains(this.mimics, mimic)) {
this.mimics.Add(mimic);
if(mimic.hooks != null) {
Hook.FireMimicked(mimic, message, context, this);
}
if(hooks != null) {
Hook.FireMimicsChanged(this, message, context, mimic);
Hook.FireMimicAdded(this, message, context, mimic);
}
}
}
public void Mimics(int index, IokeObject mimic, IokeObject message, IokeObject context) {
CheckFrozen("prependMimic!", message, context);
mimic.data.CheckMimic(mimic, message, context);
if(!Contains(this.mimics, mimic)) {
this.mimics.Insert(index, mimic);
if(mimic.hooks != null) {
Hook.FireMimicked(mimic, message, context, this);
}
if(hooks != null) {
Hook.FireMimicsChanged(this, message, context, mimic);
Hook.FireMimicAdded(this, message, context, mimic);
}
}
}
public IokeObject Mimic(IokeObject message, IokeObject context) {
CheckFrozen("mimic!", message, context);
IokeObject clone = AllocateCopy(message, context);
clone.Mimics(this, message, context);
return clone;
}
public object Perform(IokeObject ctx, IokeObject message) {
return Perform(ctx, message, message.Name);
}
private bool IsApplicable(object pass, IokeObject message, IokeObject ctx) {
if(pass != null && pass != runtime.nul && As(pass, ctx).FindCell(message, ctx, "applicable?") != runtime.nul) {
return IsObjectTrue(((Message)IokeObject.dataOf(runtime.isApplicableMessage)).SendTo(runtime.isApplicableMessage, ctx, pass, runtime.CreateMessage(Message.Wrap(message))));
}
return true;
}
public static object GetOrActivate(object obj, IokeObject context, IokeObject message, object on) {
if(obj is IokeObject) {
return As(obj, context).GetOrActivate(context, message, on);
} else {
return obj;
}
}
public virtual bool IsActivatable {
get { return IsObjectTrue(FindCell(null, null, "activatable")); }
}
public virtual bool IsTrue {
get { return data.IsTrue; }
}
public virtual bool IsNil {
get { return data.IsNil; }
}
public virtual bool IsSymbol {
get { return data.IsSymbol; }
}
public virtual bool IsMessage {
get { return data.IsMessage; }
}
public static bool IsObjectMessage(object obj) {
return (obj is IokeObject) && As(obj, null).IsMessage;
}
public static bool IsObjectTrue(object on) {
return !(on is IokeObject) || As(on, null).IsTrue;
}
public string GetKind(IokeObject message, IokeObject context) {
object obj = FindCell(null, null, "kind");
if(IokeObject.dataOf(obj) is Text) {
return ((Text)IokeObject.dataOf(obj)).GetText();
} else {
return ((Text)IokeObject.dataOf(GetOrActivate(obj, context, message, this))).GetText();
}
}
public string GetKind() {
object obj = FindCell(null, null, "kind");
if(obj != null && IokeObject.dataOf(obj) is Text) {
return ((Text)IokeObject.dataOf(obj)).GetText();
} else {
return null;
}
}
public bool HasKind {
get { return cells.ContainsKey("kind"); }
}
public object GetOrActivate(IokeObject context, IokeObject message, object on) {
if(IsActivatable || ((data is CanRun) && message.Arguments.Count > 0)) {
return Activate(context, message, on);
} else {
return this;
}
}
public static object FindSuperCellOn(object obj, IokeObject early, IokeObject message, IokeObject context, string name) {
return As(obj, context).MarkingFindSuperCell(early, message, context, name, new bool[]{false});
}
protected virtual object MarkingFindSuperCell(IokeObject early, IokeObject message, IokeObject context, string name, bool[] found) {
if(name == null || this.marked) {
return runtime.nul;
}
if(cells.ContainsKey(name)) {
if(found[0]) {
return cells[name];
}
if(early == cells[name]) {
found[0] = true;
}
}
this.marked = true;
try {
foreach(IokeObject mimic in mimics) {
object cell = mimic.MarkingFindSuperCell(early, message, context, name, found);
if(cell != runtime.nul) {
return cell;
}
}
return runtime.nul;
} finally {
this.marked = false;
}
}
public static object Activate(object self, IokeObject context, IokeObject message, object on) {
return As(self, context).Activate(context, message, on);
}
public object Activate(IokeObject context, IokeObject message, object on) {
return data.Activate(this, context, message, on);
}
public object ActivateWithData(IokeObject context, IokeObject message, object on, IDictionary<string, object> d1) {
return data.ActivateWithData(this, context, message, on, d1);
}
public object ActivateWithCall(IokeObject context, IokeObject message, object on, object c) {
return data.ActivateWithCall(this, context, message, on, c);
}
public object ActivateWithCallAndData(IokeObject context, IokeObject message, object on, object c, IDictionary<string, object> d1) {
return data.ActivateWithCallAndData(this, context, message, on, c, d1);
}
public class UseValue : Restart.ArgumentGivingRestart {
string variableName;
object[] place;
public UseValue(string variableName, object[] place) : base("useValue") {
this.variableName = variableName;
this.place = place;
}
public override string Report() {
return "Use value for: " + variableName;
}
public override IList<string> ArgumentNames {
get { return new SaneList<string>() {"newValue"}; }
}
public override IokeObject Invoke(IokeObject context, IList arguments) {
place[0] = arguments[0];
return context.runtime.nil;
}
}
private class StoreValue : Restart.ArgumentGivingRestart {
string variableName;
object[] place;
IokeObject obj;
public StoreValue(string variableName, object[] place, IokeObject obj) : base("useValue") {
this.variableName = variableName;
this.place = place;
this.obj = obj;
}
public override string Report() {
return "Store value for: " + variableName;
}
public override IList<string> ArgumentNames {
get { return new SaneList<string>() {"newValue"}; }
}
public override IokeObject Invoke(IokeObject context, IList arguments) {
place[0] = arguments[0];
obj.SetCell(name, place[0]);
return context.runtime.nil;
}
}
public static object GetCellChain(object on, IokeObject m, IokeObject c, params string[] names) {
object current = on;
foreach(string name in names) {
current = GetCell(current, m, c, name);
}
return current;
}
public object Perform(IokeObject ctx, IokeObject message, string name) {
object cell = this.FindCell(message, ctx, name);
object passed = null;
while(cell == runtime.nul && (((cell = passed = this.FindCell(message, ctx, "pass")) == runtime.nul) || !IsApplicable(passed, message, ctx))) {
IokeObject condition = As(IokeObject.GetCellChain(runtime.Condition,
message,
ctx,
"Error",
"NoSuchCell"), ctx).Mimic(message, ctx);
condition.SetCell("message", message);
condition.SetCell("context", ctx);
condition.SetCell("receiver", this);
condition.SetCell("cellName", runtime.GetSymbol(name));
object[] newCell = new object[]{cell};
runtime.WithRestartReturningArguments(() => {runtime.ErrorCondition(condition);}, ctx, new UseValue(name, newCell), new StoreValue(name, newCell, this));
cell = newCell[0];
}
return GetOrActivate(cell, ctx, message, this);
}
public static bool IsKind(object on, string kind, IokeObject context) {
return As(on, context).IsKind(kind);
}
public static bool IsMimic(object on, IokeObject potentialMimic, IokeObject context) {
return As(on, context).IsMimic(potentialMimic);
}
public static bool IsKind(IokeObject on, string kind) {
return As(on, on).IsKind(kind);
}
public static bool IsMimic(IokeObject on, IokeObject potentialMimic) {
return As(on, on).IsMimic(potentialMimic);
}
private bool IsKind(string kind) {
if(this.marked) {
return false;
}
if(cells.ContainsKey("kind") && kind.Equals(Text.GetText(cells["kind"]))) {
return true;
}
this.marked = true;
try {
foreach(IokeObject mimic in mimics) {
if(mimic.IsKind(kind)) {
return true;
}
}
return false;
} finally {
this.marked = false;
}
}
public static bool Contains(IList<IokeObject> l, IokeObject obj) {
foreach(IokeObject p in l) {
if(p == obj) {
return true;
}
}
return false;
}
private bool IsMimic(IokeObject pot) {
if(this.marked) {
return false;
}
if(this.cells == pot.cells || Contains(mimics, pot)) {
return true;
}
this.marked = true;
try {
foreach(IokeObject mimic in mimics) {
if(mimic.IsMimic(pot)) {
return true;
}
}
return false;
} finally {
this.marked = false;
}
}
public static IokeObject ConvertToRational(object on, IokeObject m, IokeObject context, bool signalCondition) {
return ((IokeObject)on).ConvertToRational(m, context, signalCondition);
}
public static IokeObject ConvertToDecimal(object on, IokeObject m, IokeObject context, bool signalCondition) {
return ((IokeObject)on).ConvertToDecimal(m, context, signalCondition);
}
public IokeObject ConvertToRational(IokeObject m, IokeObject context, bool signalCondition) {
IokeObject result = data.ConvertToRational(this, m, context, false);
if(result == null) {
if(FindCell(m, context, "asRational") != context.runtime.nul) {
return IokeObject.As(((Message)IokeObject.dataOf(context.runtime.asRationalMessage)).SendTo(context.runtime.asRationalMessage, context, this), context);
}
if(signalCondition) {
return data.ConvertToRational(this, m, context, true);
}
return context.runtime.nil;
}
return result;
}
public IokeObject ConvertToDecimal(IokeObject m, IokeObject context, bool signalCondition) {
IokeObject result = data.ConvertToDecimal(this, m, context, false);
if(result == null) {
if(FindCell(m, context, "asDecimal") != context.runtime.nul) {
return IokeObject.As(((Message)IokeObject.dataOf(context.runtime.asDecimalMessage)).SendTo(context.runtime.asDecimalMessage, context, this), context);
}
if(signalCondition) {
return data.ConvertToDecimal(this, m, context, true);
}
return context.runtime.nil;
}
return result;
}
public static IokeObject ConvertToNumber(object on, IokeObject m, IokeObject context) {
return ((IokeObject)on).ConvertToNumber(m, context);
}
public IokeObject ConvertToNumber(IokeObject m, IokeObject context) {
return data.ConvertToNumber(this, m, context);
}
public static string Inspect(object on) {
if(on is IokeObject) {
IokeObject ion = (IokeObject)on;
Runtime runtime = ion.runtime;
return Text.GetText(((Message)IokeObject.dataOf(runtime.inspectMessage)).SendTo(runtime.inspectMessage, ion, ion));
} else {
return on.ToString();
}
}
public static string Notice(object on) {
if(on is IokeObject) {
IokeObject ion = (IokeObject)on;
Runtime runtime = ion.runtime;
return Text.GetText(((Message)IokeObject.dataOf(runtime.noticeMessage)).SendTo(runtime.noticeMessage, ion, ion));
} else {
return on.ToString();
}
}
public static IokeObject ConvertToText(object on, IokeObject m, IokeObject context, bool signalCondition) {
return ((IokeObject)on).ConvertToText(m, context, signalCondition);
}
public static IokeObject TryConvertToText(object on, IokeObject m, IokeObject context) {
return ((IokeObject)on).TryConvertToText(m, context);
}
public static IokeObject ConvertToRegexp(object on, IokeObject m, IokeObject context) {
return ((IokeObject)on).ConvertToRegexp(m, context);
}
public IokeObject ConvertToRegexp(IokeObject m, IokeObject context) {
return data.ConvertToRegexp(this, m, context);
}
public static IokeObject ConvertToSymbol(object on, IokeObject m, IokeObject context, bool signalCondition) {
return ((IokeObject)on).ConvertToSymbol(m, context, signalCondition);
}
public IokeObject ConvertToSymbol(IokeObject m, IokeObject context, bool signalCondition) {
IokeObject result = data.ConvertToSymbol(this, m, context, false);
if(result == null) {
if(FindCell(m, context, "asSymbol") != context.runtime.nul) {
return As(((Message)IokeObject.dataOf(context.runtime.asSymbolMessage)).SendTo(context.runtime.asSymbolMessage, context, this), context);
}
if(signalCondition) {
return data.ConvertToSymbol(this, m, context, true);
}
return context.runtime.nil;
}
return result;
}
public IokeObject ConvertToText(IokeObject m, IokeObject context, bool signalCondition) {
IokeObject result = data.ConvertToText(this, m, context, false);
if(result == null) {
if(FindCell(m, context, "asText") != context.runtime.nul) {
return As(((Message)IokeObject.dataOf(context.runtime.asText)).SendTo(context.runtime.asText, context, this), context);
}
if(signalCondition) {
return data.ConvertToText(this, m, context, true);
}
return context.runtime.nil;
}
return result;
}
public IokeObject TryConvertToText(IokeObject m, IokeObject context) {
return data.TryConvertToText(this, m, context);
}
public static object ConvertTo(string kind, object on, bool signalCondition, string conversionMethod, IokeObject message, IokeObject context) {
return ((IokeObject)on).ConvertTo(kind, signalCondition, conversionMethod, message, context);
}
public static object ConvertTo(object mimic, object on, bool signalCondition, string conversionMethod, IokeObject message, IokeObject context) {
return ((IokeObject)on).ConvertTo(mimic, signalCondition, conversionMethod, message, context);
}
public object ConvertTo(string kind, bool signalCondition, string conversionMethod, IokeObject message, IokeObject context) {
object result = data.ConvertTo(this, kind, false, conversionMethod, message, context);
if(result == null) {
if(conversionMethod != null && FindCell(message, context, conversionMethod) != context.runtime.nul) {
IokeObject msg = context.runtime.NewMessage(conversionMethod);
return ((Message)IokeObject.dataOf(msg)).SendTo(msg, context, this);
}
if(signalCondition) {
return data.ConvertTo(this, kind, true, conversionMethod, message, context);
}
return context.runtime.nul;
}
return result;
}
public object ConvertTo(object mimic, bool signalCondition, string conversionMethod, IokeObject message, IokeObject context) {
object result = data.ConvertTo(this, mimic, false, conversionMethod, message, context);
if(result == null) {
if(conversionMethod != null && FindCell(message, context, conversionMethod) != context.runtime.nul) {
IokeObject msg = context.runtime.NewMessage(conversionMethod);
return ((Message)IokeObject.dataOf(msg)).SendTo(msg, context, this);
}
if(signalCondition) {
return data.ConvertTo(this, mimic, true, conversionMethod, message, context);
}
return context.runtime.nul;
}
return result;
}
public object ConvertToMimic(object on, IokeObject message, IokeObject context, bool signal) {
return ConvertToThis(on, signal, message, context);
}
public object ConvertToThis(object on, IokeObject message, IokeObject context) {
return ConvertToThis(on, true, message, context);
}
public object ConvertToThis(object on, bool signalCondition, IokeObject message, IokeObject context) {
if(on is IokeObject) {
if(IokeObject.dataOf(on).GetType().Equals(data.GetType())) {
return on;
} else {
return IokeObject.ConvertTo(this, on, signalCondition, IokeObject.dataOf(on).ConvertMethod, message, context);
}
} else {
if(signalCondition) {
throw new System.Exception("oh no. -(: " + message.Name);
} else {
return context.runtime.nul;
}
}
}
public override bool Equals(object other) {
try {
return IsEqualTo(other);
} catch(System.Exception) {
return false;
}
}
public override int GetHashCode() {
return IokeHashCode();
}
public new static bool Equals(object lhs, object rhs) {
return ((IokeObject)lhs).IsEqualTo(rhs);
}
public bool IsEqualTo(object other) {
return data.IsEqualTo(this, other);
}
public int IokeHashCode() {
return data.HashCode(this);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Text;
using System.Security;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.ConstrainedExecution;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.CodeAnalysis;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Remoting;
namespace System.Management.Automation.Internal
{
/// <summary>
/// Class that encapsulates native crypto provider handles and provides a
/// mechanism for resources released by them.
/// </summary>
// [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
// [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
internal class PSSafeCryptProvHandle : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// This safehandle instance "owns" the handle, hence base(true)
/// is being called. When safehandle is no longer in use it will
/// call this class's ReleaseHandle method which will release
/// the resources.
/// </summary>
internal PSSafeCryptProvHandle() : base(true) { }
/// <summary>
/// Release the crypto handle held by this instance.
/// </summary>
/// <returns>True on success, false otherwise.</returns>
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected override bool ReleaseHandle()
{
return PSCryptoNativeUtils.CryptReleaseContext(handle, 0);
}
}
/// <summary>
/// Class the encapsulates native crypto key handles and provides a
/// mechanism to release resources used by it.
/// </summary>
// [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
// [SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
internal class PSSafeCryptKey : SafeHandleZeroOrMinusOneIsInvalid
{
/// <summary>
/// This safehandle instance "owns" the handle, hence base(true)
/// is being called. When safehandle is no longer in use it will
/// call this class's ReleaseHandle method which will release the
/// resources.
/// </summary>
internal PSSafeCryptKey() : base(true) { }
/// <summary>
/// Release the crypto handle held by this instance.
/// </summary>
/// <returns>True on success, false otherwise.</returns>
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected override bool ReleaseHandle()
{
return PSCryptoNativeUtils.CryptDestroyKey(handle);
}
/// <summary>
/// Equivalent of IntPtr.Zero for the safe crypt key.
/// </summary>
internal static PSSafeCryptKey Zero { get; } = new PSSafeCryptKey();
}
/// <summary>
/// This class provides the wrapper for all Native CAPI functions.
/// </summary>
internal class PSCryptoNativeUtils
{
#region Functions
#if UNIX
/// Return Type: BOOL->int
///hProv: HCRYPTPROV->ULONG_PTR->unsigned int
///Algid: ALG_ID->unsigned int
///dwFlags: DWORD->unsigned int
///phKey: HCRYPTKEY*
public static bool CryptGenKey(
PSSafeCryptProvHandle hProv,
uint Algid,
uint dwFlags,
ref PSSafeCryptKey phKey)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
public static bool CryptDestroyKey(IntPtr hKey)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///phProv: HCRYPTPROV*
///szContainer: LPCWSTR->WCHAR*
///szProvider: LPCWSTR->WCHAR*
///dwProvType: DWORD->unsigned int
///dwFlags: DWORD->unsigned int
public static bool CryptAcquireContext(ref PSSafeCryptProvHandle phProv,
[InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string szContainer,
[InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string szProvider,
uint dwProvType,
uint dwFlags)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hProv: HCRYPTPROV->ULONG_PTR->unsigned int
///dwFlags: DWORD->unsigned int
public static bool CryptReleaseContext(IntPtr hProv, uint dwFlags)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///hHash: HCRYPTHASH->ULONG_PTR->unsigned int
///Final: BOOL->int
///dwFlags: DWORD->unsigned int
///pbData: BYTE*
///pdwDataLen: DWORD*
///dwBufLen: DWORD->unsigned int
public static bool CryptEncrypt(PSSafeCryptKey hKey,
IntPtr hHash,
[MarshalAsAttribute(UnmanagedType.Bool)] bool Final,
uint dwFlags,
byte[] pbData,
ref int pdwDataLen,
int dwBufLen)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///hHash: HCRYPTHASH->ULONG_PTR->unsigned int
///Final: BOOL->int
///dwFlags: DWORD->unsigned int
///pbData: BYTE*
///pdwDataLen: DWORD*
public static bool CryptDecrypt(PSSafeCryptKey hKey,
IntPtr hHash,
[MarshalAsAttribute(UnmanagedType.Bool)] bool Final,
uint dwFlags,
byte[] pbData,
ref int pdwDataLen)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///hExpKey: HCRYPTKEY->ULONG_PTR->unsigned int
///dwBlobType: DWORD->unsigned int
///dwFlags: DWORD->unsigned int
///pbData: BYTE*
///pdwDataLen: DWORD*
public static bool CryptExportKey(PSSafeCryptKey hKey,
PSSafeCryptKey hExpKey,
uint dwBlobType,
uint dwFlags,
byte[] pbData,
ref uint pdwDataLen)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hProv: HCRYPTPROV->ULONG_PTR->unsigned int
///pbData: BYTE*
///dwDataLen: DWORD->unsigned int
///hPubKey: HCRYPTKEY->ULONG_PTR->unsigned int
///dwFlags: DWORD->unsigned int
///phKey: HCRYPTKEY*
public static bool CryptImportKey(PSSafeCryptProvHandle hProv,
byte[] pbData,
int dwDataLen,
PSSafeCryptKey hPubKey,
uint dwFlags,
ref PSSafeCryptKey phKey)
{
throw new PSCryptoException();
}
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///pdwReserved: DWORD*
///dwFlags: DWORD->unsigned int
///phKey: HCRYPTKEY*
public static bool CryptDuplicateKey(PSSafeCryptKey hKey,
ref uint pdwReserved,
uint dwFlags,
ref PSSafeCryptKey phKey)
{
throw new PSCryptoException();
}
/// Return Type: DWORD->unsigned int
public static uint GetLastError()
{
throw new PSCryptoException();
}
#else
/// Return Type: BOOL->int
///hProv: HCRYPTPROV->ULONG_PTR->unsigned int
///Algid: ALG_ID->unsigned int
///dwFlags: DWORD->unsigned int
///phKey: HCRYPTKEY*
[DllImportAttribute(PinvokeDllNames.CryptGenKeyDllName, EntryPoint = "CryptGenKey")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptGenKey(PSSafeCryptProvHandle hProv,
uint Algid,
uint dwFlags,
ref PSSafeCryptKey phKey);
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
[DllImportAttribute(PinvokeDllNames.CryptDestroyKeyDllName, EntryPoint = "CryptDestroyKey")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptDestroyKey(IntPtr hKey);
/// Return Type: BOOL->int
///phProv: HCRYPTPROV*
///szContainer: LPCWSTR->WCHAR*
///szProvider: LPCWSTR->WCHAR*
///dwProvType: DWORD->unsigned int
///dwFlags: DWORD->unsigned int
[DllImportAttribute(PinvokeDllNames.CryptAcquireContextDllName, EntryPoint = "CryptAcquireContext")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptAcquireContext(ref PSSafeCryptProvHandle phProv,
[InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string szContainer,
[InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string szProvider,
uint dwProvType,
uint dwFlags);
/// Return Type: BOOL->int
///hProv: HCRYPTPROV->ULONG_PTR->unsigned int
///dwFlags: DWORD->unsigned int
[DllImportAttribute(PinvokeDllNames.CryptReleaseContextDllName, EntryPoint = "CryptReleaseContext")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptReleaseContext(IntPtr hProv, uint dwFlags);
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///hHash: HCRYPTHASH->ULONG_PTR->unsigned int
///Final: BOOL->int
///dwFlags: DWORD->unsigned int
///pbData: BYTE*
///pdwDataLen: DWORD*
///dwBufLen: DWORD->unsigned int
[DllImportAttribute(PinvokeDllNames.CryptEncryptDllName, EntryPoint = "CryptEncrypt")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptEncrypt(PSSafeCryptKey hKey,
IntPtr hHash,
[MarshalAsAttribute(UnmanagedType.Bool)] bool Final,
uint dwFlags,
byte[] pbData,
ref int pdwDataLen,
int dwBufLen);
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///hHash: HCRYPTHASH->ULONG_PTR->unsigned int
///Final: BOOL->int
///dwFlags: DWORD->unsigned int
///pbData: BYTE*
///pdwDataLen: DWORD*
[DllImportAttribute(PinvokeDllNames.CryptDecryptDllName, EntryPoint = "CryptDecrypt")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptDecrypt(PSSafeCryptKey hKey,
IntPtr hHash,
[MarshalAsAttribute(UnmanagedType.Bool)] bool Final,
uint dwFlags,
byte[] pbData,
ref int pdwDataLen);
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///hExpKey: HCRYPTKEY->ULONG_PTR->unsigned int
///dwBlobType: DWORD->unsigned int
///dwFlags: DWORD->unsigned int
///pbData: BYTE*
///pdwDataLen: DWORD*
[DllImportAttribute(PinvokeDllNames.CryptExportKeyDllName, EntryPoint = "CryptExportKey")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptExportKey(PSSafeCryptKey hKey,
PSSafeCryptKey hExpKey,
uint dwBlobType,
uint dwFlags,
byte[] pbData,
ref uint pdwDataLen);
/// Return Type: BOOL->int
///hProv: HCRYPTPROV->ULONG_PTR->unsigned int
///pbData: BYTE*
///dwDataLen: DWORD->unsigned int
///hPubKey: HCRYPTKEY->ULONG_PTR->unsigned int
///dwFlags: DWORD->unsigned int
///phKey: HCRYPTKEY*
[DllImportAttribute(PinvokeDllNames.CryptImportKeyDllName, EntryPoint = "CryptImportKey")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptImportKey(PSSafeCryptProvHandle hProv,
byte[] pbData,
int dwDataLen,
PSSafeCryptKey hPubKey,
uint dwFlags,
ref PSSafeCryptKey phKey);
/// Return Type: BOOL->int
///hKey: HCRYPTKEY->ULONG_PTR->unsigned int
///pdwReserved: DWORD*
///dwFlags: DWORD->unsigned int
///phKey: HCRYPTKEY*
[DllImportAttribute(PinvokeDllNames.CryptDuplicateKeyDllName, EntryPoint = "CryptDuplicateKey")]
[return: MarshalAsAttribute(UnmanagedType.Bool)]
public static extern bool CryptDuplicateKey(PSSafeCryptKey hKey,
ref uint pdwReserved,
uint dwFlags,
ref PSSafeCryptKey phKey);
/// Return Type: DWORD->unsigned int
[DllImportAttribute(PinvokeDllNames.GetLastErrorDllName, EntryPoint = "GetLastError")]
public static extern uint GetLastError();
#endif
#endregion Functions
#region Constants
/// <summary>
/// Do not use persisted private key.
/// </summary>
public const uint CRYPT_VERIFYCONTEXT = 0xF0000000;
/// <summary>
/// Mark the key for export.
/// </summary>
public const uint CRYPT_EXPORTABLE = 0x00000001;
/// <summary>
/// Automatically assign a salt value when creating a
/// session key.
/// </summary>
public const int CRYPT_CREATE_SALT = 4;
/// <summary>
/// RSA Provider.
/// </summary>
public const int PROV_RSA_FULL = 1;
/// <summary>
/// RSA Provider that supports AES
/// encryption.
/// </summary>
public const int PROV_RSA_AES = 24;
/// <summary>
/// Public key to be used for encryption.
/// </summary>
public const int AT_KEYEXCHANGE = 1;
/// <summary>
/// RSA Key.
/// </summary>
public const int CALG_RSA_KEYX =
(PSCryptoNativeUtils.ALG_CLASS_KEY_EXCHANGE |
(PSCryptoNativeUtils.ALG_TYPE_RSA | PSCryptoNativeUtils.ALG_SID_RSA_ANY));
/// <summary>
/// Create a key for encryption.
/// </summary>
public const int ALG_CLASS_KEY_EXCHANGE = (5) << (13);
/// <summary>
/// Create a RSA key pair.
/// </summary>
public const int ALG_TYPE_RSA = (2) << (9);
/// <summary>
/// </summary>
public const int ALG_SID_RSA_ANY = 0;
/// <summary>
/// Option for exporting public key blob.
/// </summary>
public const int PUBLICKEYBLOB = 6;
/// <summary>
/// Option for exporting a session key.
/// </summary>
public const int SIMPLEBLOB = 1;
/// <summary>
/// AES 256 symmetric key.
/// </summary>
public const int CALG_AES_256 = (ALG_CLASS_DATA_ENCRYPT | ALG_TYPE_BLOCK | ALG_SID_AES_256);
/// <summary>
/// ALG_CLASS_DATA_ENCRYPT.
/// </summary>
public const int ALG_CLASS_DATA_ENCRYPT = (3) << (13);
/// <summary>
/// ALG_TYPE_BLOCK.
/// </summary>
public const int ALG_TYPE_BLOCK = (3) << (9);
/// <summary>
/// ALG_SID_AES_256 -> 16.
/// </summary>
public const int ALG_SID_AES_256 = 16;
/// CALG_AES_128 -> (ALG_CLASS_DATA_ENCRYPT|ALG_TYPE_BLOCK|ALG_SID_AES_128)
public const int CALG_AES_128 = (ALG_CLASS_DATA_ENCRYPT
| (ALG_TYPE_BLOCK | ALG_SID_AES_128));
/// ALG_SID_AES_128 -> 14
public const int ALG_SID_AES_128 = 14;
#endregion Constants
}
/// <summary>
/// Defines a custom exception which is thrown when
/// a native CAPI call results in an error.
/// </summary>
/// <remarks>This exception is currently internal as it's not
/// surfaced to the user. However, if we decide to surface errors
/// to the user when something fails on the remote end, then this
/// can be turned public</remarks>
[SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")]
[Serializable]
internal class PSCryptoException : Exception
{
#region Private Members
private uint _errorCode;
#endregion Private Members
#region Internal Properties
/// <summary>
/// Error code returned by the native CAPI call.
/// </summary>
internal uint ErrorCode
{
get
{
return _errorCode;
}
}
#endregion Internal Properties
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
public PSCryptoException() : this(0, new StringBuilder(string.Empty)) { }
/// <summary>
/// Constructor that will be used from within CryptoUtils.
/// </summary>
/// <param name="errorCode">error code returned by native
/// crypto application</param>
/// <param name="message">Error message associated with this failure.</param>
public PSCryptoException(uint errorCode, StringBuilder message)
: base(message.ToString())
{
_errorCode = errorCode;
}
/// <summary>
/// Constructor with just message but no inner exception.
/// </summary>
/// <param name="message">Error message associated with this failure.</param>
public PSCryptoException(string message) : this(message, null) { }
/// <summary>
/// Constructor with inner exception.
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="innerException">Inner exception.</param>
/// <remarks>This constructor is currently not called
/// explicitly from crypto utils</remarks>
public PSCryptoException(string message, Exception innerException) :
base(message, innerException)
{
_errorCode = unchecked((uint)-1);
}
/// <summary>
/// Constructor which has type specific serialization logic.
/// </summary>
/// <param name="info">Serialization info.</param>
/// <param name="context">Context in which this constructor is called.</param>
/// <remarks>Currently no custom type-specific serialization logic is
/// implemented</remarks>
protected PSCryptoException(SerializationInfo info, StreamingContext context)
:
base(info, context)
{
_errorCode = unchecked(0xFFFFFFF);
Dbg.Assert(false, "type-specific serialization logic not implemented and so this constructor should not be called");
}
#endregion Constructors
#region ISerializable Overrides
/// <summary>
/// Returns base implementation.
/// </summary>
/// <param name="info">Serialization info.</param>
/// <param name="context">Context.</param>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
#endregion ISerializable Overrides
}
/// <summary>
/// One of the issues with RSACryptoServiceProvider is that it never uses CRYPT_VERIFYCONTEXT
/// to create ephemeral keys. This class is a facade written on top of native CAPI APIs
/// to create ephemeral keys.
/// </summary>
internal class PSRSACryptoServiceProvider : IDisposable
{
#region Private Members
private PSSafeCryptProvHandle _hProv;
// handle to the provider
private bool _canEncrypt = false; // this flag indicates that this class has a key
// imported from the remote end and so can be
// used for encryption
private PSSafeCryptKey _hRSAKey;
// handle to the RSA key with which the session
// key is exchange. This can either be generated
// or imported
private PSSafeCryptKey _hSessionKey;
// handle to the session key. This can either
// be generated or imported
private bool _sessionKeyGenerated = false;
// bool indicating if session key was generated before
private static PSSafeCryptProvHandle s_hStaticProv;
private static PSSafeCryptKey s_hStaticRSAKey;
private static bool s_keyPairGenerated = false;
private static object s_syncObject = new object();
#endregion Private Members
#region Constructors
/// <summary>
/// Private constructor.
/// </summary>
/// <param name="serverMode">indicates if this service
/// provider is operating in server mode</param>
private PSRSACryptoServiceProvider(bool serverMode)
{
if (serverMode)
{
_hProv = new PSSafeCryptProvHandle();
// We need PROV_RSA_AES to support AES-256 symmetric key
// encryption. PROV_RSA_FULL supports only RC2 and RC4
bool ret = PSCryptoNativeUtils.CryptAcquireContext(ref _hProv,
null,
null,
PSCryptoNativeUtils.PROV_RSA_AES,
PSCryptoNativeUtils.CRYPT_VERIFYCONTEXT);
CheckStatus(ret);
_hRSAKey = new PSSafeCryptKey();
}
_hSessionKey = new PSSafeCryptKey();
}
#endregion Constructors
#region Internal Methods
/// <summary>
/// Get the public key as a base64 encoded string.
/// </summary>
/// <returns>Public key as base64 encoded string.</returns>
internal string GetPublicKeyAsBase64EncodedString()
{
uint publicKeyLength = 0;
// Get key length first
bool ret = PSCryptoNativeUtils.CryptExportKey(_hRSAKey,
PSSafeCryptKey.Zero,
PSCryptoNativeUtils.PUBLICKEYBLOB,
0,
null,
ref publicKeyLength);
CheckStatus(ret);
// Create enough buffer and get the actual data
byte[] publicKey = new byte[publicKeyLength];
ret = PSCryptoNativeUtils.CryptExportKey(_hRSAKey,
PSSafeCryptKey.Zero,
PSCryptoNativeUtils.PUBLICKEYBLOB,
0,
publicKey,
ref publicKeyLength);
CheckStatus(ret);
// Convert the public key into base64 encoding so that it can be exported to
// the other end.
string result = Convert.ToBase64String(publicKey);
return result;
}
/// <summary>
/// Generates an AEX-256 session key if one is not already generated.
/// </summary>
internal void GenerateSessionKey()
{
if (_sessionKeyGenerated)
return;
lock (s_syncObject)
{
if (!_sessionKeyGenerated)
{
bool ret = PSCryptoNativeUtils.CryptGenKey(_hProv,
PSCryptoNativeUtils.CALG_AES_256,
0x01000000 | // key length = 256 bits
PSCryptoNativeUtils.CRYPT_EXPORTABLE |
PSCryptoNativeUtils.CRYPT_CREATE_SALT,
ref _hSessionKey);
CheckStatus(ret);
_sessionKeyGenerated = true;
_canEncrypt = true; // we can encrypt and decrypt once session key is available
}
}
}
/// <summary>
/// 1. Generate a AES-256 session key
/// 2. Encrypt the session key with the Imported
/// RSA public key
/// 3. Encode result above as base 64 string and export.
/// </summary>
/// <returns>Session key encrypted with receivers public key
/// and encoded as a base 64 string.</returns>
internal string SafeExportSessionKey()
{
// generate one if not already done.
GenerateSessionKey();
uint length = 0;
// get key length first
bool ret = PSCryptoNativeUtils.CryptExportKey(_hSessionKey,
_hRSAKey,
PSCryptoNativeUtils.SIMPLEBLOB,
0,
null,
ref length);
CheckStatus(ret);
// allocate buffer and export the key
byte[] sessionkey = new byte[length];
ret = PSCryptoNativeUtils.CryptExportKey(_hSessionKey,
_hRSAKey,
PSCryptoNativeUtils.SIMPLEBLOB,
0,
sessionkey,
ref length);
CheckStatus(ret);
// now we can encrypt as we have the session key
_canEncrypt = true;
// convert the key to base64 before exporting
return Convert.ToBase64String(sessionkey);
}
/// <summary>
/// Import a public key into the provider whose context
/// has been obtained.
/// </summary>
/// <param name="publicKey">Base64 encoded public key to import.</param>
internal void ImportPublicKeyFromBase64EncodedString(string publicKey)
{
Dbg.Assert(!string.IsNullOrEmpty(publicKey), "key cannot be null or empty");
byte[] convertedBase64 = Convert.FromBase64String(publicKey);
bool ret = PSCryptoNativeUtils.CryptImportKey(_hProv,
convertedBase64,
convertedBase64.Length,
PSSafeCryptKey.Zero,
0,
ref _hRSAKey);
CheckStatus(ret);
}
/// <summary>
/// Import a session key from the remote side into
/// the current CSP.
/// </summary>
/// <param name="sessionKey">encrypted session key as a
/// base64 encoded string</param>
internal void ImportSessionKeyFromBase64EncodedString(string sessionKey)
{
Dbg.Assert(!string.IsNullOrEmpty(sessionKey), "key cannot be null or empty");
byte[] convertedBase64 = Convert.FromBase64String(sessionKey);
bool ret = PSCryptoNativeUtils.CryptImportKey(_hProv,
convertedBase64,
convertedBase64.Length,
_hRSAKey,
0,
ref _hSessionKey);
CheckStatus(ret);
// now we have imported the key and will be able to
// encrypt using the session key
_canEncrypt = true;
}
/// <summary>
/// Encrypt the specified byte array.
/// </summary>
/// <param name="data">Data to encrypt.</param>
/// <returns>Encrypted byte array.</returns>
internal byte[] EncryptWithSessionKey(byte[] data)
{
// first make a copy of the original data.This is needed
// as CryptEncrypt uses the same buffer to write the encrypted data
// into.
Dbg.Assert(_canEncrypt, "Remote key has not been imported to encrypt");
byte[] encryptedData = new byte[data.Length];
Array.Copy(data, 0, encryptedData, 0, data.Length);
int dataLength = encryptedData.Length;
// encryption always happens using the session key
bool ret = PSCryptoNativeUtils.CryptEncrypt(_hSessionKey,
IntPtr.Zero,
true,
0,
encryptedData,
ref dataLength,
data.Length);
// if encryption failed, then dataLength will contain the length
// of buffer needed to store the encrypted contents. Recreate
// the buffer
if (false == ret)
{
// before reallocating the encryptedData buffer,
// zero out its contents
for (int i = 0; i < encryptedData.Length; i++)
{
encryptedData[i] = 0;
}
encryptedData = new byte[dataLength];
Array.Copy(data, 0, encryptedData, 0, data.Length);
dataLength = data.Length;
ret = PSCryptoNativeUtils.CryptEncrypt(_hSessionKey,
IntPtr.Zero,
true,
0,
encryptedData,
ref dataLength,
encryptedData.Length);
CheckStatus(ret);
}
// make sure we copy only appropriate data
// dataLength will contain the length of the encrypted
// data buffer
byte[] result = new byte[dataLength];
Array.Copy(encryptedData, 0, result, 0, dataLength);
return result;
}
/// <summary>
/// Decrypt the specified buffer.
/// </summary>
/// <param name="data">Data to decrypt.</param>
/// <returns>Decrypted buffer.</returns>
internal byte[] DecryptWithSessionKey(byte[] data)
{
// first make a copy of the original data.This is needed
// as CryptDecrypt uses the same buffer to write the decrypted data
// into.
byte[] decryptedData = new byte[data.Length];
Array.Copy(data, 0, decryptedData, 0, data.Length);
int dataLength = decryptedData.Length;
bool ret = PSCryptoNativeUtils.CryptDecrypt(_hSessionKey,
IntPtr.Zero,
true,
0,
decryptedData,
ref dataLength);
// if decryption failed, then dataLength will contain the length
// of buffer needed to store the decrypted contents. Recreate
// the buffer
if (false == ret)
{
decryptedData = new byte[dataLength];
Array.Copy(data, 0, decryptedData, 0, data.Length);
ret = PSCryptoNativeUtils.CryptDecrypt(_hSessionKey,
IntPtr.Zero,
true,
0,
decryptedData,
ref dataLength);
CheckStatus(ret);
}
// make sure we copy only appropriate data
// dataLength will contain the length of the encrypted
// data buffer
byte[] result = new byte[dataLength];
Array.Copy(decryptedData, 0, result, 0, dataLength);
// zero out the decryptedData buffer
for (int i = 0; i < decryptedData.Length; i++)
{
decryptedData[i] = 0;
}
return result;
}
/// <summary>
/// Generates key pair in a thread safe manner
/// the first time when required.
/// </summary>
internal void GenerateKeyPair()
{
if (!s_keyPairGenerated)
{
lock (s_syncObject)
{
if (!s_keyPairGenerated)
{
s_hStaticProv = new PSSafeCryptProvHandle();
// We need PROV_RSA_AES to support AES-256 symmetric key
// encryption. PROV_RSA_FULL supports only RC2 and RC4
bool ret = PSCryptoNativeUtils.CryptAcquireContext(ref s_hStaticProv,
null,
null,
PSCryptoNativeUtils.PROV_RSA_AES,
PSCryptoNativeUtils.CRYPT_VERIFYCONTEXT);
CheckStatus(ret);
s_hStaticRSAKey = new PSSafeCryptKey();
ret = PSCryptoNativeUtils.CryptGenKey(s_hStaticProv,
PSCryptoNativeUtils.AT_KEYEXCHANGE,
0x08000000 | PSCryptoNativeUtils.CRYPT_EXPORTABLE, // key length -> 2048
ref s_hStaticRSAKey);
CheckStatus(ret);
// key needs to be generated once
s_keyPairGenerated = true;
}
}
}
_hProv = s_hStaticProv;
_hRSAKey = s_hStaticRSAKey;
}
/// <summary>
/// Indicates if a key exchange is complete
/// and this provider can encrypt.
/// </summary>
internal bool CanEncrypt
{
get
{
return _canEncrypt;
}
set
{
_canEncrypt = value;
}
}
#endregion Internal Methods
#region Internal Static Methods
/// <summary>
/// Returns a crypto service provider for use in the
/// client. This will reuse the key that has been
/// generated.
/// </summary>
/// <returns>Crypto service provider for
/// the client side.</returns>
internal static PSRSACryptoServiceProvider GetRSACryptoServiceProviderForClient()
{
PSRSACryptoServiceProvider cryptoProvider = new PSRSACryptoServiceProvider(false);
// set the handles for provider and rsa key
cryptoProvider._hProv = s_hStaticProv;
cryptoProvider._hRSAKey = s_hStaticRSAKey;
return cryptoProvider;
}
/// <summary>
/// Returns a crypto service provider for use in the
/// server. This will not generate a key pair.
/// </summary>
/// <returns>Crypto service provider for
/// the server side.</returns>
internal static PSRSACryptoServiceProvider GetRSACryptoServiceProviderForServer()
{
PSRSACryptoServiceProvider cryptoProvider = new PSRSACryptoServiceProvider(true);
return cryptoProvider;
}
#endregion Internal Static Methods
#region Private Methods
/// <summary>
/// Checks the status of a call, if it had resulted in an error
/// then obtains the last error, wraps it in an exception and
/// throws the same.
/// </summary>
/// <param name="value">Value to examine.</param>
private void CheckStatus(bool value)
{
if (value)
{
return;
}
uint errorCode = PSCryptoNativeUtils.GetLastError();
StringBuilder errorMessage = new StringBuilder(new ComponentModel.Win32Exception(unchecked((int)errorCode)).Message);
throw new PSCryptoException(errorCode, errorMessage);
}
#endregion Private Methods
#region IDisposable
/// <summary>
/// Dispose resources.
/// </summary>
public void Dispose()
{
Dispose(true);
System.GC.SuppressFinalize(this);
}
// [SecurityPermission(SecurityAction.Demand, UnmanagedCode=true)]
protected void Dispose(bool disposing)
{
if (disposing)
{
if (_hSessionKey != null)
{
if (!_hSessionKey.IsInvalid)
{
_hSessionKey.Dispose();
}
_hSessionKey = null;
}
// we need to dismiss the provider and key
// only if the static members are not allocated
// since otherwise, these are just references
// to the static members
if (s_hStaticRSAKey == null)
{
if (_hRSAKey != null)
{
if (!_hRSAKey.IsInvalid)
{
_hRSAKey.Dispose();
}
_hRSAKey = null;
}
}
if (s_hStaticProv == null)
{
if (_hProv != null)
{
if (!_hProv.IsInvalid)
{
_hProv.Dispose();
}
_hProv = null;
}
}
}
}
/// <summary>
/// Destructor.
/// </summary>
~PSRSACryptoServiceProvider()
{
// When Dispose() is called, GC.SuppressFinalize()
// is called and therefore this finalizer will not
// be invoked. Hence this is run only on process
// shutdown
Dispose(true);
}
#endregion IDisposable
}
/// <summary>
/// Helper for exchanging keys and encrypting/decrypting
/// secure strings for serialization in remoting.
/// </summary>
internal abstract class PSRemotingCryptoHelper : IDisposable
{
#region Protected Members
/// <summary>
/// Crypto provider which will be used for importing remote
/// public key as well as generating a session key, exporting
/// it and performing symmetric key operations using the
/// session key.
/// </summary>
protected PSRSACryptoServiceProvider _rsaCryptoProvider;
/// <summary>
/// Key exchange has been completed and both keys
/// available.
/// </summary>
protected ManualResetEvent _keyExchangeCompleted = new ManualResetEvent(false);
/// <summary>
/// Object for synchronizing key exchange.
/// </summary>
protected object syncObject = new object();
private bool _keyExchangeStarted = false;
/// <summary>
/// </summary>
protected void RunKeyExchangeIfRequired()
{
Dbg.Assert(Session != null, "data structure handler not set");
if (!_rsaCryptoProvider.CanEncrypt)
{
try
{
lock (syncObject)
{
if (!_rsaCryptoProvider.CanEncrypt)
{
if (!_keyExchangeStarted)
{
_keyExchangeStarted = true;
_keyExchangeCompleted.Reset();
Session.StartKeyExchange();
}
}
}
}
finally
{
// for whatever reason if StartKeyExchange()
// throws an exception it should reset the
// wait handle, so it should pass this wait
// if it doesn't do so, its a bug
_keyExchangeCompleted.WaitOne();
}
}
}
/// <summary>
/// Core logic to encrypt a string. Assumes session key is already generated.
/// </summary>
/// <param name="secureString">
/// secure string to be encrypted
/// </param>
/// <returns></returns>
protected string EncryptSecureStringCore(SecureString secureString)
{
string encryptedDataAsString = null;
if (_rsaCryptoProvider.CanEncrypt)
{
IntPtr ptr = Marshal.SecureStringToCoTaskMemUnicode(secureString);
if (ptr != IntPtr.Zero)
{
byte[] data = new byte[secureString.Length * 2];
for (int i = 0; i < data.Length; i++)
{
data[i] = Marshal.ReadByte(ptr, i);
}
Marshal.ZeroFreeCoTaskMemUnicode(ptr);
try
{
byte[] encryptedData = _rsaCryptoProvider.EncryptWithSessionKey(data);
encryptedDataAsString = Convert.ToBase64String(encryptedData);
}
finally
{
for (int j = 0; j < data.Length; j++)
{
data[j] = 0;
}
}
}
}
else
{
throw new PSCryptoException(SecuritySupportStrings.CannotEncryptSecureString);
}
return encryptedDataAsString;
}
/// <summary>
/// Core logic to decrypt a secure string. Assumes session key is already available.
/// </summary>
/// <param name="encryptedString">
/// encrypted string to be decrypted
/// </param>
/// <returns></returns>
protected SecureString DecryptSecureStringCore(string encryptedString)
{
// removing an earlier assert from here. It is
// possible to encrypt and decrypt empty
// secure strings
SecureString secureString = null;
// before you can decrypt a key exchange should have
// happened successfully
if (_rsaCryptoProvider.CanEncrypt)
{
byte[] data = null;
try
{
data = Convert.FromBase64String(encryptedString);
}
catch (FormatException)
{
// do nothing
// this catch is to ensure that the exception doesn't
// go unhandled leading to a crash
throw new PSCryptoException();
}
if (data != null)
{
byte[] decryptedData = _rsaCryptoProvider.DecryptWithSessionKey(data);
secureString = new SecureString();
UInt16 value = 0;
try
{
for (int i = 0; i < decryptedData.Length; i += 2)
{
value = (UInt16)(decryptedData[i] + (UInt16)(decryptedData[i + 1] << 8));
secureString.AppendChar((char)value);
value = 0;
}
}
finally
{
// if there was an exception for whatever reason,
// clear the last value store in Value
value = 0;
// zero out the contents
for (int i = 0; i < decryptedData.Length; i += 2)
{
decryptedData[i] = 0;
decryptedData[i + 1] = 0;
}
}
}
}
else
{
Dbg.Assert(false, "Session key not available to decrypt");
}
return secureString;
}
#endregion Protected Members
#region Internal Methods
/// <summary>
/// Encrypt a secure string.
/// </summary>
/// <param name="secureString">Secure string to encrypt.</param>
/// <returns>Encrypted string.</returns>
/// <remarks>This method zeroes out all interim buffers used</remarks>
internal abstract string EncryptSecureString(SecureString secureString);
/// <summary>
/// Decrypt a string and construct a secure string from its
/// contents.
/// </summary>
/// <param name="encryptedString">Encrypted string.</param>
/// <returns>Secure string object.</returns>
/// <remarks>This method zeroes out any interim buffers used</remarks>
internal abstract SecureString DecryptSecureString(string encryptedString);
/// <summary>
/// Represents the session to be used for requesting public key.
/// </summary>
internal abstract RemoteSession Session { get; set; }
/// <summary>
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// </summary>
/// <param name="disposing"></param>
public void Dispose(bool disposing)
{
if (disposing)
{
if (_rsaCryptoProvider != null)
{
_rsaCryptoProvider.Dispose();
}
_rsaCryptoProvider = null;
_keyExchangeCompleted.Dispose();
}
}
/// <summary>
/// Resets the wait for key exchange.
/// </summary>
internal void CompleteKeyExchange()
{
_keyExchangeCompleted.Set();
}
#endregion Internal Methods
}
/// <summary>
/// Helper for exchanging keys and encrypting/decrypting
/// secure strings for serialization in remoting.
/// </summary>
internal class PSRemotingCryptoHelperServer : PSRemotingCryptoHelper
{
#region Private Members
/// <summary>
/// This is the instance of runspace pool data structure handler
/// to use for negotiations.
/// </summary>
private RemoteSession _session;
#endregion Private Members
#region Constructors
/// <summary>
/// Creates the encryption provider, but generates no key.
/// The key will be imported later.
/// </summary>
internal PSRemotingCryptoHelperServer()
{
#if UNIX
_rsaCryptoProvider = null;
#else
_rsaCryptoProvider = PSRSACryptoServiceProvider.GetRSACryptoServiceProviderForServer();
#endif
}
#endregion Constructors
#region Internal Methods
internal override string EncryptSecureString(SecureString secureString)
{
ServerRemoteSession session = Session as ServerRemoteSession;
// session!=null check required for DRTs TestEncryptSecureString* entries in CryptoUtilsTest/UTUtils.dll
// for newer clients, server will never initiate key exchange.
// for server, just the session key is required to encrypt/decrypt anything
if ((session != null) && (session.Context.ClientCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM))
{
_rsaCryptoProvider.GenerateSessionKey();
}
else // older clients
{
RunKeyExchangeIfRequired();
}
return EncryptSecureStringCore(secureString);
}
internal override SecureString DecryptSecureString(string encryptedString)
{
RunKeyExchangeIfRequired();
return DecryptSecureStringCore(encryptedString);
}
/// <summary>
/// Imports a public key from its base64 encoded string representation.
/// </summary>
/// <param name="publicKeyAsString">Public key in its string representation.</param>
/// <returns>True on success.</returns>
internal bool ImportRemotePublicKey(string publicKeyAsString)
{
Dbg.Assert(!string.IsNullOrEmpty(publicKeyAsString), "public key passed in cannot be null");
// generate the crypto provider to use for encryption
// _rsaCryptoProvider = GenerateCryptoServiceProvider(false);
try
{
_rsaCryptoProvider.ImportPublicKeyFromBase64EncodedString(publicKeyAsString);
}
catch (PSCryptoException)
{
return false;
}
return true;
}
/// <summary>
/// Represents the session to be used for requesting public key.
/// </summary>
internal override RemoteSession Session
{
get
{
return _session;
}
set
{
_session = value;
}
}
/// <summary>
/// </summary>
/// <param name="encryptedSessionKey"></param>
/// <returns></returns>
internal bool ExportEncryptedSessionKey(out string encryptedSessionKey)
{
try
{
encryptedSessionKey = _rsaCryptoProvider.SafeExportSessionKey();
}
catch (PSCryptoException)
{
encryptedSessionKey = string.Empty;
return false;
}
return true;
}
/// <summary>
/// Gets a helper with a test session.
/// </summary>
/// <returns>Helper for testing.</returns>
/// <remarks>To be used only for testing</remarks>
internal static PSRemotingCryptoHelperServer GetTestRemotingCryptHelperServer()
{
PSRemotingCryptoHelperServer helper = new PSRemotingCryptoHelperServer();
helper.Session = new TestHelperSession();
return helper;
}
#endregion Internal Methods
}
/// <summary>
/// Helper for exchanging keys and encrypting/decrypting
/// secure strings for serialization in remoting.
/// </summary>
internal class PSRemotingCryptoHelperClient : PSRemotingCryptoHelper
{
#region Private Members
#endregion Private Members
#region Constructors
/// <summary>
/// Creates the encryption provider, but generates no key.
/// The key will be imported later.
/// </summary>
internal PSRemotingCryptoHelperClient()
{
_rsaCryptoProvider = PSRSACryptoServiceProvider.GetRSACryptoServiceProviderForClient();
// _session = new RemoteSession();
}
#endregion Constructors
#region Protected Methods
#endregion Protected Methods
#region Internal Methods
internal override string EncryptSecureString(SecureString secureString)
{
RunKeyExchangeIfRequired();
return EncryptSecureStringCore(secureString);
}
internal override SecureString DecryptSecureString(string encryptedString)
{
RunKeyExchangeIfRequired();
return DecryptSecureStringCore(encryptedString);
}
/// <summary>
/// Export the public key as a base64 encoded string.
/// </summary>
/// <param name="publicKeyAsString">on execution will contain
/// the public key as string</param>
/// <returns>True on success.</returns>
internal bool ExportLocalPublicKey(out string publicKeyAsString)
{
// generate keys - the method already takes of creating
// only when its not already created
try
{
_rsaCryptoProvider.GenerateKeyPair();
}
catch (PSCryptoException)
{
throw;
// the caller has to ensure that they
// complete the key exchange process
}
try
{
publicKeyAsString = _rsaCryptoProvider.GetPublicKeyAsBase64EncodedString();
}
catch (PSCryptoException)
{
publicKeyAsString = string.Empty;
return false;
}
return true;
}
/// <summary>
/// </summary>
/// <param name="encryptedSessionKey"></param>
/// <returns></returns>
internal bool ImportEncryptedSessionKey(string encryptedSessionKey)
{
Dbg.Assert(!string.IsNullOrEmpty(encryptedSessionKey), "encrypted session key passed in cannot be null");
try
{
_rsaCryptoProvider.ImportSessionKeyFromBase64EncodedString(encryptedSessionKey);
}
catch (PSCryptoException)
{
return false;
}
return true;
}
/// <summary>
/// Represents the session to be used for requesting public key.
/// </summary>
internal override RemoteSession Session { get; set; }
/// <summary>
/// Gets a helper with a test session.
/// </summary>
/// <returns>Helper for testing.</returns>
/// <remarks>To be used only for testing</remarks>
internal static PSRemotingCryptoHelperClient GetTestRemotingCryptHelperClient()
{
PSRemotingCryptoHelperClient helper = new PSRemotingCryptoHelperClient();
helper.Session = new TestHelperSession();
return helper;
}
#endregion Internal Methods
}
#region TestHelpers
internal class TestHelperSession : RemoteSession
{
internal override void StartKeyExchange()
{
// intentionally left blank
}
internal override RemotingDestination MySelf
{
get
{
return RemotingDestination.InvalidDestination;
}
}
internal override void CompleteKeyExchange()
{
// intentionally left blank
}
}
#endregion TestHelpers
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
internal const bool CheckOperationsRequiresSetHandle = true;
internal ThreadPoolBoundHandle _threadPoolBinding;
internal static string GetPipePath(string serverName, string pipeName)
{
string normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName);
if (String.Equals(normalizedPipePath, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentOutOfRangeException("pipeName", SR.ArgumentOutOfRange_AnonymousReserved);
}
return normalizedPipePath;
}
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary>
/// <param name="safePipeHandle">The handle to validate.</param>
internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle)
{
// Check that this handle is infact a handle to a pipe.
if (Interop.mincore.GetFileType(safePipeHandle) != Interop.mincore.FileTypes.FILE_TYPE_PIPE)
{
throw new IOException(SR.IO_InvalidPipeHandle);
}
}
/// <summary>Initializes the handle to be used asynchronously.</summary>
/// <param name="handle">The handle.</param>
private void InitializeAsyncHandle(SafePipeHandle handle)
{
// If the handle is of async type, bind the handle to the ThreadPool so that we can use
// the async operations (it's needed so that our native callbacks get called).
_threadPoolBinding = ThreadPoolBoundHandle.BindHandle(handle);
}
private void UninitializeAsyncHandle()
{
if (_threadPoolBinding != null)
_threadPoolBinding.Dispose();
}
[SecurityCritical]
private unsafe int ReadCore(byte[] buffer, int offset, int count)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanRead, "can't read");
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
if (_isAsync)
{
IAsyncResult result = BeginReadCore(buffer, offset, count, null, null);
return EndRead(result);
}
int errorCode = 0;
int r = ReadFileNative(_handle, buffer, offset, count, null, out errorCode);
if (r == -1)
{
// If the other side has broken the connection, set state to Broken and return 0
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED)
{
State = PipeState.Broken;
r = 0;
}
else
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode, String.Empty);
}
}
_isMessageComplete = (errorCode != Interop.mincore.Errors.ERROR_MORE_DATA);
Debug.Assert(r >= 0, "PipeStream's ReadCore is likely broken.");
return r;
}
[SecuritySafeCritical]
private Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ReadWriteAsyncParams state = new ReadWriteAsyncParams(buffer, offset, count, cancellationToken);
return Task.Factory.FromAsync<int>(BeginRead, EndRead, state);
}
[SecurityCritical]
private unsafe void WriteCore(byte[] buffer, int offset, int count)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanWrite, "can't write");
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
if (_isAsync)
{
IAsyncResult result = BeginWriteCore(buffer, offset, count, null, null);
EndWrite(result);
return;
}
int errorCode = 0;
int r = WriteFileNative(_handle, buffer, offset, count, null, out errorCode);
if (r == -1)
{
WinIOError(errorCode);
}
Debug.Assert(r >= 0, "PipeStream's WriteCore is likely broken.");
return;
}
[SecuritySafeCritical]
private Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
ReadWriteAsyncParams state = new ReadWriteAsyncParams(buffer, offset, count, cancellationToken);
return Task.Factory.FromAsync(BeginWrite, EndWrite, state);
}
// Blocks until the other end of the pipe has read in all written buffer.
[SecurityCritical]
public void WaitForPipeDrain()
{
CheckWriteOperations();
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
// Block until other end of the pipe has read everything.
if (!Interop.mincore.FlushFileBuffers(_handle))
{
WinIOError(Marshal.GetLastWin32Error());
}
}
// Gets the transmission mode for the pipe. This is virtual so that subclassing types can
// override this in cases where only one mode is legal (such as anonymous pipes)
public virtual PipeTransmissionMode TransmissionMode
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (_isFromExistingHandle)
{
int pipeFlags;
if (!Interop.mincore.GetNamedPipeInfo(_handle, out pipeFlags, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero))
{
WinIOError(Marshal.GetLastWin32Error());
}
if ((pipeFlags & Interop.mincore.PipeOptions.PIPE_TYPE_MESSAGE) != 0)
{
return PipeTransmissionMode.Message;
}
else
{
return PipeTransmissionMode.Byte;
}
}
else
{
return _transmissionMode;
}
}
}
// Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read
// access. If that passes, call to GetNamedPipeInfo will succeed.
public virtual int InBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
get
{
CheckPipePropertyOperations();
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
int inBufferSize;
if (!Interop.mincore.GetNamedPipeInfo(_handle, IntPtr.Zero, IntPtr.Zero, out inBufferSize, IntPtr.Zero))
{
WinIOError(Marshal.GetLastWin32Error());
}
return inBufferSize;
}
}
// Gets the buffer size in the outbound direction for the pipe. This uses cached version
// if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe.
// However, returning cached is good fallback, especially if user specified a value in
// the ctor.
public virtual int OutBufferSize
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
CheckPipePropertyOperations();
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
int outBufferSize;
// Use cached value if direction is out; otherwise get fresh version
if (_pipeDirection == PipeDirection.Out)
{
outBufferSize = _outBufferSize;
}
else if (!Interop.mincore.GetNamedPipeInfo(_handle, IntPtr.Zero, out outBufferSize,
IntPtr.Zero, IntPtr.Zero))
{
WinIOError(Marshal.GetLastWin32Error());
}
return outBufferSize;
}
}
public virtual PipeTransmissionMode ReadMode
{
[SecurityCritical]
get
{
CheckPipePropertyOperations();
// get fresh value if it could be stale
if (_isFromExistingHandle || IsHandleExposed)
{
UpdateReadMode();
}
return _readMode;
}
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
set
{
// Nothing fancy here. This is just a wrapper around the Win32 API. Note, that NamedPipeServerStream
// and the AnonymousPipeStreams override this.
CheckPipePropertyOperations();
if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
unsafe
{
int pipeReadType = (int)value << 1;
if (!Interop.mincore.SetNamedPipeHandleState(_handle, &pipeReadType, IntPtr.Zero, IntPtr.Zero))
{
WinIOError(Marshal.GetLastWin32Error());
}
else
{
_readMode = value;
}
}
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
private class ReadWriteAsyncParams
{
public ReadWriteAsyncParams() { }
public ReadWriteAsyncParams(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
this.Buffer = buffer;
this.Offset = offset;
this.Count = count;
this.CancellationHelper = cancellationToken.CanBeCanceled ? new IOCancellationHelper(cancellationToken) : null;
}
public byte[] Buffer { get; set; }
public int Offset { get; set; }
public int Count { get; set; }
public IOCancellationHelper CancellationHelper { get; private set; }
}
[SecurityCritical]
private unsafe static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(PipeStream.AsyncPSCallback);
[SecurityCritical]
private IAsyncResult BeginWrite(AsyncCallback callback, Object state)
{
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
Debug.Assert(readWriteParams != null);
byte[] buffer = readWriteParams.Buffer;
int offset = readWriteParams.Offset;
int count = readWriteParams.Count;
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!CanWrite)
{
throw __Error.GetWriteNotSupported();
}
CheckWriteOperations();
if (!_isAsync)
{
return _streamAsyncHelper.BeginWrite(buffer, offset, count, callback, state);
}
else
{
return BeginWriteCore(buffer, offset, count, callback, state);
}
}
[SecurityCritical]
unsafe private PipeStreamAsyncResult BeginWriteCore(byte[] buffer, int offset, int count,
AsyncCallback callback, Object state)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanWrite, "can't write");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert(_isAsync, "BeginWriteCore doesn't work on synchronous file streams!");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
// Create and store async stream class library specific data in the async result
PipeStreamAsyncResult asyncResult = new PipeStreamAsyncResult();
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
asyncResult._isWrite = true;
asyncResult._handle = _handle;
// fixed doesn't work well with zero length arrays. Set the zero-byte flag in case
// caller needs to do any cleanup
if (buffer.Length == 0)
{
//intOverlapped->InternalLow = IntPtr.Zero;
// EndRead will free the Overlapped struct
asyncResult.CallUserCallback();
}
else
{
// For Synchronous IO, I could go with either a userCallback and using the managed
// Monitor class, or I could create a handle and wait on it.
ManualResetEvent waitHandle = new ManualResetEvent(false);
asyncResult._waitHandle = waitHandle;
NativeOverlapped* intOverlapped = _threadPoolBinding.AllocateNativeOverlapped(s_IOCallback, asyncResult, buffer);
asyncResult._overlapped = intOverlapped;
int errorCode = 0;
// Queue an async WriteFile operation and pass in a packed overlapped
int r = WriteFileNative(_handle, buffer, offset, count, intOverlapped, out errorCode);
// WriteFile, the OS version, will return 0 on failure, but this WriteFileNative
// wrapper returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer written back from this
// call when using overlapped structures! You must not pass in a non-null
// lpNumBytesWritten to WriteFile when using overlapped structures! This is by design
// NT behavior.
if (r == -1 && errorCode != Interop.mincore.Errors.ERROR_IO_PENDING)
{
// Clean up
if (intOverlapped != null) _threadPoolBinding.FreeNativeOverlapped(intOverlapped);
WinIOError(errorCode);
}
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
if (readWriteParams != null)
{
if (readWriteParams.CancellationHelper != null)
{
readWriteParams.CancellationHelper.AllowCancellation(_handle, intOverlapped);
}
}
}
return asyncResult;
}
[SecurityCritical]
private unsafe void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
if (!_isAsync)
{
_streamAsyncHelper.EndWrite(asyncResult);
return;
}
PipeStreamAsyncResult afsar = asyncResult as PipeStreamAsyncResult;
if (afsar == null || !afsar._isWrite)
{
throw __Error.GetWrongAsyncResult();
}
// Ensure we can't get into any races by doing an interlocked
// CompareExchange here. Avoids corrupting memory via freeing the
// NativeOverlapped class or GCHandle twice. --
if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
{
throw __Error.GetEndWriteCalledTwice();
}
ReadWriteAsyncParams readWriteParams = afsar.AsyncState as ReadWriteAsyncParams;
IOCancellationHelper cancellationHelper = null;
if (readWriteParams != null)
{
cancellationHelper = readWriteParams.CancellationHelper;
if (cancellationHelper != null)
{
cancellationHelper.SetOperationCompleted();
}
}
// Obtain the WaitHandle, but don't use public property in case we
// delay initialize the manual reset event in the future.
WaitHandle wh = afsar._waitHandle;
if (wh != null)
{
// We must block to ensure that AsyncPSCallback has completed,
// and we should close the WaitHandle in here. AsyncPSCallback
// and the hand-ported imitation version in COMThreadPool.cpp
// are the only places that set this event.
using (wh)
{
wh.WaitOne();
Debug.Assert(afsar._isComplete == true, "PipeStream::EndWrite - AsyncPSCallback didn't set _isComplete to true!");
}
}
// Free memory & GC handles.
NativeOverlapped* overlappedPtr = afsar._overlapped;
if (overlappedPtr != null)
{
_threadPoolBinding.FreeNativeOverlapped(overlappedPtr);
}
// Now check for any error during the write.
if (afsar._errorCode != 0)
{
if (afsar._errorCode == Interop.mincore.Errors.ERROR_OPERATION_ABORTED)
{
if (cancellationHelper != null)
{
cancellationHelper.ThrowIOOperationAborted();
}
}
WinIOError(afsar._errorCode);
}
// Number of buffer written is afsar._numBytes.
return;
}
[SecurityCritical]
private unsafe int ReadFileNative(SafePipeHandle handle, byte[] buffer, int offset, int count,
NativeOverlapped* overlapped, out int errorCode)
{
Debug.Assert(handle != null, "handle is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to ReadFileNative.");
Debug.Assert(buffer.Length - offset >= count, "offset + count >= buffer length");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int r = 0;
int numBytesRead = 0;
fixed (byte* p = buffer)
{
if (_isAsync)
{
r = Interop.mincore.ReadFile(handle, p + offset, count, IntPtr.Zero, overlapped);
}
else
{
r = Interop.mincore.ReadFile(handle, p + offset, count, out numBytesRead, IntPtr.Zero);
}
}
if (r == 0)
{
// We should never silently swallow an error here without some
// extra work. We must make sure that BeginReadCore won't return an
// IAsyncResult that will cause EndRead to block, since the OS won't
// call AsyncPSCallback for us.
errorCode = Marshal.GetLastWin32Error();
// In message mode, the ReadFile can inform us that there is more data to come.
if (errorCode == Interop.mincore.Errors.ERROR_MORE_DATA)
{
return numBytesRead;
}
return -1;
}
else
{
errorCode = 0;
}
return numBytesRead;
}
[SecurityCritical]
private unsafe int WriteFileNative(SafePipeHandle handle, byte[] buffer, int offset, int count,
NativeOverlapped* overlapped, out int errorCode)
{
Debug.Assert(handle != null, "handle is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to WriteFileNative.");
Debug.Assert(buffer.Length - offset >= count, "offset + count >= buffer length");
// You can't use the fixed statement on an array of length 0. Note that async callers
// check to avoid calling this first, so they can call user's callback
if (buffer.Length == 0)
{
errorCode = 0;
return 0;
}
int numBytesWritten = 0;
int r = 0;
fixed (byte* p = buffer)
{
if (_isAsync)
{
r = Interop.mincore.WriteFile(handle, p + offset, count, IntPtr.Zero, overlapped);
}
else
{
r = Interop.mincore.WriteFile(handle, p + offset, count, out numBytesWritten, IntPtr.Zero);
}
}
if (r == 0)
{
// We should never silently swallow an error here without some
// extra work. We must make sure that BeginWriteCore won't return an
// IAsyncResult that will cause EndWrite to block, since the OS won't
// call AsyncPSCallback for us.
errorCode = Marshal.GetLastWin32Error();
return -1;
}
else
{
errorCode = 0;
}
return numBytesWritten;
}
[SecurityCritical]
private IAsyncResult BeginRead(AsyncCallback callback, Object state)
{
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
Debug.Assert(readWriteParams != null);
byte[] buffer = readWriteParams.Buffer;
int offset = readWriteParams.Offset;
int count = readWriteParams.Count;
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!CanRead)
{
throw __Error.GetReadNotSupported();
}
CheckReadOperations();
if (!_isAsync)
{
// special case when this is called for sync broken pipes because otherwise Stream's
// Begin/EndRead hang. Reads return 0 bytes in this case so we can call the user's
// callback immediately
if (_state == PipeState.Broken)
{
PipeStreamAsyncResult asyncResult = new PipeStreamAsyncResult();
asyncResult._handle = _handle;
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
asyncResult._isWrite = false;
asyncResult.CallUserCallback();
return asyncResult;
}
else
{
return _streamAsyncHelper.BeginRead(buffer, offset, count, callback, state);
}
}
else
{
return BeginReadCore(buffer, offset, count, callback, state);
}
}
[SecurityCritical]
unsafe private PipeStreamAsyncResult BeginReadCore(byte[] buffer, int offset, int count,
AsyncCallback callback, Object state)
{
Debug.Assert(_handle != null, "_handle is null");
Debug.Assert(!_handle.IsClosed, "_handle is closed");
Debug.Assert(CanRead, "can't read");
Debug.Assert(buffer != null, "buffer == null");
Debug.Assert(_isAsync, "BeginReadCore doesn't work on synchronous file streams!");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
// Create and store async stream class library specific data in the async result
PipeStreamAsyncResult asyncResult = new PipeStreamAsyncResult();
asyncResult._handle = _handle;
asyncResult._userCallback = callback;
asyncResult._userStateObject = state;
asyncResult._isWrite = false;
// handle zero-length buffers separately; fixed keyword ReadFileNative doesn't like
// 0-length buffers. Call user callback and we're done
if (buffer.Length == 0)
{
asyncResult.CallUserCallback();
}
else
{
// For Synchronous IO, I could go with either a userCallback and using
// the managed Monitor class, or I could create a handle and wait on it.
ManualResetEvent waitHandle = new ManualResetEvent(false);
asyncResult._waitHandle = waitHandle;
NativeOverlapped* intOverlapped = _threadPoolBinding.AllocateNativeOverlapped(s_IOCallback, asyncResult, buffer);
asyncResult._overlapped = intOverlapped;
// Queue an async ReadFile operation and pass in a packed overlapped
int errorCode = 0;
int r = ReadFileNative(_handle, buffer, offset, count, intOverlapped, out errorCode);
// ReadFile, the OS version, will return 0 on failure, but this ReadFileNative wrapper
// returns -1. This will return the following:
// - On error, r==-1.
// - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING
// - On async requests that completed sequentially, r==0
//
// You will NEVER RELIABLY be able to get the number of buffer read back from this call
// when using overlapped structures! You must not pass in a non-null lpNumBytesRead to
// ReadFile when using overlapped structures! This is by design NT behavior.
if (r == -1)
{
// One side has closed its handle or server disconnected. Set the state to Broken
// and do some cleanup work
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED)
{
State = PipeState.Broken;
// Clear the overlapped status bit for this special case. Failure to do so looks
// like we are freeing a pending overlapped.
intOverlapped->InternalLow = IntPtr.Zero;
// EndRead will free the Overlapped struct
asyncResult.CallUserCallback();
}
else if (errorCode != Interop.mincore.Errors.ERROR_IO_PENDING)
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
ReadWriteAsyncParams readWriteParams = state as ReadWriteAsyncParams;
if (readWriteParams != null)
{
if (readWriteParams.CancellationHelper != null)
{
readWriteParams.CancellationHelper.AllowCancellation(_handle, intOverlapped);
}
}
}
return asyncResult;
}
[SecurityCritical]
private unsafe int EndRead(IAsyncResult asyncResult)
{
// There are 3 significantly different IAsyncResults we'll accept
// here. One is from Stream::BeginRead. The other two are variations
// on our PipeStreamAsyncResult. One is from BeginReadCore,
// while the other is from the BeginRead buffering wrapper.
if (asyncResult == null)
{
throw new ArgumentNullException("asyncResult");
}
if (!_isAsync)
{
return _streamAsyncHelper.EndRead(asyncResult);
}
PipeStreamAsyncResult afsar = asyncResult as PipeStreamAsyncResult;
if (afsar == null || afsar._isWrite)
{
throw __Error.GetWrongAsyncResult();
}
// Ensure we can't get into any races by doing an interlocked
// CompareExchange here. Avoids corrupting memory via freeing the
// NativeOverlapped class or GCHandle twice.
if (1 == Interlocked.CompareExchange(ref afsar._EndXxxCalled, 1, 0))
{
throw __Error.GetEndReadCalledTwice();
}
ReadWriteAsyncParams readWriteParams = asyncResult.AsyncState as ReadWriteAsyncParams;
IOCancellationHelper cancellationHelper = null;
if (readWriteParams != null)
{
cancellationHelper = readWriteParams.CancellationHelper;
if (cancellationHelper != null)
{
readWriteParams.CancellationHelper.SetOperationCompleted();
}
}
// Obtain the WaitHandle, but don't use public property in case we
// delay initialize the manual reset event in the future.
WaitHandle wh = afsar._waitHandle;
if (wh != null)
{
// We must block to ensure that AsyncPSCallback has completed,
// and we should close the WaitHandle in here. AsyncPSCallback
// and the hand-ported imitation version in COMThreadPool.cpp
// are the only places that set this event.
using (wh)
{
wh.WaitOne();
Debug.Assert(afsar._isComplete == true,
"FileStream::EndRead - AsyncPSCallback didn't set _isComplete to true!");
}
}
// Free memory & GC handles.
NativeOverlapped* overlappedPtr = afsar._overlapped;
if (overlappedPtr != null)
{
_threadPoolBinding.FreeNativeOverlapped(overlappedPtr);
}
// Now check for any error during the read.
if (afsar._errorCode != 0)
{
if (afsar._errorCode == Interop.mincore.Errors.ERROR_OPERATION_ABORTED)
{
if (cancellationHelper != null)
{
cancellationHelper.ThrowIOOperationAborted();
}
}
WinIOError(afsar._errorCode);
}
// set message complete to true if the pipe is broken as well; need this to signal to readers
// to stop reading
_isMessageComplete = _state == PipeState.Broken ||
afsar._isMessageComplete;
return afsar._numBytes;
}
[SecurityCritical]
internal static Interop.mincore.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability)
{
Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES);
if ((inheritability & HandleInheritability.Inheritable) != 0)
{
secAttrs = new Interop.mincore.SECURITY_ATTRIBUTES();
secAttrs.nLength = (uint)Marshal.SizeOf(secAttrs);
secAttrs.bInheritHandle = true;
}
return secAttrs;
}
// When doing IO asynchronously (i.e., _isAsync==true), this callback is
// called by a free thread in the threadpool when the IO operation
// completes.
[SecurityCritical]
unsafe private static void AsyncPSCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
{
// Extract async result from overlapped
PipeStreamAsyncResult asyncResult = (PipeStreamAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped);
asyncResult._numBytes = (int)numBytes;
// Allow async read to finish
if (!asyncResult._isWrite)
{
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED ||
errorCode == Interop.mincore.Errors.ERROR_NO_DATA)
{
errorCode = 0;
numBytes = 0;
}
}
// For message type buffer.
if (errorCode == Interop.mincore.Errors.ERROR_MORE_DATA)
{
errorCode = 0;
asyncResult._isMessageComplete = false;
}
else
{
asyncResult._isMessageComplete = true;
}
asyncResult._errorCode = (int)errorCode;
// Call the user-provided callback. It can and often should
// call EndRead or EndWrite. There's no reason to use an async
// delegate here - we're already on a threadpool thread.
// IAsyncResult's completedSynchronously property must return
// false here, saying the user callback was called on another thread.
asyncResult._completedSynchronously = false;
asyncResult._isComplete = true;
// The OS does not signal this event. We must do it ourselves.
ManualResetEvent wh = asyncResult._waitHandle;
if (wh != null)
{
Debug.Assert(!wh.GetSafeWaitHandle().IsClosed, "ManualResetEvent already closed!");
bool r = wh.Set();
Debug.Assert(r, "ManualResetEvent::Set failed!");
if (!r)
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
AsyncCallback callback = asyncResult._userCallback;
if (callback != null)
{
callback(asyncResult);
}
}
/// <summary>
/// Determine pipe read mode from Win32
/// </summary>
[SecurityCritical]
private void UpdateReadMode()
{
int flags;
if (!Interop.mincore.GetNamedPipeHandleState(SafePipeHandle, out flags, IntPtr.Zero, IntPtr.Zero,
IntPtr.Zero, IntPtr.Zero, 0))
{
WinIOError(Marshal.GetLastWin32Error());
}
if ((flags & Interop.mincore.PipeOptions.PIPE_READMODE_MESSAGE) != 0)
{
_readMode = PipeTransmissionMode.Message;
}
else
{
_readMode = PipeTransmissionMode.Byte;
}
}
/// <summary>
/// Filter out all pipe related errors and do some cleanup before calling __Error.WinIOError.
/// </summary>
/// <param name="errorCode"></param>
[SecurityCritical]
internal void WinIOError(int errorCode)
{
if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE ||
errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED ||
errorCode == Interop.mincore.Errors.ERROR_NO_DATA
)
{
// Other side has broken the connection
_state = PipeState.Broken;
throw new IOException(SR.IO_PipeBroken, Win32Marshal.MakeHRFromErrorCode(errorCode));
}
else if (errorCode == Interop.mincore.Errors.ERROR_HANDLE_EOF)
{
throw __Error.GetEndOfFile();
}
else
{
// For invalid handles, detect the error and mark our handle
// as invalid to give slightly better error messages. Also
// help ensure we avoid handle recycling bugs.
if (errorCode == Interop.mincore.Errors.ERROR_INVALID_HANDLE)
{
_handle.SetHandleAsInvalid();
_state = PipeState.Broken;
}
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Globalization;
using Xunit;
public class Comparer_Objects
{
/////////////////////////////////////////////////////////////////////
// Begin Testing run
/////////////////////////////////////////////////////////////////////
public Boolean runTest()
{
int iCountTestcases = 0;
int iCountErrors = 0;
Object obj1, obj2;
int compRet;
Comparer comp;
//------------------- TEST 1
//[]use Comparer to compare two different objects
try
{
++iCountTestcases;
if (Comparer.Default.Compare(2, 1) <= 0)
{
++iCountErrors;
Console.WriteLine("Err_001a, compare should have returned positive integer");
}
}
catch (Exception ex)
{
++iCountErrors;
Console.WriteLine("Err_001b, Unexpected exception was thrown ex: " + ex.ToString());
}
//------------------- TEST 2
//[]use Comparer to compare two different objects
try
{
++iCountTestcases;
if (Comparer.Default.Compare(1, 2) >= 0)
{
++iCountErrors;
Console.WriteLine("Err_002a, compare should have returned negative integer");
}
}
catch (Exception ex)
{
++iCountErrors;
Console.WriteLine("Err_002b, Unexpected exception was thrown ex: " + ex.ToString());
}
//------------------- TEST 3
//[]use Comparer to compare two equal objects
try
{
++iCountTestcases;
if (Comparer.Default.Compare(1, 1) != 0)
{
++iCountErrors;
Console.WriteLine("Err_003a, compare should have returned 0 for equal objects");
}
}
catch (Exception ex)
{
++iCountErrors;
Console.WriteLine("Err_003b, Unexpected exception was thrown ex: " + ex.ToString());
}
//------------------- TEST 4
//[]use Comparer to compare a null object to a non null object
try
{
++iCountTestcases;
if (Comparer.Default.Compare(null, 1) >= 0)
{
++iCountErrors;
Console.WriteLine("Err_004a, a null object should be always less than something else");
}
}
catch (Exception ex)
{
++iCountErrors;
Console.WriteLine("Err_004b, Unexpected exception was thrown ex: " + ex.ToString());
}
//------------------- TEST 5
//[]use Comparer to compare an object to a null object
try
{
++iCountTestcases;
if (Comparer.Default.Compare(0, null) <= 0)
{
++iCountErrors;
Console.WriteLine("Err_005a, a null object should be always less than something else");
}
}
catch (Exception ex)
{
++iCountErrors;
Console.WriteLine("Err_005b, Unexpected exception was thrown ex: " + ex.ToString());
}
//------------------- TEST 6
//[]for two null objects comparer returns equal
try
{
++iCountTestcases;
if (Comparer.Default.Compare(null, null) != 0)
{
++iCountErrors;
Console.WriteLine("Err_006a, two nulls should be equal");
}
}
catch (Exception ex)
{
++iCountErrors;
Console.WriteLine("Err_006b, Unexpected exception was thrown ex: " + ex.ToString());
}
///////////////////////////////////// NOW PASS IN THINGS THAT CANNOT BE COMPARED /////////////////
//------------------- TEST 7
//[]compare two objects that do not implement IComparable
try
{
++iCountTestcases;
Comparer.Default.Compare(new Object(), new Object());
++iCountErrors;
Console.WriteLine("Err_007a, Expected exception ArgumentException was not thrown.");
}
catch (ArgumentException)
{ }
catch (Exception ex)
{
++iCountErrors;
Console.WriteLine("Err_007b, Unexpected exception was thrown ex: " + ex.ToString());
}
//------------------- TEST 8
//[]compare two objects that are not of the same type
try
{
++iCountTestcases;
Comparer.Default.Compare(1L, 1);
++iCountErrors;
Console.WriteLine("Err_008a, Expected exception ArgumentException was not thrown.");
}
catch (ArgumentException)
{ }
catch (Exception ex)
{
++iCountErrors;
Console.WriteLine("Err_008b, Unexpected exception was thrown ex: " + ex.ToString());
}
//------------------- TEST 9
//[]compare two objects that are not of the same type
try
{
++iCountTestcases;
Comparer.Default.Compare(1, 1L);
++iCountErrors;
Console.WriteLine("Err_009a, Expected exception ArgumentException was not thrown.");
}
catch (ArgumentException)
{ }
catch (Exception ex)
{
++iCountErrors;
Console.WriteLine("Err_009b, Unexpected exception was thrown ex: " + ex.ToString());
}
//[]Verify Compare where only one object implements IComparable
//and exception is expected from incompatible types
comp = Comparer.Default;
obj1 = "Aa";
obj2 = new Object();
try
{
compRet = comp.Compare(obj1, obj2);
iCountErrors++;
Console.WriteLine("Err_37035ashz! Expected exception to be thrown");
}
catch (ArgumentException) { }
catch (Exception e)
{
iCountErrors++;
Console.WriteLine("Err_3407pahs! Unexpected exception thrown {0}", e);
}
try
{
compRet = comp.Compare(obj2, obj1);
iCountErrors++;
Console.WriteLine("Err_0777paya! Expected exception to be thrown");
}
catch (ArgumentException) { }
catch (Exception e)
{
iCountErrors++;
Console.WriteLine("Err_73543aha! Unexpected exception thrown {0}", e);
}
//[]Verify Compare where neither object implements IComparable
comp = Comparer.Default;
obj1 = new Object();
obj2 = new Object();
try
{
compRet = comp.Compare(obj1, obj2);
iCountErrors++;
Console.WriteLine("Err_22435asps! Expected exception to be thrown");
}
catch (ArgumentException) { }
catch (Exception e)
{
iCountErrors++;
Console.WriteLine("Err_5649asdh! Unexpected exception thrown {0}", e);
}
try
{
compRet = comp.Compare(obj2, obj1);
iCountErrors++;
Console.WriteLine("Err_9879nmmj! Expected exception to be thrown");
}
catch (ArgumentException) { }
catch (Exception e)
{
iCountErrors++;
Console.WriteLine("Err_9881qa! Unexpected exception thrown {0}", e);
}
//[]Verify Compare where only one object implements IComparable
//and it will handle the conversion
comp = Comparer.Default;
obj1 = new Foo(5);
obj2 = new Bar(5);
if (0 != comp.Compare(obj1, obj2))
{
iCountErrors++;
Console.WriteLine("Err_3073ahsk! Expected Compare to return 0 Compare(obj1, obj2)={0}, Compare(obj2, obj1)={1}",
comp.Compare(obj1, obj2), comp.Compare(obj2, obj1));
}
obj1 = new Foo(1);
obj2 = new Bar(2);
if (0 <= comp.Compare(obj1, obj2))
{
iCountErrors++;
Console.WriteLine("Err_8922ayps! Expected Compare to return -1 Compare(obj1, obj2)={0}, Compare(obj2, obj1)={1}",
comp.Compare(obj1, obj2), comp.Compare(obj2, obj1));
}
if (iCountErrors == 0)
{
return true;
}
else
{
Console.WriteLine("Fail! iCountErrors=" + iCountErrors.ToString());
return false;
}
}
[Fact]
public static void ExecuteComparer_Objects()
{
var runClass = new Comparer_Objects();
Boolean bResult = runClass.runTest();
Assert.True(bResult);
}
}
public class Foo : IComparable
{
public int Data;
public Foo(int i)
{
Data = i;
}
public int CompareTo(Object o)
{
if (o is Foo)
{
return Data.CompareTo(((Foo)o).Data);
}
else if (o is Bar)
{
return Data.CompareTo(((Bar)o).Data);
}
throw new ArgumentException("Object is not a Foo or a Bar");
}
}
public class Bar
{
public int Data;
public Bar(int i)
{
Data = i;
}
}
| |
// 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.Runtime.InteropServices;
namespace System.Threading
{
//
// Implementation of ThreadPoolBoundHandle that sits on top of the CLR's ThreadPool and Overlapped infrastructure
//
/// <summary>
/// Represents an I/O handle that is bound to the system thread pool and enables low-level
/// components to receive notifications for asynchronous I/O operations.
/// </summary>
public sealed partial class ThreadPoolBoundHandle : IDisposable
{
private readonly SafeHandle _handle;
private bool _isDisposed;
private ThreadPoolBoundHandle(SafeHandle handle)
{
_handle = handle;
}
/// <summary>
/// Gets the bound operating system handle.
/// </summary>
/// <value>
/// A <see cref="SafeHandle"/> object that holds the bound operating system handle.
/// </value>
public SafeHandle Handle
{
get { return _handle; }
}
/// <summary>
/// Returns a <see cref="ThreadPoolBoundHandle"/> for the specific handle,
/// which is bound to the system thread pool.
/// </summary>
/// <param name="handle">
/// A <see cref="SafeHandle"/> object that holds the operating system handle. The
/// handle must have been opened for overlapped I/O on the unmanaged side.
/// </param>
/// <returns>
/// <see cref="ThreadPoolBoundHandle"/> for <paramref name="handle"/>, which
/// is bound to the system thread pool.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="handle"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="handle"/> has been disposed.
/// <para>
/// -or-
/// </para>
/// <paramref name="handle"/> does not refer to a valid I/O handle.
/// <para>
/// -or-
/// </para>
/// <paramref name="handle"/> refers to a handle that has not been opened
/// for overlapped I/O.
/// <para>
/// -or-
/// </para>
/// <paramref name="handle"/> refers to a handle that has already been bound.
/// </exception>
/// <remarks>
/// This method should be called once per handle.
/// <para>
/// -or-
/// </para>
/// <see cref="ThreadPoolBoundHandle"/> does not take ownership of <paramref name="handle"/>,
/// it remains the responsibility of the caller to call <see cref="SafeHandle.Dispose"/>.
/// </remarks>
public static ThreadPoolBoundHandle BindHandle(SafeHandle handle)
{
if (handle == null)
throw new ArgumentNullException(nameof(handle));
if (handle.IsClosed || handle.IsInvalid)
throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle));
try
{
// ThreadPool.BindHandle will always return true, otherwise, it throws. See the underlying FCall
// implementation in ThreadPoolNative::CorBindIoCompletionCallback to see the implementation.
bool succeeded = ThreadPool.BindHandle(handle);
Debug.Assert(succeeded);
}
catch (Exception ex)
{ // BindHandle throws ApplicationException on full CLR and Exception on CoreCLR.
// We do not let either of these leak and convert them to ArgumentException to
// indicate that the specified handles are invalid.
if (ex.HResult == System.HResults.E_HANDLE) // Bad handle
throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle));
if (ex.HResult == System.HResults.E_INVALIDARG) // Handle already bound or sync handle
throw new ArgumentException(SR.Argument_AlreadyBoundOrSyncHandle, nameof(handle));
throw;
}
return new ThreadPoolBoundHandle(handle);
}
/// <summary>
/// Returns an unmanaged pointer to a <see cref="NativeOverlapped"/> structure, specifying
/// a delegate that is invoked when the asynchronous I/O operation is complete, a user-provided
/// object providing context, and managed objects that serve as buffers.
/// </summary>
/// <param name="callback">
/// An <see cref="IOCompletionCallback"/> delegate that represents the callback method
/// invoked when the asynchronous I/O operation completes.
/// </param>
/// <param name="state">
/// A user-provided object that distinguishes this <see cref="NativeOverlapped"/> from other
/// <see cref="NativeOverlapped"/> instances. Can be <see langword="null"/>.
/// </param>
/// <param name="pinData">
/// An object or array of objects representing the input or output buffer for the operation. Each
/// object represents a buffer, for example an array of bytes. Can be <see langword="null"/>.
/// </param>
/// <returns>
/// An unmanaged pointer to a <see cref="NativeOverlapped"/> structure.
/// </returns>
/// <remarks>
/// <para>
/// The unmanaged pointer returned by this method can be passed to the operating system in
/// overlapped I/O operations. The <see cref="NativeOverlapped"/> structure is fixed in
/// physical memory until <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> is called.
/// </para>
/// <para>
/// The buffer or buffers specified in <paramref name="pinData"/> must be the same as those passed
/// to the unmanaged operating system function that performs the asynchronous I/O.
/// </para>
/// <note>
/// The buffers specified in <paramref name="pinData"/> are pinned for the duration of
/// the I/O operation.
/// </note>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="callback"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed.
/// </exception>
[CLSCompliant(false)]
public unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object state, object pinData)
{
if (callback == null)
throw new ArgumentNullException(nameof(callback));
EnsureNotDisposed();
ThreadPoolBoundHandleOverlapped overlapped = new ThreadPoolBoundHandleOverlapped(callback, state, pinData, preAllocated: null);
overlapped._boundHandle = this;
return overlapped._nativeOverlapped;
}
/// <summary>
/// Returns an unmanaged pointer to a <see cref="NativeOverlapped"/> structure, using the callback,
/// state, and buffers associated with the specified <see cref="PreAllocatedOverlapped"/> object.
/// </summary>
/// <param name="preAllocated">
/// A <see cref="PreAllocatedOverlapped"/> object from which to create the NativeOverlapped pointer.
/// </param>
/// <returns>
/// An unmanaged pointer to a <see cref="NativeOverlapped"/> structure.
/// </returns>
/// <remarks>
/// <para>
/// The unmanaged pointer returned by this method can be passed to the operating system in
/// overlapped I/O operations. The <see cref="NativeOverlapped"/> structure is fixed in
/// physical memory until <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> is called.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="preAllocated"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="preAllocated"/> is currently in use for another I/O operation.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed, or
/// this method was called after <paramref name="preAllocated"/> was disposed.
/// </exception>
/// <seealso cref="PreAllocatedOverlapped"/>
[CLSCompliant(false)]
public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated)
{
if (preAllocated == null)
throw new ArgumentNullException(nameof(preAllocated));
EnsureNotDisposed();
preAllocated.AddRef();
try
{
ThreadPoolBoundHandleOverlapped overlapped = preAllocated._overlapped;
if (overlapped._boundHandle != null)
throw new ArgumentException(SR.Argument_PreAllocatedAlreadyAllocated, nameof(preAllocated));
overlapped._boundHandle = this;
return overlapped._nativeOverlapped;
}
catch
{
preAllocated.Release();
throw;
}
}
/// <summary>
/// Frees the unmanaged memory associated with a <see cref="NativeOverlapped"/> structure
/// allocated by the <see cref="AllocateNativeOverlapped"/> method.
/// </summary>
/// <param name="overlapped">
/// An unmanaged pointer to the <see cref="NativeOverlapped"/> structure to be freed.
/// </param>
/// <remarks>
/// <note type="caution">
/// You must call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method exactly once
/// on every <see cref="NativeOverlapped"/> unmanaged pointer allocated using the
/// <see cref="AllocateNativeOverlapped"/> method.
/// If you do not call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method, you will
/// leak memory. If you call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method more
/// than once on the same <see cref="NativeOverlapped"/> unmanaged pointer, memory will be corrupted.
/// </note>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <paramref name="overlapped"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed.
/// </exception>
[CLSCompliant(false)]
public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped)
{
if (overlapped == null)
throw new ArgumentNullException(nameof(overlapped));
// Note: we explicitly allow FreeNativeOverlapped calls after the ThreadPoolBoundHandle has been Disposed.
ThreadPoolBoundHandleOverlapped wrapper = GetOverlappedWrapper(overlapped, this);
if (wrapper._boundHandle != this)
throw new ArgumentException(SR.Argument_NativeOverlappedWrongBoundHandle, nameof(overlapped));
if (wrapper._preAllocated != null)
wrapper._preAllocated.Release();
else
Overlapped.Free(overlapped);
}
/// <summary>
/// Returns the user-provided object specified when the <see cref="NativeOverlapped"/> instance was
/// allocated using the <see cref="AllocateNativeOverlapped(IOCompletionCallback, object, byte[])"/>.
/// </summary>
/// <param name="overlapped">
/// An unmanaged pointer to the <see cref="NativeOverlapped"/> structure from which to return the
/// asscociated user-provided object.
/// </param>
/// <returns>
/// A user-provided object that distinguishes this <see cref="NativeOverlapped"/>
/// from other <see cref="NativeOverlapped"/> instances, otherwise, <see langword="null"/> if one was
/// not specified when the instance was allocated using <see cref="AllocateNativeOverlapped"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="overlapped"/> is <see langword="null"/>.
/// </exception>
[CLSCompliant(false)]
public static unsafe object GetNativeOverlappedState(NativeOverlapped* overlapped)
{
if (overlapped == null)
throw new ArgumentNullException(nameof(overlapped));
ThreadPoolBoundHandleOverlapped wrapper = GetOverlappedWrapper(overlapped, null);
Debug.Assert(wrapper._boundHandle != null);
return wrapper._userState;
}
private static unsafe ThreadPoolBoundHandleOverlapped GetOverlappedWrapper(NativeOverlapped* overlapped, ThreadPoolBoundHandle expectedBoundHandle)
{
ThreadPoolBoundHandleOverlapped wrapper;
try
{
wrapper = (ThreadPoolBoundHandleOverlapped)Overlapped.Unpack(overlapped);
}
catch (NullReferenceException ex)
{
throw new ArgumentException(SR.Argument_NativeOverlappedAlreadyFree, nameof(overlapped), ex);
}
return wrapper;
}
public void Dispose()
{
// .NET Native's version of ThreadPoolBoundHandle that wraps the Win32 ThreadPool holds onto
// native resources so it needs to be disposable. To match the contract, we are also disposable.
// We also implement a disposable state to mimic behavior between this implementation and
// .NET Native's version (code written against us, will also work against .NET Native's version).
_isDisposed = true;
}
private void EnsureNotDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(GetType().ToString());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.ContentApps;
using Umbraco.Cms.Core.Dictionary;
using Umbraco.Cms.Core.Events;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Mapping;
using Umbraco.Cms.Core.Media;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Models.Entities;
using Umbraco.Cms.Core.Models.Validation;
using Umbraco.Cms.Core.Persistence.Querying;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Infrastructure.Persistence;
using Umbraco.Cms.Web.BackOffice.Authorization;
using Umbraco.Cms.Web.BackOffice.Filters;
using Umbraco.Cms.Web.BackOffice.ModelBinders;
using Umbraco.Cms.Web.Common.Attributes;
using Umbraco.Cms.Web.Common.Authorization;
using Umbraco.Extensions;
namespace Umbraco.Cms.Web.BackOffice.Controllers
{
/// <remarks>
/// This controller is decorated with the UmbracoApplicationAuthorizeAttribute which means that any user requesting
/// access to ALL of the methods on this controller will need access to the media application.
/// </remarks>
[PluginController(Constants.Web.Mvc.BackOfficeApiArea)]
[Authorize(Policy = AuthorizationPolicies.SectionAccessMedia)]
[ParameterSwapControllerActionSelector(nameof(GetById), "id", typeof(int), typeof(Guid), typeof(Udi))]
[ParameterSwapControllerActionSelector(nameof(GetChildren), "id", typeof(int), typeof(Guid), typeof(Udi))]
public class MediaController : ContentControllerBase
{
private readonly IShortStringHelper _shortStringHelper;
private readonly ContentSettings _contentSettings;
private readonly IMediaTypeService _mediaTypeService;
private readonly IMediaService _mediaService;
private readonly IEntityService _entityService;
private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor;
private readonly IUmbracoMapper _umbracoMapper;
private readonly IDataTypeService _dataTypeService;
private readonly ILocalizedTextService _localizedTextService;
private readonly ISqlContext _sqlContext;
private readonly IContentTypeBaseServiceProvider _contentTypeBaseServiceProvider;
private readonly IRelationService _relationService;
private readonly IImageUrlGenerator _imageUrlGenerator;
private readonly IAuthorizationService _authorizationService;
private readonly AppCaches _appCaches;
private readonly ILogger<MediaController> _logger;
public MediaController(
ICultureDictionary cultureDictionary,
ILoggerFactory loggerFactory,
IShortStringHelper shortStringHelper,
IEventMessagesFactory eventMessages,
ILocalizedTextService localizedTextService,
IOptions<ContentSettings> contentSettings,
IMediaTypeService mediaTypeService,
IMediaService mediaService,
IEntityService entityService,
IBackOfficeSecurityAccessor backofficeSecurityAccessor,
IUmbracoMapper umbracoMapper,
IDataTypeService dataTypeService,
ISqlContext sqlContext,
IContentTypeBaseServiceProvider contentTypeBaseServiceProvider,
IRelationService relationService,
PropertyEditorCollection propertyEditors,
MediaFileManager mediaFileManager,
MediaUrlGeneratorCollection mediaUrlGenerators,
IHostingEnvironment hostingEnvironment,
IImageUrlGenerator imageUrlGenerator,
IJsonSerializer serializer,
IAuthorizationService authorizationService,
AppCaches appCaches)
: base(cultureDictionary, loggerFactory, shortStringHelper, eventMessages, localizedTextService, serializer)
{
_shortStringHelper = shortStringHelper;
_contentSettings = contentSettings.Value;
_mediaTypeService = mediaTypeService;
_mediaService = mediaService;
_entityService = entityService;
_backofficeSecurityAccessor = backofficeSecurityAccessor;
_umbracoMapper = umbracoMapper;
_dataTypeService = dataTypeService;
_localizedTextService = localizedTextService;
_sqlContext = sqlContext;
_contentTypeBaseServiceProvider = contentTypeBaseServiceProvider;
_relationService = relationService;
_propertyEditors = propertyEditors;
_mediaFileManager = mediaFileManager;
_mediaUrlGenerators = mediaUrlGenerators;
_hostingEnvironment = hostingEnvironment;
_logger = loggerFactory.CreateLogger<MediaController>();
_imageUrlGenerator = imageUrlGenerator;
_authorizationService = authorizationService;
_appCaches = appCaches;
}
/// <summary>
/// Gets an empty content item for the
/// </summary>
/// <param name="contentTypeAlias"></param>
/// <param name="parentId"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
public ActionResult<MediaItemDisplay> GetEmpty(string contentTypeAlias, int parentId)
{
var contentType = _mediaTypeService.Get(contentTypeAlias);
if (contentType == null)
{
return NotFound();
}
var emptyContent = _mediaService.CreateMedia("", parentId, contentType.Alias, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
var mapped = _umbracoMapper.Map<MediaItemDisplay>(emptyContent);
//remove the listview app if it exists
mapped.ContentApps = mapped.ContentApps.Where(x => x.Alias != "umbListView").ToList();
return mapped;
}
/// <summary>
/// Returns an item to be used to display the recycle bin for media
/// </summary>
/// <returns></returns>
public MediaItemDisplay GetRecycleBin()
{
var apps = new List<ContentApp>();
apps.Add(ListViewContentAppFactory.CreateContentApp(_dataTypeService, _propertyEditors, "recycleBin", "media", Constants.DataTypes.DefaultMediaListView));
apps[0].Active = true;
var display = new MediaItemDisplay
{
Id = Constants.System.RecycleBinMedia,
Alias = "recycleBin",
ParentId = -1,
Name = _localizedTextService.Localize("general", "recycleBin"),
ContentTypeAlias = "recycleBin",
CreateDate = DateTime.Now,
IsContainer = true,
Path = "-1," + Constants.System.RecycleBinMedia,
ContentApps = apps
};
return display;
}
/// <summary>
/// Gets the media item by id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[Authorize(Policy = AuthorizationPolicies.MediaPermissionPathById)]
public MediaItemDisplay GetById(int id)
{
var foundMedia = GetObjectFromRequest(() => _mediaService.GetById(id));
if (foundMedia == null)
{
HandleContentNotFound(id);
//HandleContentNotFound will throw an exception
return null;
}
return _umbracoMapper.Map<MediaItemDisplay>(foundMedia);
}
/// <summary>
/// Gets the media item by id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[Authorize(Policy = AuthorizationPolicies.MediaPermissionPathById)]
public MediaItemDisplay GetById(Guid id)
{
var foundMedia = GetObjectFromRequest(() => _mediaService.GetById(id));
if (foundMedia == null)
{
HandleContentNotFound(id);
//HandleContentNotFound will throw an exception
return null;
}
return _umbracoMapper.Map<MediaItemDisplay>(foundMedia);
}
/// <summary>
/// Gets the media item by id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[Authorize(Policy = AuthorizationPolicies.MediaPermissionPathById)]
public ActionResult<MediaItemDisplay> GetById(Udi id)
{
var guidUdi = id as GuidUdi;
if (guidUdi != null)
{
return GetById(guidUdi.Guid);
}
return NotFound();
}
/// <summary>
/// Return media for the specified ids
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[FilterAllowedOutgoingMedia(typeof(IEnumerable<MediaItemDisplay>))]
public IEnumerable<MediaItemDisplay> GetByIds([FromQuery] int[] ids)
{
var foundMedia = _mediaService.GetByIds(ids);
return foundMedia.Select(media => _umbracoMapper.Map<MediaItemDisplay>(media));
}
/// <summary>
/// Returns a paged result of media items known to be of a "Folder" type
/// </summary>
/// <param name="id"></param>
/// <param name="pageNumber"></param>
/// <param name="pageSize"></param>
/// <returns></returns>
public PagedResult<ContentItemBasic<ContentPropertyBasic>> GetChildFolders(int id, int pageNumber = 1, int pageSize = 1000)
{
//Suggested convention for folder mediatypes - we can make this more or less complicated as long as we document it...
//if you create a media type, which has an alias that ends with ...Folder then its a folder: ex: "secureFolder", "bannerFolder", "Folder"
var folderTypes = _mediaTypeService
.GetAll()
.Where(x => x.Alias.EndsWith("Folder"))
.Select(x => x.Id)
.ToArray();
if (folderTypes.Length == 0)
{
return new PagedResult<ContentItemBasic<ContentPropertyBasic>>(0, pageNumber, pageSize);
}
long total;
var children = _mediaService.GetPagedChildren(id, pageNumber - 1, pageSize, out total,
//lookup these content types
_sqlContext.Query<IMedia>().Where(x => folderTypes.Contains(x.ContentTypeId)),
Ordering.By("Name", Direction.Ascending));
return new PagedResult<ContentItemBasic<ContentPropertyBasic>>(total, pageNumber, pageSize)
{
Items = children.Select(_umbracoMapper.Map<IMedia, ContentItemBasic<ContentPropertyBasic>>)
};
}
/// <summary>
/// Returns the root media objects
/// </summary>
[FilterAllowedOutgoingMedia(typeof(IEnumerable<ContentItemBasic<ContentPropertyBasic>>))]
public IEnumerable<ContentItemBasic<ContentPropertyBasic>> GetRootMedia()
{
// TODO: Add permissions check!
return _mediaService.GetRootMedia()
.Select(_umbracoMapper.Map<IMedia, ContentItemBasic<ContentPropertyBasic>>);
}
#region GetChildren
private int[] _userStartNodes;
private readonly PropertyEditorCollection _propertyEditors;
private readonly MediaFileManager _mediaFileManager;
private readonly MediaUrlGeneratorCollection _mediaUrlGenerators;
private readonly IHostingEnvironment _hostingEnvironment;
protected int[] UserStartNodes
{
get { return _userStartNodes ?? (_userStartNodes = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.CalculateMediaStartNodeIds(_entityService, _appCaches)); }
}
/// <summary>
/// Returns the child media objects - using the entity INT id
/// </summary>
[FilterAllowedOutgoingMedia(typeof(IEnumerable<ContentItemBasic<ContentPropertyBasic>>), "Items")]
public PagedResult<ContentItemBasic<ContentPropertyBasic>> GetChildren(int id,
int pageNumber = 0,
int pageSize = 0,
string orderBy = "SortOrder",
Direction orderDirection = Direction.Ascending,
bool orderBySystemField = true,
string filter = "")
{
//if a request is made for the root node data but the user's start node is not the default, then
// we need to return their start nodes
if (id == Constants.System.Root && UserStartNodes.Length > 0 && UserStartNodes.Contains(Constants.System.Root) == false)
{
if (pageNumber > 0)
return new PagedResult<ContentItemBasic<ContentPropertyBasic>>(0, 0, 0);
var nodes = _mediaService.GetByIds(UserStartNodes).ToArray();
if (nodes.Length == 0)
return new PagedResult<ContentItemBasic<ContentPropertyBasic>>(0, 0, 0);
if (pageSize < nodes.Length)
pageSize = nodes.Length; // bah
var pr = new PagedResult<ContentItemBasic<ContentPropertyBasic>>(nodes.Length, pageNumber, pageSize)
{
Items = nodes.Select(_umbracoMapper.Map<IMedia, ContentItemBasic<ContentPropertyBasic>>)
};
return pr;
}
// else proceed as usual
long totalChildren;
List<IMedia> children;
if (pageNumber > 0 && pageSize > 0)
{
IQuery<IMedia> queryFilter = null;
if (filter.IsNullOrWhiteSpace() == false)
{
//add the default text filter
queryFilter = _sqlContext.Query<IMedia>()
.Where(x => x.Name.Contains(filter));
}
children = _mediaService
.GetPagedChildren(
id, (pageNumber - 1), pageSize,
out totalChildren,
queryFilter,
Ordering.By(orderBy, orderDirection, isCustomField: !orderBySystemField)).ToList();
}
else
{
//better to not use this without paging where possible, currently only the sort dialog does
children = _mediaService.GetPagedChildren(id, 0, int.MaxValue, out var total).ToList();
totalChildren = children.Count;
}
if (totalChildren == 0)
{
return new PagedResult<ContentItemBasic<ContentPropertyBasic>>(0, 0, 0);
}
var pagedResult = new PagedResult<ContentItemBasic<ContentPropertyBasic>>(totalChildren, pageNumber, pageSize);
pagedResult.Items = children
.Select(_umbracoMapper.Map<IMedia, ContentItemBasic<ContentPropertyBasic>>);
return pagedResult;
}
/// <summary>
/// Returns the child media objects - using the entity GUID id
/// </summary>
/// <param name="id"></param>
/// <param name="pageNumber"></param>
/// <param name="pageSize"></param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="orderBySystemField"></param>
/// <param name="filter"></param>
/// <returns></returns>
[FilterAllowedOutgoingMedia(typeof(IEnumerable<ContentItemBasic<ContentPropertyBasic>>), "Items")]
public ActionResult<PagedResult<ContentItemBasic<ContentPropertyBasic>>> GetChildren(Guid id,
int pageNumber = 0,
int pageSize = 0,
string orderBy = "SortOrder",
Direction orderDirection = Direction.Ascending,
bool orderBySystemField = true,
string filter = "")
{
var entity = _entityService.Get(id);
if (entity != null)
{
return GetChildren(entity.Id, pageNumber, pageSize, orderBy, orderDirection, orderBySystemField, filter);
}
return NotFound();
}
/// <summary>
/// Returns the child media objects - using the entity UDI id
/// </summary>
/// <param name="id"></param>
/// <param name="pageNumber"></param>
/// <param name="pageSize"></param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="orderBySystemField"></param>
/// <param name="filter"></param>
/// <returns></returns>
[FilterAllowedOutgoingMedia(typeof(IEnumerable<ContentItemBasic<ContentPropertyBasic>>), "Items")]
public ActionResult<PagedResult<ContentItemBasic<ContentPropertyBasic>>> GetChildren(Udi id,
int pageNumber = 0,
int pageSize = 0,
string orderBy = "SortOrder",
Direction orderDirection = Direction.Ascending,
bool orderBySystemField = true,
string filter = "")
{
var guidUdi = id as GuidUdi;
if (guidUdi != null)
{
var entity = _entityService.Get(guidUdi.Guid);
if (entity != null)
{
return GetChildren(entity.Id, pageNumber, pageSize, orderBy, orderDirection, orderBySystemField, filter);
}
}
return NotFound();
}
#endregion
/// <summary>
/// Moves an item to the recycle bin, if it is already there then it will permanently delete it
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[Authorize(Policy = AuthorizationPolicies.MediaPermissionPathById)]
[HttpPost]
public IActionResult DeleteById(int id)
{
var foundMedia = GetObjectFromRequest(() => _mediaService.GetById(id));
if (foundMedia == null)
{
return HandleContentNotFound(id);
}
//if the current item is in the recycle bin
if (foundMedia.Trashed == false)
{
var moveResult = _mediaService.MoveToRecycleBin(foundMedia, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
if (moveResult == false)
{
return ValidationProblem();
}
}
else
{
var deleteResult = _mediaService.Delete(foundMedia, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
if (deleteResult == false)
{
return ValidationProblem();
}
}
return Ok();
}
/// <summary>
/// Change the sort order for media
/// </summary>
/// <param name="move"></param>
/// <returns></returns>
public async Task<IActionResult> PostMove(MoveOrCopy move)
{
// Authorize...
var requirement = new MediaPermissionsResourceRequirement();
var authorizationResult = await _authorizationService.AuthorizeAsync(User, new MediaPermissionsResource(_mediaService.GetById(move.Id)), requirement);
if (!authorizationResult.Succeeded)
{
return Forbid();
}
var toMoveResult = ValidateMoveOrCopy(move);
var toMove = toMoveResult.Value;
if (toMove is null && toMoveResult is IConvertToActionResult convertToActionResult)
{
return convertToActionResult.Convert();
}
var destinationParentID = move.ParentId;
var sourceParentID = toMove.ParentId;
var moveResult = _mediaService.Move(toMove, move.ParentId, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
if (sourceParentID == destinationParentID)
{
return ValidationProblem(new SimpleNotificationModel(new BackOfficeNotification("", _localizedTextService.Localize("media", "moveToSameFolderFailed"), NotificationStyle.Error)));
}
if (moveResult == false)
{
return ValidationProblem();
}
else
{
return Content(toMove.Path, MediaTypeNames.Text.Plain, Encoding.UTF8);
}
}
/// <summary>
/// Saves content
/// </summary>
/// <returns></returns>
[FileUploadCleanupFilter]
[MediaItemSaveValidation]
[OutgoingEditorModelEvent]
public ActionResult<MediaItemDisplay> PostSave(
[ModelBinder(typeof(MediaItemBinder))]
MediaItemSave contentItem)
{
//Recent versions of IE/Edge may send in the full client side file path instead of just the file name.
//To ensure similar behavior across all browsers no matter what they do - we strip the FileName property of all
//uploaded files to being *only* the actual file name (as it should be).
if (contentItem.UploadedFiles != null && contentItem.UploadedFiles.Any())
{
foreach (var file in contentItem.UploadedFiles)
{
file.FileName = Path.GetFileName(file.FileName);
}
}
//If we've reached here it means:
// * Our model has been bound
// * and validated
// * any file attachments have been saved to their temporary location for us to use
// * we have a reference to the DTO object and the persisted object
// * Permissions are valid
//Don't update the name if it is empty
if (contentItem.Name.IsNullOrWhiteSpace() == false)
{
contentItem.PersistedContent.Name = contentItem.Name;
}
MapPropertyValuesForPersistence<IMedia, MediaItemSave>(
contentItem,
contentItem.PropertyCollectionDto,
(save, property) => property.GetValue(), //get prop val
(save, property, v) => property.SetValue(v), //set prop val
null); // media are all invariant
//we will continue to save if model state is invalid, however we cannot save if critical data is missing.
//TODO: Allowing media to be saved when it is invalid is odd - media doesn't have a publish phase so suddenly invalid data is allowed to be 'live'
if (!ModelState.IsValid)
{
//check for critical data validation issues, we can't continue saving if this data is invalid
if (!RequiredForPersistenceAttribute.HasRequiredValuesForPersistence(contentItem))
{
//ok, so the absolute mandatory data is invalid and it's new, we cannot actually continue!
// add the model state to the outgoing object and throw validation response
MediaItemDisplay forDisplay = _umbracoMapper.Map<MediaItemDisplay>(contentItem.PersistedContent);
return ValidationProblem(forDisplay, ModelState);
}
}
//save the item
var saveStatus = _mediaService.Save(contentItem.PersistedContent, _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
//return the updated model
var display = _umbracoMapper.Map<MediaItemDisplay>(contentItem.PersistedContent);
//lastly, if it is not valid, add the model state to the outgoing object and throw a 403
if (!ModelState.IsValid)
{
return ValidationProblem(display, ModelState, StatusCodes.Status403Forbidden);
}
//put the correct msgs in
switch (contentItem.Action)
{
case ContentSaveAction.Save:
case ContentSaveAction.SaveNew:
if (saveStatus.Success)
{
display.AddSuccessNotification(
_localizedTextService.Localize("speechBubbles", "editMediaSaved"),
_localizedTextService.Localize("speechBubbles", "editMediaSavedText"));
}
else
{
AddCancelMessage(display);
//If the item is new and the operation was cancelled, we need to return a different
// status code so the UI can handle it since it won't be able to redirect since there
// is no Id to redirect to!
if (saveStatus.Result.Result == OperationResultType.FailedCancelledByEvent && IsCreatingAction(contentItem.Action))
{
return ValidationProblem(display);
}
}
break;
}
return display;
}
/// <summary>
/// Empties the recycle bin
/// </summary>
/// <returns></returns>
[HttpDelete]
[HttpPost]
public IActionResult EmptyRecycleBin()
{
_mediaService.EmptyRecycleBin(_backofficeSecurityAccessor.BackOfficeSecurity.GetUserId().ResultOr(Constants.Security.SuperUserId));
return Ok(_localizedTextService.Localize("defaultdialogs", "recycleBinIsEmpty"));
}
/// <summary>
/// Change the sort order for media
/// </summary>
/// <param name="sorted"></param>
/// <returns></returns>
public async Task<IActionResult> PostSort(ContentSortOrder sorted)
{
if (sorted == null)
{
return NotFound();
}
//if there's nothing to sort just return ok
if (sorted.IdSortOrder.Length == 0)
{
return Ok();
}
// Authorize...
var requirement = new MediaPermissionsResourceRequirement();
var resource = new MediaPermissionsResource(sorted.ParentId);
var authorizationResult = await _authorizationService.AuthorizeAsync(User, resource, requirement);
if (!authorizationResult.Succeeded)
{
return Forbid();
}
var sortedMedia = new List<IMedia>();
try
{
sortedMedia.AddRange(sorted.IdSortOrder.Select(_mediaService.GetById));
// Save Media with new sort order and update content xml in db accordingly
if (_mediaService.Sort(sortedMedia) == false)
{
_logger.LogWarning("Media sorting failed, this was probably caused by an event being cancelled");
return ValidationProblem("Media sorting failed, this was probably caused by an event being cancelled");
}
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, "Could not update media sort order");
throw;
}
}
public async Task<ActionResult<MediaItemDisplay>> PostAddFolder(PostedFolder folder)
{
var parentIdResult = await GetParentIdAsIntAsync(folder.ParentId, validatePermissions: true);
if (!(parentIdResult.Result is null))
{
return new ActionResult<MediaItemDisplay>(parentIdResult.Result);
}
var parentId = parentIdResult.Value;
if (!parentId.HasValue)
{
return NotFound("The passed id doesn't exist");
}
var isFolderAllowed = IsFolderCreationAllowedHere(parentId.Value);
if (isFolderAllowed == false)
{
return ValidationProblem(_localizedTextService.Localize("speechBubbles", "folderCreationNotAllowed"));
}
var f = _mediaService.CreateMedia(folder.Name, parentId.Value, Constants.Conventions.MediaTypes.Folder);
_mediaService.Save(f, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
return _umbracoMapper.Map<MediaItemDisplay>(f);
}
/// <summary>
/// Used to submit a media file
/// </summary>
/// <returns></returns>
/// <remarks>
/// We cannot validate this request with attributes (nicely) due to the nature of the multi-part for data.
/// </remarks>
public async Task<IActionResult> PostAddFile([FromForm] string path, [FromForm] string currentFolder, [FromForm] string contentTypeAlias, List<IFormFile> file)
{
var root = _hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.TempFileUploads);
//ensure it exists
Directory.CreateDirectory(root);
//must have a file
if (file.Count == 0)
{
return NotFound();
}
//get the string json from the request
var parentIdResult = await GetParentIdAsIntAsync(currentFolder, validatePermissions: true);
if (!(parentIdResult.Result is null))
{
return parentIdResult.Result;
}
var parentId = parentIdResult.Value;
if (!parentId.HasValue)
{
return NotFound("The passed id doesn't exist");
}
var tempFiles = new PostedFiles();
//in case we pass a path with a folder in it, we will create it and upload media to it.
if (!string.IsNullOrEmpty(path))
{
if (!IsFolderCreationAllowedHere(parentId.Value))
{
AddCancelMessage(tempFiles, _localizedTextService.Localize("speechBubbles", "folderUploadNotAllowed"));
return Ok(tempFiles);
}
var folders = path.Split(Constants.CharArrays.ForwardSlash);
for (int i = 0; i < folders.Length - 1; i++)
{
var folderName = folders[i];
IMedia folderMediaItem;
//if uploading directly to media root and not a subfolder
if (parentId == Constants.System.Root)
{
//look for matching folder
folderMediaItem =
_mediaService.GetRootMedia().FirstOrDefault(x => x.Name == folderName && x.ContentType.Alias == Constants.Conventions.MediaTypes.Folder);
if (folderMediaItem == null)
{
//if null, create a folder
folderMediaItem = _mediaService.CreateMedia(folderName, -1, Constants.Conventions.MediaTypes.Folder);
_mediaService.Save(folderMediaItem);
}
}
else
{
//get current parent
var mediaRoot = _mediaService.GetById(parentId.Value);
//if the media root is null, something went wrong, we'll abort
if (mediaRoot == null)
return Problem(
"The folder: " + folderName + " could not be used for storing images, its ID: " + parentId +
" returned null");
//look for matching folder
folderMediaItem = FindInChildren(mediaRoot.Id, folderName, Constants.Conventions.MediaTypes.Folder);
if (folderMediaItem == null)
{
//if null, create a folder
folderMediaItem = _mediaService.CreateMedia(folderName, mediaRoot, Constants.Conventions.MediaTypes.Folder);
_mediaService.Save(folderMediaItem);
}
}
//set the media root to the folder id so uploaded files will end there.
parentId = folderMediaItem.Id;
}
}
var mediaTypeAlias = string.Empty;
var allMediaTypes = _mediaTypeService.GetAll().ToList();
var allowedContentTypes = new HashSet<IMediaType>();
if (parentId != Constants.System.Root)
{
var mediaFolderItem = _mediaService.GetById(parentId.Value);
var mediaFolderType = allMediaTypes.FirstOrDefault(x => x.Alias == mediaFolderItem.ContentType.Alias);
if (mediaFolderType != null)
{
IMediaType mediaTypeItem = null;
foreach (ContentTypeSort allowedContentType in mediaFolderType.AllowedContentTypes)
{
IMediaType checkMediaTypeItem = allMediaTypes.FirstOrDefault(x => x.Id == allowedContentType.Id.Value);
allowedContentTypes.Add(checkMediaTypeItem);
var fileProperty = checkMediaTypeItem?.CompositionPropertyTypes.FirstOrDefault(x => x.Alias == Constants.Conventions.Media.File);
if (fileProperty != null)
{
mediaTypeItem = checkMediaTypeItem;
}
}
//Only set the permission-based mediaType if we only allow 1 specific file under this parent.
if (allowedContentTypes.Count == 1 && mediaTypeItem != null)
{
mediaTypeAlias = mediaTypeItem.Alias;
}
}
}
else
{
var typesAllowedAtRoot = allMediaTypes.Where(x => x.AllowedAsRoot).ToList();
allowedContentTypes.UnionWith(typesAllowedAtRoot);
}
//get the files
foreach (var formFile in file)
{
var fileName = formFile.FileName.Trim(Constants.CharArrays.DoubleQuote).TrimEnd();
var safeFileName = fileName.ToSafeFileName(ShortStringHelper);
var ext = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLower();
if (!_contentSettings.IsFileAllowedForUpload(ext))
{
tempFiles.Notifications.Add(new BackOfficeNotification(
_localizedTextService.Localize("speechBubbles", "operationFailedHeader"),
_localizedTextService.Localize("media", "disallowedFileType"),
NotificationStyle.Warning));
continue;
}
if (string.IsNullOrEmpty(mediaTypeAlias))
{
mediaTypeAlias = Constants.Conventions.MediaTypes.File;
if (contentTypeAlias == Constants.Conventions.MediaTypes.AutoSelect)
{
// Look up MediaTypes
foreach (var mediaTypeItem in allMediaTypes)
{
var fileProperty = mediaTypeItem.CompositionPropertyTypes.FirstOrDefault(x => x.Alias == Constants.Conventions.Media.File);
if (fileProperty == null)
{
continue;
}
var dataTypeKey = fileProperty.DataTypeKey;
var dataType = _dataTypeService.GetDataType(dataTypeKey);
if (dataType == null || dataType.Configuration is not IFileExtensionsConfig fileExtensionsConfig)
{
continue;
}
var fileExtensions = fileExtensionsConfig.FileExtensions;
if (fileExtensions == null || fileExtensions.All(x => x.Value != ext))
{
continue;
}
mediaTypeAlias = mediaTypeItem.Alias;
break;
}
// If media type is still File then let's check if it's an image.
if (mediaTypeAlias == Constants.Conventions.MediaTypes.File && _imageUrlGenerator.SupportedImageFileTypes.Contains(ext))
{
mediaTypeAlias = Constants.Conventions.MediaTypes.Image;
}
}
else
{
mediaTypeAlias = contentTypeAlias;
}
}
if (allowedContentTypes.Any(x => x.Alias == mediaTypeAlias) == false)
{
tempFiles.Notifications.Add(new BackOfficeNotification(
_localizedTextService.Localize("speechBubbles", "operationFailedHeader"),
_localizedTextService.Localize("media", "disallowedMediaType", new[] { mediaTypeAlias }),
NotificationStyle.Warning));
continue;
}
var mediaItemName = fileName.ToFriendlyName();
var createdMediaItem = _mediaService.CreateMedia(mediaItemName, parentId.Value, mediaTypeAlias, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
await using (var stream = formFile.OpenReadStream())
{
createdMediaItem.SetValue(_mediaFileManager, _mediaUrlGenerators, _shortStringHelper, _contentTypeBaseServiceProvider, Constants.Conventions.Media.File, fileName, stream);
}
var saveResult = _mediaService.Save(createdMediaItem, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Id);
if (saveResult == false)
{
AddCancelMessage(tempFiles, _localizedTextService.Localize("speechBubbles", "operationCancelledText") + " -- " + mediaItemName);
}
}
//Different response if this is a 'blueimp' request
if (HttpContext.Request.Query.Any(x => x.Key == "origin"))
{
var origin = HttpContext.Request.Query.First(x => x.Key == "origin");
if (origin.Value == "blueimp")
{
return new JsonResult(tempFiles); //Don't output the angular xsrf stuff, blue imp doesn't like that
}
}
return Ok(tempFiles);
}
private bool IsFolderCreationAllowedHere(int parentId)
{
var allMediaTypes = _mediaTypeService.GetAll().ToList();
var isFolderAllowed = false;
if (parentId == Constants.System.Root)
{
var typesAllowedAtRoot = allMediaTypes.Where(ct => ct.AllowedAsRoot).ToList();
isFolderAllowed = typesAllowedAtRoot.Any(x => x.Alias == Constants.Conventions.MediaTypes.Folder);
}
else
{
var parentMediaType = _mediaService.GetById(parentId);
var mediaFolderType = allMediaTypes.FirstOrDefault(x => x.Alias == parentMediaType.ContentType.Alias);
if (mediaFolderType != null)
{
isFolderAllowed =
mediaFolderType.AllowedContentTypes.Any(x => x.Alias == Constants.Conventions.MediaTypes.Folder);
}
}
return isFolderAllowed;
}
private IMedia FindInChildren(int mediaId, string nameToFind, string contentTypeAlias)
{
const int pageSize = 500;
var page = 0;
var total = long.MaxValue;
while (page * pageSize < total)
{
var children = _mediaService.GetPagedChildren(mediaId, page++, pageSize, out total,
_sqlContext.Query<IMedia>().Where(x => x.Name == nameToFind));
var match = children.FirstOrDefault(c => c.ContentType.Alias == contentTypeAlias);
if (match != null)
{
return match;
}
}
return null;
}
/// <summary>
/// Given a parent id which could be a GUID, UDI or an INT, this will resolve the INT
/// </summary>
/// <param name="parentId"></param>
/// <param name="validatePermissions">
/// If true, this will check if the current user has access to the resolved integer parent id
/// and if that check fails an unauthorized exception will occur
/// </param>
/// <returns></returns>
private async Task<ActionResult<int?>> GetParentIdAsIntAsync(string parentId, bool validatePermissions)
{
int intParentId;
// test for udi
if (UdiParser.TryParse(parentId, out GuidUdi parentUdi))
{
parentId = parentUdi.Guid.ToString();
}
//if it's not an INT then we'll check for GUID
if (int.TryParse(parentId, NumberStyles.Integer, CultureInfo.InvariantCulture, out intParentId) == false)
{
// if a guid then try to look up the entity
Guid idGuid;
if (Guid.TryParse(parentId, out idGuid))
{
var entity = _entityService.Get(idGuid);
if (entity != null)
{
intParentId = entity.Id;
}
else
{
return null;
}
}
else
{
return ValidationProblem("The request was not formatted correctly, the parentId is not an integer, Guid or UDI");
}
}
// Authorize...
//ensure the user has access to this folder by parent id!
if (validatePermissions)
{
var requirement = new MediaPermissionsResourceRequirement();
var authorizationResult = await _authorizationService.AuthorizeAsync(User, new MediaPermissionsResource(_mediaService.GetById(intParentId)), requirement);
if (!authorizationResult.Succeeded)
{
return ValidationProblem(
new SimpleNotificationModel(new BackOfficeNotification(
_localizedTextService.Localize("speechBubbles", "operationFailedHeader"),
_localizedTextService.Localize("speechBubbles", "invalidUserPermissionsText"),
NotificationStyle.Warning)),
StatusCodes.Status403Forbidden);
}
}
return intParentId;
}
/// <summary>
/// Ensures the item can be moved/copied to the new location
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
private ActionResult<IMedia> ValidateMoveOrCopy(MoveOrCopy model)
{
if (model == null)
{
return NotFound();
}
var toMove = _mediaService.GetById(model.Id);
if (toMove == null)
{
return NotFound();
}
if (model.ParentId < 0)
{
//cannot move if the content item is not allowed at the root unless there are
//none allowed at root (in which case all should be allowed at root)
var mediaTypeService = _mediaTypeService;
if (toMove.ContentType.AllowedAsRoot == false && mediaTypeService.GetAll().Any(ct => ct.AllowedAsRoot))
{
var notificationModel = new SimpleNotificationModel();
notificationModel.AddErrorNotification(_localizedTextService.Localize("moveOrCopy", "notAllowedAtRoot"), "");
return ValidationProblem(notificationModel);
}
}
else
{
var parent = _mediaService.GetById(model.ParentId);
if (parent == null)
{
return NotFound();
}
//check if the item is allowed under this one
var parentContentType = _mediaTypeService.Get(parent.ContentTypeId);
if (parentContentType.AllowedContentTypes.Select(x => x.Id).ToArray()
.Any(x => x.Value == toMove.ContentType.Id) == false)
{
var notificationModel = new SimpleNotificationModel();
notificationModel.AddErrorNotification(_localizedTextService.Localize("moveOrCopy", "notAllowedByContentType"), "");
return ValidationProblem(notificationModel);
}
// Check on paths
if ((string.Format(",{0},", parent.Path)).IndexOf(string.Format(",{0},", toMove.Id), StringComparison.Ordinal) > -1)
{
var notificationModel = new SimpleNotificationModel();
notificationModel.AddErrorNotification(_localizedTextService.Localize("moveOrCopy", "notAllowedByPath"), "");
return ValidationProblem(notificationModel);
}
}
return new ActionResult<IMedia>(toMove);
}
[Obsolete("Please use TrackedReferencesController.GetPagedReferences() instead. Scheduled for removal in V11.")]
public PagedResult<EntityBasic> GetPagedReferences(int id, string entityType, int pageNumber = 1, int pageSize = 100)
{
if (pageNumber <= 0 || pageSize <= 0)
{
throw new NotSupportedException("Both pageNumber and pageSize must be greater than zero");
}
var objectType = ObjectTypes.GetUmbracoObjectType(entityType);
var udiType = ObjectTypes.GetUdiType(objectType);
var relations = _relationService.GetPagedParentEntitiesByChildId(id, pageNumber - 1, pageSize, out var totalRecords, objectType);
return new PagedResult<EntityBasic>(totalRecords, pageNumber, pageSize)
{
Items = relations.Cast<ContentEntitySlim>().Select(rel => new EntityBasic
{
Id = rel.Id,
Key = rel.Key,
Udi = Udi.Create(udiType, rel.Key),
Icon = rel.ContentTypeIcon,
Name = rel.Name,
Alias = rel.ContentTypeAlias
})
};
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
// Copyright (c) 2010, Nathan Brown
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Announcers;
using FluentMigrator.Runner.Generators.SqlServer;
using FluentMigrator.Runner.Initialization;
using FluentMigrator.Runner.Processors;
using FluentMigrator.Runner.Processors.Firebird;
using FluentMigrator.Runner.Processors.MySql;
using FluentMigrator.Runner.Processors.Postgres;
using FluentMigrator.Runner.Processors.Sqlite;
using FluentMigrator.Runner.Processors.SqlServer;
using FluentMigrator.Tests.Integration.Migrations;
using FluentMigrator.Tests.Integration.Migrations.Tagged;
using FluentMigrator.Tests.Unit;
using FluentMigrator.Tests.Integration.Migrations.Interleaved.Pass3;
using FluentMigrator.Tests.Integration.Migrations.Invalid;
using Moq;
using NUnit.Framework;
using NUnit.Should;
namespace FluentMigrator.Tests.Integration
{
[TestFixture]
[Category("Integration")]
public class MigrationRunnerTests : IntegrationTestBase
{
private IRunnerContext _runnerContext;
[SetUp]
public void SetUp()
{
_runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = "FluentMigrator.Tests.Integration.Migrations"
};
}
[Test]
public void CanRunMigration()
{
ExecuteWithSupportedProcessors(processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.TableExists(null, "TestTable").ShouldBeTrue();
// This is a hack until MigrationVersionRunner and MigrationRunner are refactored and merged together
//processor.CommitTransaction();
runner.Down(new TestCreateAndDropTableMigration());
processor.TableExists(null, "TestTable").ShouldBeFalse();
});
}
[Test]
public void CanSilentlyFail()
{
try
{
var processorOptions = new Mock<IMigrationProcessorOptions>();
processorOptions.SetupGet(x => x.PreviewOnly).Returns(false);
var processor = new Mock<IMigrationProcessor>();
processor.Setup(x => x.Process(It.IsAny<CreateForeignKeyExpression>())).Throws(new Exception("Error"));
processor.Setup(x => x.Process(It.IsAny<DeleteForeignKeyExpression>())).Throws(new Exception("Error"));
processor.Setup(x => x.Options).Returns(processorOptions.Object);
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor.Object) { SilentlyFail = true };
runner.Up(new TestForeignKeySilentFailure());
runner.CaughtExceptions.Count.ShouldBeGreaterThan(0);
runner.Down(new TestForeignKeySilentFailure());
runner.CaughtExceptions.Count.ShouldBeGreaterThan(0);
}
finally
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner testRunner = SetupMigrationRunner(processor);
testRunner.RollbackToVersion(0);
}, false);
}
}
[Test]
public void CanApplyForeignKeyConvention()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestForeignKeyNamingConvention());
processor.ConstraintExists(null, "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeTrue();
runner.Down(new TestForeignKeyNamingConvention());
processor.ConstraintExists(null, "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeFalse();
}, false, typeof(SqliteProcessor));
}
[Test]
public void CanApplyForeignKeyConventionWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestForeignKeyNamingConventionWithSchema());
processor.ConstraintExists("TestSchema", "Users", "FK_Users_GroupId_Groups_GroupId").ShouldBeTrue();
runner.Down(new TestForeignKeyNamingConventionWithSchema());
}, false, new []{typeof(SqliteProcessor), typeof(FirebirdProcessor)});
}
[Test]
public void CanApplyIndexConvention()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestIndexNamingConvention());
processor.IndexExists(null, "Users", "IX_Users_GroupId").ShouldBeTrue();
processor.TableExists(null, "Users").ShouldBeTrue();
runner.Down(new TestIndexNamingConvention());
processor.IndexExists(null, "Users", "IX_Users_GroupId").ShouldBeFalse();
processor.TableExists(null, "Users").ShouldBeFalse();
});
}
[Test]
public void CanApplyIndexConventionWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestIndexNamingConventionWithSchema());
processor.IndexExists("TestSchema", "Users", "IX_Users_GroupId").ShouldBeTrue();
processor.TableExists("TestSchema", "Users").ShouldBeTrue();
runner.Down(new TestIndexNamingConventionWithSchema());
processor.IndexExists("TestSchema", "Users", "IX_Users_GroupId").ShouldBeFalse();
processor.TableExists("TestSchema", "Users").ShouldBeFalse();
});
}
[Test]
public void CanCreateAndDropIndex()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Up(new TestCreateAndDropIndexMigration());
processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeTrue();
runner.Down(new TestCreateAndDropIndexMigration());
processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigration());
processor.IndexExists(null, "TestTable", "IX_TestTable_Name").ShouldBeFalse();
//processor.CommitTransaction();
});
}
[Test]
public void CanCreateAndDropIndexWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Up(new TestCreateAndDropIndexMigrationWithSchema());
processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeTrue();
runner.Down(new TestCreateAndDropIndexMigrationWithSchema());
processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
processor.IndexExists("TestSchema", "TestTable", "IX_TestTable_Name").ShouldBeFalse();
runner.Down(new TestCreateSchema());
//processor.CommitTransaction();
}, false, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanRenameTable()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.TableExists(null, "TestTable2").ShouldBeTrue();
runner.Up(new TestRenameTableMigration());
processor.TableExists(null, "TestTable2").ShouldBeFalse();
processor.TableExists(null, "TestTable'3").ShouldBeTrue();
runner.Down(new TestRenameTableMigration());
processor.TableExists(null, "TestTable'3").ShouldBeFalse();
processor.TableExists(null, "TestTable2").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigration());
processor.TableExists(null, "TestTable2").ShouldBeFalse();
//processor.CommitTransaction();
});
}
[Test]
public void CanRenameTableWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable2").ShouldBeTrue();
runner.Up(new TestRenameTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable2").ShouldBeFalse();
processor.TableExists("TestSchema", "TestTable'3").ShouldBeTrue();
runner.Down(new TestRenameTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable'3").ShouldBeFalse();
processor.TableExists("TestSchema", "TestTable2").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable2").ShouldBeFalse();
runner.Down(new TestCreateSchema());
//processor.CommitTransaction();
});
}
[Test]
public void CanRenameColumn()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.ColumnExists(null, "TestTable2", "Name").ShouldBeTrue();
runner.Up(new TestRenameColumnMigration());
processor.ColumnExists(null, "TestTable2", "Name").ShouldBeFalse();
processor.ColumnExists(null, "TestTable2", "Name'3").ShouldBeTrue();
runner.Down(new TestRenameColumnMigration());
processor.ColumnExists(null, "TestTable2", "Name'3").ShouldBeFalse();
processor.ColumnExists(null, "TestTable2", "Name").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigration());
processor.ColumnExists(null, "TestTable2", "Name").ShouldBeFalse();
}, true, typeof(SqliteProcessor));
}
[Test]
public void CanRenameColumnWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeTrue();
runner.Up(new TestRenameColumnMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeFalse();
processor.ColumnExists("TestSchema", "TestTable2", "Name'3").ShouldBeTrue();
runner.Down(new TestRenameColumnMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name'3").ShouldBeFalse();
processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name").ShouldBeFalse();
runner.Down(new TestCreateSchema());
}, true, typeof(SqliteProcessor), typeof(FirebirdProcessor));
}
[Test]
public void CanLoadMigrations()
{
ExecuteWithSupportedProcessors(processor =>
{
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TestMigration).Namespace,
};
var runner = new MigrationRunner(typeof(MigrationRunnerTests).Assembly, runnerContext, processor);
//runner.Processor.CommitTransaction();
runner.MigrationLoader.LoadMigrations().ShouldNotBeNull();
});
}
[Test]
public void CanLoadVersion()
{
ExecuteWithSupportedProcessors(processor =>
{
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TestMigration).Namespace,
};
var runner = new MigrationRunner(typeof(TestMigration).Assembly, runnerContext, processor);
//runner.Processor.CommitTransaction();
runner.VersionLoader.VersionInfo.ShouldNotBeNull();
});
}
[Test]
public void CanRunMigrations()
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp(false);
runner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeTrue();
runner.VersionLoader.VersionInfo.HasAppliedMigration(2).ShouldBeTrue();
runner.VersionLoader.VersionInfo.HasAppliedMigration(3).ShouldBeTrue();
runner.VersionLoader.VersionInfo.HasAppliedMigration(4).ShouldBeTrue();
runner.VersionLoader.VersionInfo.Latest().ShouldBe(4);
runner.RollbackToVersion(0, false);
});
}
[Test]
public void CanMigrateASpecificVersion()
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
try
{
runner.MigrateUp(1, false);
runner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeTrue();
processor.TableExists(null, "Users").ShouldBeTrue();
}
finally
{
runner.RollbackToVersion(0, false);
}
});
}
[Test]
public void CanMigrateASpecificVersionDown()
{
try
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp(1, false);
runner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeTrue();
processor.TableExists(null, "Users").ShouldBeTrue();
MigrationRunner testRunner = SetupMigrationRunner(processor);
testRunner.MigrateDown(0, false);
testRunner.VersionLoader.VersionInfo.HasAppliedMigration(1).ShouldBeFalse();
processor.TableExists(null, "Users").ShouldBeFalse();
}, false, typeof(SqliteProcessor));
}
finally
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner testRunner = SetupMigrationRunner(processor);
testRunner.RollbackToVersion(0, false);
}, false);
}
}
[Test]
public void RollbackAllShouldRemoveVersionInfoTable()
{
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp(2);
processor.TableExists(runner.VersionLoader.VersionTableMetaData.SchemaName, runner.VersionLoader.VersionTableMetaData.TableName).ShouldBeTrue();
});
ExecuteWithSupportedProcessors(processor =>
{
MigrationRunner runner = SetupMigrationRunner(processor);
runner.RollbackToVersion(0);
processor.TableExists(runner.VersionLoader.VersionTableMetaData.SchemaName, runner.VersionLoader.VersionTableMetaData.TableName).ShouldBeFalse();
});
}
[Test]
public void MigrateUpWithSqlServerProcessorShouldCommitItsTransaction()
{
if (!IntegrationTestOptions.SqlServer2008.IsEnabled)
return;
var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString);
var processor = new SqlServerProcessor(connection, new SqlServer2008Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory());
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp();
try
{
processor.WasCommitted.ShouldBeTrue();
}
finally
{
CleanupTestSqlServerDatabase(connection, processor);
}
}
[Test]
public void MigrateUpSpecificVersionWithSqlServerProcessorShouldCommitItsTransaction()
{
if (!IntegrationTestOptions.SqlServer2008.IsEnabled)
return;
var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString);
var processor = new SqlServerProcessor(connection, new SqlServer2008Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory());
MigrationRunner runner = SetupMigrationRunner(processor);
runner.MigrateUp(1);
try
{
processor.WasCommitted.ShouldBeTrue();
}
finally
{
CleanupTestSqlServerDatabase(connection, processor);
}
}
[Test]
public void MigrateUpWithTaggedMigrationsShouldOnlyApplyMatchedMigrations()
{
ExecuteWithSupportedProcessors(processor =>
{
var assembly = typeof(TenantATable).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TenantATable).Namespace,
Tags = new[] { "TenantA" }
};
var runner = new MigrationRunner(assembly, runnerContext, processor);
try
{
runner.MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeTrue();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeTrue();
}
finally
{
runner.RollbackToVersion(0);
}
});
}
[Test]
public void MigrateUpWithTaggedMigrationsAndUsingMultipleTagsShouldOnlyApplyMatchedMigrations()
{
ExecuteWithSupportedProcessors(processor =>
{
var assembly = typeof(TenantATable).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TenantATable).Namespace,
Tags = new[] { "TenantA", "TenantB" }
};
var runner = new MigrationRunner(assembly, runnerContext, processor);
try
{
runner.MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeFalse();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeTrue();
}
finally
{
new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0);
}
});
}
[Test]
public void MigrateDownWithDifferentTagsToMigrateUpShouldApplyMatchedMigrations()
{
var assembly = typeof(TenantATable).Assembly;
var migrationsNamespace = typeof(TenantATable).Namespace;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = migrationsNamespace,
};
// Excluded SqliteProcessor as it errors on DB cleanup (RollbackToVersion).
ExecuteWithSupportedProcessors(processor =>
{
try
{
runnerContext.Tags = new[] { "TenantA" };
new MigrationRunner(assembly, runnerContext, processor).MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeTrue();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeTrue();
runnerContext.Tags = new[] { "TenantB" };
new MigrationRunner(assembly, runnerContext, processor).MigrateDown(0, false);
processor.TableExists(null, "TenantATable").ShouldBeTrue();
processor.TableExists(null, "NormalTable").ShouldBeFalse();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeFalse();
}
finally
{
runnerContext.Tags = new[] { "TenantA" };
new MigrationRunner(assembly, runnerContext, processor).RollbackToVersion(0, false);
}
}, true, typeof(SqliteProcessor));
}
[Test]
public void VersionInfoCreationScriptsOnlyGeneratedOnceInPreviewMode()
{
if (!IntegrationTestOptions.SqlServer2008.IsEnabled)
return;
var connection = new SqlConnection(IntegrationTestOptions.SqlServer2008.ConnectionString);
var processorOptions = new ProcessorOptions { PreviewOnly = true };
var outputSql = new StringWriter();
var announcer = new TextWriterAnnouncer(outputSql){ ShowSql = true };
var processor = new SqlServerProcessor(connection, new SqlServer2008Generator(), announcer, processorOptions, new SqlServerDbFactory());
try
{
var asm = typeof(MigrationRunnerTests).Assembly;
var runnerContext = new RunnerContext(announcer)
{
Namespace = "FluentMigrator.Tests.Integration.Migrations",
PreviewOnly = true
};
var runner = new MigrationRunner(asm, runnerContext, processor);
runner.MigrateUp(1, false);
processor.CommitTransaction();
string schemaName = new TestVersionTableMetaData().SchemaName;
var schemaAndTableName = string.Format("\\[{0}\\]\\.\\[{1}\\]", schemaName, TestVersionTableMetaData.TABLENAME);
var outputSqlString = outputSql.ToString();
var createSchemaMatches = new Regex(string.Format("CREATE SCHEMA \\[{0}\\]", schemaName)).Matches(outputSqlString).Count;
var createTableMatches = new Regex("CREATE TABLE " + schemaAndTableName).Matches(outputSqlString).Count;
var createIndexMatches = new Regex("CREATE UNIQUE CLUSTERED INDEX \\[" + TestVersionTableMetaData.UNIQUEINDEXNAME + "\\] ON " + schemaAndTableName).Matches(outputSqlString).Count;
var alterTableMatches = new Regex("ALTER TABLE " + schemaAndTableName).Matches(outputSqlString).Count;
System.Console.WriteLine(outputSqlString);
createSchemaMatches.ShouldBe(1);
createTableMatches.ShouldBe(1);
alterTableMatches.ShouldBe(2);
createIndexMatches.ShouldBe(1);
}
finally
{
CleanupTestSqlServerDatabase(connection, processor);
}
}
[Test]
public void MigrateUpWithTaggedMigrationsShouldNotApplyAnyMigrationsIfNoTagsParameterIsPassedIntoTheRunner()
{
ExecuteWithSupportedProcessors(processor =>
{
var assembly = typeof(TenantATable).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = typeof(TenantATable).Namespace
};
var runner = new MigrationRunner(assembly, runnerContext, processor);
try
{
runner.MigrateUp(false);
processor.TableExists(null, "TenantATable").ShouldBeFalse();
processor.TableExists(null, "NormalTable").ShouldBeTrue();
processor.TableExists(null, "TenantBTable").ShouldBeFalse();
processor.TableExists(null, "TenantAandBTable").ShouldBeFalse();
}
finally
{
runner.RollbackToVersion(0);
}
});
}
[Test]
public void ValidateVersionOrderShouldDoNothingIfUnappliedMigrationVersionIsGreaterThanLatestAppliedMigration()
{
// Using SqlServer instead of SqlLite as versions not deleted from VersionInfo table when using Sqlite.
var excludedProcessors = new[] { typeof(SqliteProcessor), typeof(MySqlProcessor), typeof(PostgresProcessor) };
var assembly = typeof(User).Assembly;
var runnerContext1 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass2.User).Namespace };
var runnerContext2 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass3.User).Namespace };
try
{
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext1, processor);
migrationRunner.MigrateUp(3);
}, false, excludedProcessors);
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor);
Assert.DoesNotThrow(migrationRunner.ValidateVersionOrder);
}, false, excludedProcessors);
}
finally
{
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor);
migrationRunner.RollbackToVersion(0);
}, true, excludedProcessors);
}
}
[Test]
public void ValidateVersionOrderShouldThrowExceptionIfUnappliedMigrationVersionIsLessThanLatestAppliedMigration()
{
// Using SqlServer instead of SqlLite as versions not deleted from VersionInfo table when using Sqlite.
var excludedProcessors = new[] { typeof(SqliteProcessor), typeof(MySqlProcessor), typeof(PostgresProcessor) };
var assembly = typeof(User).Assembly;
var runnerContext1 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass2.User).Namespace };
var runnerContext2 = new RunnerContext(new TextWriterAnnouncer(System.Console.Out)) { Namespace = typeof(Migrations.Interleaved.Pass3.User).Namespace };
VersionOrderInvalidException caughtException = null;
try
{
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext1, processor);
migrationRunner.MigrateUp();
}, false, excludedProcessors);
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor);
migrationRunner.ValidateVersionOrder();
}, false, excludedProcessors);
}
catch (VersionOrderInvalidException ex)
{
caughtException = ex;
}
finally
{
ExecuteWithSupportedProcessors(processor =>
{
var migrationRunner = new MigrationRunner(assembly, runnerContext2, processor);
migrationRunner.RollbackToVersion(0);
}, true, excludedProcessors);
}
caughtException.ShouldNotBeNull();
caughtException.InvalidMigrations.Count().ShouldBe(1);
var keyValuePair = caughtException.InvalidMigrations.First();
keyValuePair.Key.ShouldBe(200909060935);
keyValuePair.Value.Migration.ShouldBeOfType<UserEmail>();
}
[Test]
public void CanCreateSequence()
{
ExecuteWithSqlServer2012(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSequence());
processor.SequenceExists(null, "TestSequence");
runner.Down(new TestCreateSequence());
processor.SequenceExists(null, "TestSequence").ShouldBeFalse();
}, true);
}
[Test]
public void CanCreateSequenceWithSchema()
{
Action<IMigrationProcessor> action = processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSequence());
processor.SequenceExists("TestSchema", "TestSequence");
runner.Down(new TestCreateSequence());
processor.SequenceExists("TestSchema", "TestSequence").ShouldBeFalse();
};
ExecuteWithSqlServer2012(
action,true);
ExecuteWithPostgres(action, IntegrationTestOptions.Postgres, true);
}
[Test]
public void CanAlterColumnWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue();
processor.DefaultValueExists("TestSchema", "TestTable", "Name", "Anonymous").ShouldBeTrue();
runner.Up(new TestAlterColumnWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue();
runner.Down(new TestAlterColumnWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "Name2").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanAlterTableWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeFalse();
runner.Up(new TestAlterTableWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeTrue();
runner.Down(new TestAlterTableWithSchema());
processor.ColumnExists("TestSchema", "TestTable2", "NewColumn").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanAlterTablesSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.TableExists("TestSchema", "TestTable").ShouldBeTrue();
runner.Up(new TestAlterSchema());
processor.TableExists("NewSchema", "TestTable").ShouldBeTrue();
runner.Down(new TestAlterSchema());
processor.TableExists("TestSchema", "TestTable").ShouldBeTrue();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanCreateUniqueConstraint()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse();
runner.Up(new TestCreateUniqueConstraint());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeTrue();
runner.Down(new TestCreateUniqueConstraint());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigration());
}, true, typeof(SqliteProcessor));
}
[Test]
public void CanCreateUniqueConstraintWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse();
runner.Up(new TestCreateUniqueConstraintWithSchema());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeTrue();
runner.Down(new TestCreateUniqueConstraintWithSchema());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanInsertData()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
DataSet ds = processor.ReadTableData(null, "TestTable");
ds.Tables[0].Rows.Count.ShouldBe(1);
ds.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigration());
}, true, new[] { typeof(SqliteProcessor) });
}
[Test]
public void CanInsertDataWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
DataSet ds = processor.ReadTableData("TestSchema", "TestTable");
ds.Tables[0].Rows.Count.ShouldBe(1);
ds.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanUpdateData()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
runner.Up(new TestUpdateData());
DataSet upDs = processor.ReadTableData("TestSchema", "TestTable");
upDs.Tables[0].Rows.Count.ShouldBe(1);
upDs.Tables[0].Rows[0][1].ShouldBe("Updated");
runner.Down(new TestUpdateData());
DataSet downDs = processor.ReadTableData("TestSchema", "TestTable");
downDs.Tables[0].Rows.Count.ShouldBe(1);
downDs.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanDeleteData()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
runner.Up(new TestDeleteData());
DataSet upDs = processor.ReadTableData(null, "TestTable");
upDs.Tables[0].Rows.Count.ShouldBe(0);
runner.Down(new TestDeleteData());
DataSet downDs = processor.ReadTableData(null, "TestTable");
downDs.Tables[0].Rows.Count.ShouldBe(1);
downDs.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigration());
}, true, new[] { typeof(SqliteProcessor) });
}
[Test]
public void CanDeleteDataWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
runner.Up(new TestDeleteDataWithSchema());
DataSet upDs = processor.ReadTableData("TestSchema", "TestTable");
upDs.Tables[0].Rows.Count.ShouldBe(0);
runner.Down(new TestDeleteDataWithSchema());
DataSet downDs = processor.ReadTableData("TestSchema", "TestTable");
downDs.Tables[0].Rows.Count.ShouldBe(1);
downDs.Tables[0].Rows[0][1].ShouldBe("Test");
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor), typeof(FirebirdProcessor) });
}
[Test]
public void CanReverseCreateIndex()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
runner.Up(new TestCreateIndexWithReversing());
processor.IndexExists("TestSchema", "TestTable2", "IX_TestTable2_Name2").ShouldBeTrue();
runner.Down(new TestCreateIndexWithReversing());
processor.IndexExists("TestSchema", "TestTable2", "IX_TestTable2_Name2").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor) });
}
[Test]
public void CanReverseCreateUniqueConstraint()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateAndDropTableMigration());
runner.Up(new TestCreateUniqueConstraintWithReversing());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeTrue();
runner.Down(new TestCreateUniqueConstraintWithReversing());
processor.ConstraintExists(null, "TestTable2", "TestUnique").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigration());
}, true, new[] { typeof(SqliteProcessor) });
}
[Test]
public void CanReverseCreateUniqueConstraintWithSchema()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestCreateSchema());
runner.Up(new TestCreateAndDropTableMigrationWithSchema());
runner.Up(new TestCreateUniqueConstraintWithSchemaWithReversing());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeTrue();
runner.Down(new TestCreateUniqueConstraintWithSchemaWithReversing());
processor.ConstraintExists("TestSchema", "TestTable2", "TestUnique").ShouldBeFalse();
runner.Down(new TestCreateAndDropTableMigrationWithSchema());
runner.Down(new TestCreateSchema());
}, true, new[] { typeof(SqliteProcessor) });
}
[Test]
public void CanExecuteSql()
{
ExecuteWithSupportedProcessors(
processor =>
{
var runner = new MigrationRunner(Assembly.GetExecutingAssembly(), _runnerContext, processor);
runner.Up(new TestExecuteSql());
runner.Down(new TestExecuteSql());
}, true, new[] { typeof(FirebirdProcessor) });
}
private static MigrationRunner SetupMigrationRunner(IMigrationProcessor processor)
{
Assembly asm = typeof(MigrationRunnerTests).Assembly;
var runnerContext = new RunnerContext(new TextWriterAnnouncer(System.Console.Out))
{
Namespace = "FluentMigrator.Tests.Integration.Migrations"
};
return new MigrationRunner(asm, runnerContext, processor);
}
private static void CleanupTestSqlServerDatabase(SqlConnection connection, SqlServerProcessor origProcessor)
{
if (origProcessor.WasCommitted)
{
connection.Close();
var cleanupProcessor = new SqlServerProcessor(connection, new SqlServer2008Generator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new SqlServerDbFactory());
MigrationRunner cleanupRunner = SetupMigrationRunner(cleanupProcessor);
cleanupRunner.RollbackToVersion(0);
}
else
{
origProcessor.RollbackTransaction();
}
}
}
internal class TestForeignKeyNamingConvention : Migration
{
public override void Up()
{
Create.Table("Users")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Table("Groups")
.WithColumn("GroupId").AsInt32().Identity().PrimaryKey()
.WithColumn("Name").AsString(32).NotNullable();
Create.ForeignKey().FromTable("Users").ForeignColumn("GroupId").ToTable("Groups").PrimaryColumn("GroupId");
}
public override void Down()
{
Delete.Table("Users");
Delete.Table("Groups");
}
}
internal class TestIndexNamingConvention : Migration
{
public override void Up()
{
Create.Table("Users")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Index().OnTable("Users").OnColumn("GroupId").Ascending();
}
public override void Down()
{
Delete.Index("IX_Users_GroupId").OnTable("Users").OnColumn("GroupId");
Delete.Table("Users");
}
}
internal class TestForeignKeySilentFailure : Migration
{
public override void Up()
{
Create.Table("Users")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Table("Groups")
.WithColumn("GroupId").AsInt32().Identity().PrimaryKey()
.WithColumn("Name").AsString(32).NotNullable();
Create.ForeignKey("FK_Foo").FromTable("Users").ForeignColumn("GroupId").ToTable("Groups").PrimaryColumn("GroupId");
}
public override void Down()
{
Delete.ForeignKey("FK_Foo").OnTable("Users");
Delete.Table("Users");
Delete.Table("Groups");
}
}
internal class TestCreateAndDropTableMigration : Migration
{
public override void Up()
{
Create.Table("TestTable")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(255).NotNullable().WithDefaultValue("Anonymous");
Create.Table("TestTable2")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(255).Nullable()
.WithColumn("TestTableId").AsInt32().NotNullable();
Create.Index("ix_Name").OnTable("TestTable2").OnColumn("Name").Ascending()
.WithOptions().NonClustered();
Create.Column("Name2").OnTable("TestTable2").AsBoolean().Nullable();
Create.ForeignKey("fk_TestTable2_TestTableId_TestTable_Id")
.FromTable("TestTable2").ForeignColumn("TestTableId")
.ToTable("TestTable").PrimaryColumn("Id");
Insert.IntoTable("TestTable").Row(new { Name = "Test" });
}
public override void Down()
{
Delete.Table("TestTable2");
Delete.Table("TestTable");
}
}
internal class TestRenameTableMigration : AutoReversingMigration
{
public override void Up()
{
Rename.Table("TestTable2").To("TestTable'3");
}
}
internal class TestRenameColumnMigration : AutoReversingMigration
{
public override void Up()
{
Rename.Column("Name").OnTable("TestTable2").To("Name'3");
}
}
internal class TestCreateAndDropIndexMigration : Migration
{
public override void Up()
{
Create.Index("IX_TestTable_Name").OnTable("TestTable").OnColumn("Name");
}
public override void Down()
{
Delete.Index("IX_TestTable_Name").OnTable("TestTable");
}
}
internal class TestForeignKeyNamingConventionWithSchema : Migration
{
public override void Up()
{
Create.Schema("TestSchema");
Create.Table("Users")
.InSchema("TestSchema")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Table("Groups")
.InSchema("TestSchema")
.WithColumn("GroupId").AsInt32().Identity().PrimaryKey()
.WithColumn("Name").AsString(32).NotNullable();
Create.ForeignKey().FromTable("Users").InSchema("TestSchema").ForeignColumn("GroupId").ToTable("Groups").InSchema("TestSchema").PrimaryColumn("GroupId");
}
public override void Down()
{
Delete.Table("Users").InSchema("TestSchema");
Delete.Table("Groups").InSchema("TestSchema");
Delete.Schema("TestSchema");
}
}
internal class TestIndexNamingConventionWithSchema : Migration
{
public override void Up()
{
Create.Schema("TestSchema");
Create.Table("Users")
.InSchema("TestSchema")
.WithColumn("UserId").AsInt32().Identity().PrimaryKey()
.WithColumn("GroupId").AsInt32().NotNullable()
.WithColumn("UserName").AsString(32).NotNullable()
.WithColumn("Password").AsString(32).NotNullable();
Create.Index().OnTable("Users").InSchema("TestSchema").OnColumn("GroupId").Ascending();
}
public override void Down()
{
Delete.Index("IX_Users_GroupId").OnTable("Users").InSchema("TestSchema").OnColumn("GroupId");
Delete.Table("Users").InSchema("TestSchema");
Delete.Schema("TestSchema");
}
}
internal class TestCreateAndDropTableMigrationWithSchema : Migration
{
public override void Up()
{
Create.Table("TestTable")
.InSchema("TestSchema")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(255).NotNullable().WithDefaultValue("Anonymous");
Create.Table("TestTable2")
.InSchema("TestSchema")
.WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
.WithColumn("Name").AsString(255).Nullable()
.WithColumn("TestTableId").AsInt32().NotNullable();
Create.Index("ix_Name").OnTable("TestTable2").InSchema("TestSchema").OnColumn("Name").Ascending()
.WithOptions().NonClustered();
Create.Column("Name2").OnTable("TestTable2").InSchema("TestSchema").AsString(10).Nullable();
Create.ForeignKey("fk_TestTable2_TestTableId_TestTable_Id")
.FromTable("TestTable2").InSchema("TestSchema").ForeignColumn("TestTableId")
.ToTable("TestTable").InSchema("TestSchema").PrimaryColumn("Id");
Insert.IntoTable("TestTable").InSchema("TestSchema").Row(new { Name = "Test" });
}
public override void Down()
{
Delete.Table("TestTable2").InSchema("TestSchema");
Delete.Table("TestTable").InSchema("TestSchema");
}
}
internal class TestRenameTableMigrationWithSchema : AutoReversingMigration
{
public override void Up()
{
Rename.Table("TestTable2").InSchema("TestSchema").To("TestTable'3");
}
}
internal class TestRenameColumnMigrationWithSchema : AutoReversingMigration
{
public override void Up()
{
Rename.Column("Name").OnTable("TestTable2").InSchema("TestSchema").To("Name'3");
}
}
internal class TestCreateAndDropIndexMigrationWithSchema : Migration
{
public override void Up()
{
Create.Index("IX_TestTable_Name").OnTable("TestTable").InSchema("TestSchema").OnColumn("Name");
}
public override void Down()
{
Delete.Index("IX_TestTable_Name").OnTable("TestTable").InSchema("TestSchema");
}
}
internal class TestCreateSchema : Migration
{
public override void Up()
{
Create.Schema("TestSchema");
}
public override void Down()
{
Delete.Schema("TestSchema");
}
}
internal class TestCreateSequence : Migration
{
public override void Up()
{
Create.Sequence("TestSequence").StartWith(1).IncrementBy(1).MinValue(0).MaxValue(1000).Cycle().Cache(10);
}
public override void Down()
{
Delete.Sequence("TestSequence");
}
}
internal class TestCreateSequenceWithSchema : Migration
{
public override void Up()
{
Create.Sequence("TestSequence").InSchema("TestSchema").StartWith(1).IncrementBy(1).MinValue(0).MaxValue(1000).Cycle().Cache(10);
}
public override void Down()
{
Delete.Sequence("TestSequence").InSchema("TestSchema");
}
}
internal class TestAlterColumnWithSchema: Migration
{
public override void Up()
{
Alter.Column("Name2").OnTable("TestTable2").InSchema("TestSchema").AsAnsiString(100).Nullable();
}
public override void Down()
{
Alter.Column("Name2").OnTable("TestTable2").InSchema("TestSchema").AsString(10).Nullable();
}
}
internal class TestAlterTableWithSchema : Migration
{
public override void Up()
{
Alter.Table("TestTable2").InSchema("TestSchema").AddColumn("NewColumn").AsInt32().WithDefaultValue(1);
}
public override void Down()
{
Delete.Column("NewColumn").FromTable("TestTable2").InSchema("TestSchema");
}
}
internal class TestAlterSchema : Migration
{
public override void Up()
{
Create.Schema("NewSchema");
Alter.Table("TestTable").InSchema("TestSchema").ToSchema("NewSchema");
}
public override void Down()
{
Alter.Table("TestTable").InSchema("NewSchema").ToSchema("TestSchema");
Delete.Schema("NewSchema");
}
}
internal class TestCreateUniqueConstraint : Migration
{
public override void Up()
{
Create.UniqueConstraint("TestUnique").OnTable("TestTable2").Column("Name");
}
public override void Down()
{
Delete.UniqueConstraint("TestUnique").FromTable("TestTable2");
}
}
internal class TestCreateUniqueConstraintWithSchema : Migration
{
public override void Up()
{
Create.UniqueConstraint("TestUnique").OnTable("TestTable2").WithSchema("TestSchema").Column("Name");
}
public override void Down()
{
Delete.UniqueConstraint("TestUnique").FromTable("TestTable2").InSchema("TestSchema");
}
}
internal class TestUpdateData : Migration
{
public override void Up()
{
Update.Table("TestTable").InSchema("TestSchema").Set(new { Name = "Updated" }).AllRows();
}
public override void Down()
{
Update.Table("TestTable").InSchema("TestSchema").Set(new { Name = "Test" }).AllRows();
}
}
internal class TestDeleteData : Migration
{
public override void Up()
{
Delete.FromTable("TestTable").Row(new { Name = "Test" });
}
public override void Down()
{
Insert.IntoTable("TestTable").Row(new { Name = "Test" });
}
}
internal class TestDeleteDataWithSchema :Migration
{
public override void Up()
{
Delete.FromTable("TestTable").InSchema("TestSchema").Row(new { Name = "Test"});
}
public override void Down()
{
Insert.IntoTable("TestTable").InSchema("TestSchema").Row(new { Name = "Test" });
}
}
internal class TestCreateIndexWithReversing : AutoReversingMigration
{
public override void Up()
{
Create.Index().OnTable("TestTable2").InSchema("TestSchema").OnColumn("Name2").Ascending();
}
}
internal class TestCreateUniqueConstraintWithReversing : AutoReversingMigration
{
public override void Up()
{
Create.UniqueConstraint("TestUnique").OnTable("TestTable2").Column("Name");
}
}
internal class TestCreateUniqueConstraintWithSchemaWithReversing : AutoReversingMigration
{
public override void Up()
{
Create.UniqueConstraint("TestUnique").OnTable("TestTable2").WithSchema("TestSchema").Column("Name");
}
}
internal class TestExecuteSql : Migration
{
public override void Up()
{
Execute.Sql("select 1");
}
public override void Down()
{
Execute.Sql("select 2");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
using Blog.Web.Client.Models;
namespace Blog.Web.Client.Migrations
{
[ContextType(typeof(ApplicationDbContext))]
partial class CreateIdentitySchema
{
public override string Id
{
get { return "00000000000000_CreateIdentitySchema"; }
}
public override string ProductVersion
{
get { return "7.0.0-beta5"; }
}
public override void BuildTargetModel(ModelBuilder builder)
{
builder
.Annotation("SqlServer:ValueGeneration", "Identity");
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("NormalizedName")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity)
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity)
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ProviderKey")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ProviderDisplayName")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 1);
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("Blog.Web.Client.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<int>("AccessFailedCount")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 2);
b.Property<string>("Email")
.Annotation("OriginalValueIndex", 3);
b.Property<bool>("EmailConfirmed")
.Annotation("OriginalValueIndex", 4);
b.Property<bool>("LockoutEnabled")
.Annotation("OriginalValueIndex", 5);
b.Property<DateTimeOffset?>("LockoutEnd")
.Annotation("OriginalValueIndex", 6);
b.Property<string>("NormalizedEmail")
.Annotation("OriginalValueIndex", 7);
b.Property<string>("NormalizedUserName")
.Annotation("OriginalValueIndex", 8);
b.Property<string>("PasswordHash")
.Annotation("OriginalValueIndex", 9);
b.Property<string>("PhoneNumber")
.Annotation("OriginalValueIndex", 10);
b.Property<bool>("PhoneNumberConfirmed")
.Annotation("OriginalValueIndex", 11);
b.Property<string>("SecurityStamp")
.Annotation("OriginalValueIndex", 12);
b.Property<bool>("TwoFactorEnabled")
.Annotation("OriginalValueIndex", 13);
b.Property<string>("UserName")
.Annotation("OriginalValueIndex", 14);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Reference("Blog.Web.Client.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Reference("Blog.Web.Client.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
b.Reference("Blog.Web.Client.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace VentudaVibexDemo.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
namespace System.Windows.Forms
{
using System;
using System.ComponentModel;
using System.Reactive;
using System.Reactive.Linq;
/// <summary>
/// Extension methods providing IObservable wrappers for the events on Form.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ObservableFormEvents
{
/// <summary>
/// Returns an observable sequence wrapping the AutoSizeChanged event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the AutoSizeChanged event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> AutoSizeChangedObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.AutoSizeChanged += handler,
handler => instance.AutoSizeChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the AutoValidateChanged event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the AutoValidateChanged event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> AutoValidateChangedObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.AutoValidateChanged += handler,
handler => instance.AutoValidateChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the HelpButtonClicked event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the HelpButtonClicked event on the Form instance.</returns>
public static IObservable<EventPattern<CancelEventArgs>> HelpButtonClickedObservable(this Form instance)
{
return Observable.FromEventPattern<CancelEventHandler, CancelEventArgs>(
handler => instance.HelpButtonClicked += handler,
handler => instance.HelpButtonClicked -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the MaximizedBoundsChanged event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the MaximizedBoundsChanged event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> MaximizedBoundsChangedObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.MaximizedBoundsChanged += handler,
handler => instance.MaximizedBoundsChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the MaximumSizeChanged event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the MaximumSizeChanged event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> MaximumSizeChangedObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.MaximumSizeChanged += handler,
handler => instance.MaximumSizeChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the MarginChanged event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the MarginChanged event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> MarginChangedObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.MarginChanged += handler,
handler => instance.MarginChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the MinimumSizeChanged event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the MinimumSizeChanged event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> MinimumSizeChangedObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.MinimumSizeChanged += handler,
handler => instance.MinimumSizeChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the TabIndexChanged event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the TabIndexChanged event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> TabIndexChangedObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.TabIndexChanged += handler,
handler => instance.TabIndexChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the TabStopChanged event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the TabStopChanged event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> TabStopChangedObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.TabStopChanged += handler,
handler => instance.TabStopChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Activated event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the Activated event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> ActivatedObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.Activated += handler,
handler => instance.Activated -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Closing event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the Closing event on the Form instance.</returns>
public static IObservable<EventPattern<CancelEventArgs>> ClosingObservable(this Form instance)
{
return Observable.FromEventPattern<CancelEventHandler, CancelEventArgs>(
handler => instance.Closing += handler,
handler => instance.Closing -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Closed event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the Closed event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> ClosedObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.Closed += handler,
handler => instance.Closed -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Deactivate event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the Deactivate event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> DeactivateObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.Deactivate += handler,
handler => instance.Deactivate -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the FormClosing event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the FormClosing event on the Form instance.</returns>
public static IObservable<EventPattern<FormClosingEventArgs>> FormClosingObservable(this Form instance)
{
return Observable.FromEventPattern<FormClosingEventHandler, FormClosingEventArgs>(
handler => instance.FormClosing += handler,
handler => instance.FormClosing -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the FormClosed event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the FormClosed event on the Form instance.</returns>
public static IObservable<EventPattern<FormClosedEventArgs>> FormClosedObservable(this Form instance)
{
return Observable.FromEventPattern<FormClosedEventHandler, FormClosedEventArgs>(
handler => instance.FormClosed += handler,
handler => instance.FormClosed -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Load event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the Load event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> LoadObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.Load += handler,
handler => instance.Load -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the MdiChildActivate event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the MdiChildActivate event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> MdiChildActivateObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.MdiChildActivate += handler,
handler => instance.MdiChildActivate -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the MenuComplete event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the MenuComplete event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> MenuCompleteObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.MenuComplete += handler,
handler => instance.MenuComplete -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the MenuStart event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the MenuStart event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> MenuStartObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.MenuStart += handler,
handler => instance.MenuStart -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the InputLanguageChanged event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the InputLanguageChanged event on the Form instance.</returns>
public static IObservable<EventPattern<InputLanguageChangedEventArgs>> InputLanguageChangedObservable(this Form instance)
{
return Observable.FromEventPattern<InputLanguageChangedEventHandler, InputLanguageChangedEventArgs>(
handler => instance.InputLanguageChanged += handler,
handler => instance.InputLanguageChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the InputLanguageChanging event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the InputLanguageChanging event on the Form instance.</returns>
public static IObservable<EventPattern<InputLanguageChangingEventArgs>> InputLanguageChangingObservable(this Form instance)
{
return Observable.FromEventPattern<InputLanguageChangingEventHandler, InputLanguageChangingEventArgs>(
handler => instance.InputLanguageChanging += handler,
handler => instance.InputLanguageChanging -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the RightToLeftLayoutChanged event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the RightToLeftLayoutChanged event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> RightToLeftLayoutChangedObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.RightToLeftLayoutChanged += handler,
handler => instance.RightToLeftLayoutChanged -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the Shown event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the Shown event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> ShownObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.Shown += handler,
handler => instance.Shown -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the ResizeBegin event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the ResizeBegin event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> ResizeBeginObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.ResizeBegin += handler,
handler => instance.ResizeBegin -= handler);
}
/// <summary>
/// Returns an observable sequence wrapping the ResizeEnd event on the Form instance.
/// </summary>
/// <param name="instance">The Form instance to observe.</param>
/// <returns>An observable sequence wrapping the ResizeEnd event on the Form instance.</returns>
public static IObservable<EventPattern<EventArgs>> ResizeEndObservable(this Form instance)
{
return Observable.FromEventPattern<EventHandler, EventArgs>(
handler => instance.ResizeEnd += handler,
handler => instance.ResizeEnd -= handler);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.Management.Automation.InteropServices
{
/// <summary>
/// Variant is the basic COM type for late-binding. It can contain any other COM data type.
/// This type definition precisely matches the unmanaged data layout so that the struct can be passed
/// to and from COM calls.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal partial struct Variant
{
#if DEBUG
static Variant()
{
// Variant size is the size of 4 pointers (16 bytes) on a 32-bit processor,
// and 3 pointers (24 bytes) on a 64-bit processor.
int variantSize = Marshal.SizeOf(typeof(Variant));
if (IntPtr.Size == 4)
{
Debug.Assert(variantSize == (4 * IntPtr.Size));
}
else
{
Debug.Assert(IntPtr.Size == 8);
Debug.Assert(variantSize == (3 * IntPtr.Size));
}
}
#endif
// Most of the data types in the Variant are carried in _typeUnion
[FieldOffset(0)] private TypeUnion _typeUnion;
// Decimal is the largest data type and it needs to use the space that is normally unused in TypeUnion._wReserved1, etc.
// Hence, it is declared to completely overlap with TypeUnion. A Decimal does not use the first two bytes, and so
// TypeUnion._vt can still be used to encode the type.
[FieldOffset(0)] private decimal _decimal;
[StructLayout(LayoutKind.Sequential)]
private struct TypeUnion
{
public ushort _vt;
public ushort _wReserved1;
public ushort _wReserved2;
public ushort _wReserved3;
public UnionTypes _unionTypes;
}
[StructLayout(LayoutKind.Sequential)]
private struct Record
{
public IntPtr _record;
public IntPtr _recordInfo;
}
[StructLayout(LayoutKind.Explicit)]
private struct UnionTypes
{
[FieldOffset(0)] public sbyte _i1;
[FieldOffset(0)] public short _i2;
[FieldOffset(0)] public int _i4;
[FieldOffset(0)] public long _i8;
[FieldOffset(0)] public byte _ui1;
[FieldOffset(0)] public ushort _ui2;
[FieldOffset(0)] public uint _ui4;
[FieldOffset(0)] public ulong _ui8;
[FieldOffset(0)] public int _int;
[FieldOffset(0)] public uint _uint;
[FieldOffset(0)] public short _bool;
[FieldOffset(0)] public int _error;
[FieldOffset(0)] public float _r4;
[FieldOffset(0)] public double _r8;
[FieldOffset(0)] public long _cy;
[FieldOffset(0)] public double _date;
[FieldOffset(0)] public IntPtr _bstr;
[FieldOffset(0)] public IntPtr _unknown;
[FieldOffset(0)] public IntPtr _dispatch;
[FieldOffset(0)] public IntPtr _pvarVal;
[FieldOffset(0)] public IntPtr _byref;
[FieldOffset(0)] public Record _record;
}
/// <summary>
/// Primitive types are the basic COM types. It includes valuetypes like ints, but also reference types
/// like BStrs. It does not include composite types like arrays and user-defined COM types (IUnknown/IDispatch).
/// </summary>
public static bool IsPrimitiveType(VarEnum varEnum)
{
switch (varEnum)
{
case VarEnum.VT_I1:
case VarEnum.VT_I2:
case VarEnum.VT_I4:
case VarEnum.VT_I8:
case VarEnum.VT_UI1:
case VarEnum.VT_UI2:
case VarEnum.VT_UI4:
case VarEnum.VT_UI8:
case VarEnum.VT_INT:
case VarEnum.VT_UINT:
case VarEnum.VT_BOOL:
case VarEnum.VT_ERROR:
case VarEnum.VT_R4:
case VarEnum.VT_R8:
case VarEnum.VT_DECIMAL:
case VarEnum.VT_CY:
case VarEnum.VT_DATE:
case VarEnum.VT_BSTR:
return true;
}
return false;
}
public unsafe void CopyFromIndirect(object value)
{
VarEnum vt = (VarEnum)(((int)this.VariantType) & ~((int)VarEnum.VT_BYREF));
if (value == null)
{
if (vt == VarEnum.VT_DISPATCH || vt == VarEnum.VT_UNKNOWN || vt == VarEnum.VT_BSTR)
{
*(IntPtr*)this._typeUnion._unionTypes._byref = IntPtr.Zero;
}
return;
}
if ((vt & VarEnum.VT_ARRAY) != 0)
{
Variant vArray;
Marshal.GetNativeVariantForObject(value, (IntPtr)(void*)&vArray);
*(IntPtr*)this._typeUnion._unionTypes._byref = vArray._typeUnion._unionTypes._byref;
return;
}
switch (vt)
{
case VarEnum.VT_I1:
*(sbyte*)this._typeUnion._unionTypes._byref = (sbyte)value;
break;
case VarEnum.VT_UI1:
*(byte*)this._typeUnion._unionTypes._byref = (byte)value;
break;
case VarEnum.VT_I2:
*(short*)this._typeUnion._unionTypes._byref = (short)value;
break;
case VarEnum.VT_UI2:
*(ushort*)this._typeUnion._unionTypes._byref = (ushort)value;
break;
case VarEnum.VT_BOOL:
// VARIANT_TRUE = -1
// VARIANT_FALSE = 0
*(short*)this._typeUnion._unionTypes._byref = (bool)value ? (short)-1 : (short)0;
break;
case VarEnum.VT_I4:
case VarEnum.VT_INT:
*(int*)this._typeUnion._unionTypes._byref = (int)value;
break;
case VarEnum.VT_UI4:
case VarEnum.VT_UINT:
*(uint*)this._typeUnion._unionTypes._byref = (uint)value;
break;
case VarEnum.VT_ERROR:
*(int*)this._typeUnion._unionTypes._byref = ((ErrorWrapper)value).ErrorCode;
break;
case VarEnum.VT_I8:
*(long*)this._typeUnion._unionTypes._byref = (long)value;
break;
case VarEnum.VT_UI8:
*(ulong*)this._typeUnion._unionTypes._byref = (ulong)value;
break;
case VarEnum.VT_R4:
*(float*)this._typeUnion._unionTypes._byref = (float)value;
break;
case VarEnum.VT_R8:
*(double*)this._typeUnion._unionTypes._byref = (double)value;
break;
case VarEnum.VT_DATE:
*(double*)this._typeUnion._unionTypes._byref = ((DateTime)value).ToOADate();
break;
case VarEnum.VT_UNKNOWN:
*(IntPtr*)this._typeUnion._unionTypes._byref = Marshal.GetIUnknownForObject(value);
break;
case VarEnum.VT_DISPATCH:
*(IntPtr*)this._typeUnion._unionTypes._byref = Marshal.GetComInterfaceForObject<object, IDispatch>(value);
break;
case VarEnum.VT_BSTR:
*(IntPtr*)this._typeUnion._unionTypes._byref = Marshal.StringToBSTR((string)value);
break;
case VarEnum.VT_CY:
*(long*)this._typeUnion._unionTypes._byref = decimal.ToOACurrency((decimal)value);
break;
case VarEnum.VT_DECIMAL:
*(decimal*)this._typeUnion._unionTypes._byref = (decimal)value;
break;
case VarEnum.VT_VARIANT:
Marshal.GetNativeVariantForObject(value, this._typeUnion._unionTypes._byref);
break;
default:
throw new ArgumentException();
}
}
/// <summary>
/// Get the managed object representing the Variant.
/// </summary>
/// <returns></returns>
public object? ToObject()
{
// Check the simple case upfront
if (IsEmpty)
{
return null;
}
switch (VariantType)
{
case VarEnum.VT_NULL:
return DBNull.Value;
case VarEnum.VT_I1: return AsI1;
case VarEnum.VT_I2: return AsI2;
case VarEnum.VT_I4: return AsI4;
case VarEnum.VT_I8: return AsI8;
case VarEnum.VT_UI1: return AsUi1;
case VarEnum.VT_UI2: return AsUi2;
case VarEnum.VT_UI4: return AsUi4;
case VarEnum.VT_UI8: return AsUi8;
case VarEnum.VT_INT: return AsInt;
case VarEnum.VT_UINT: return AsUint;
case VarEnum.VT_BOOL: return AsBool;
case VarEnum.VT_ERROR: return AsError;
case VarEnum.VT_R4: return AsR4;
case VarEnum.VT_R8: return AsR8;
case VarEnum.VT_DECIMAL: return AsDecimal;
case VarEnum.VT_CY: return AsCy;
case VarEnum.VT_DATE: return AsDate;
case VarEnum.VT_BSTR: return AsBstr;
case VarEnum.VT_UNKNOWN: return AsUnknown;
case VarEnum.VT_DISPATCH: return AsDispatch;
default:
unsafe
{
fixed (void* pThis = &this)
{
return Marshal.GetObjectForNativeVariant((System.IntPtr)pThis);
}
}
}
}
[DllImport("oleaut32.dll")]
internal static extern void VariantClear(IntPtr variant);
/// <summary>
/// Release any unmanaged memory associated with the Variant
/// </summary>
public void Clear()
{
// We do not need to call OLE32's VariantClear for primitive types or ByRefs
// to save ourselves the cost of interop transition.
// ByRef indicates the memory is not owned by the VARIANT itself while
// primitive types do not have any resources to free up.
// Hence, only safearrays, BSTRs, interfaces and user types are
// handled differently.
VarEnum vt = VariantType;
if ((vt & VarEnum.VT_BYREF) != 0)
{
VariantType = VarEnum.VT_EMPTY;
}
else if (((vt & VarEnum.VT_ARRAY) != 0)
|| (vt == VarEnum.VT_BSTR)
|| (vt == VarEnum.VT_UNKNOWN)
|| (vt == VarEnum.VT_DISPATCH)
|| (vt == VarEnum.VT_VARIANT)
|| (vt == VarEnum.VT_RECORD))
{
unsafe
{
fixed (void* pThis = &this)
{
VariantClear((IntPtr)pThis);
}
}
Debug.Assert(IsEmpty);
}
else
{
VariantType = VarEnum.VT_EMPTY;
}
}
public VarEnum VariantType
{
get => (VarEnum)_typeUnion._vt;
set => _typeUnion._vt = (ushort)value;
}
public bool IsEmpty => _typeUnion._vt == ((ushort)VarEnum.VT_EMPTY);
public bool IsByRef => (_typeUnion._vt & ((ushort)VarEnum.VT_BYREF)) != 0;
public void SetAsNULL()
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_NULL;
}
// VT_I1
public sbyte AsI1
{
get
{
Debug.Assert(VariantType == VarEnum.VT_I1);
return _typeUnion._unionTypes._i1;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_I1;
_typeUnion._unionTypes._i1 = value;
}
}
// VT_I2
public short AsI2
{
get
{
Debug.Assert(VariantType == VarEnum.VT_I2);
return _typeUnion._unionTypes._i2;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_I2;
_typeUnion._unionTypes._i2 = value;
}
}
// VT_I4
public int AsI4
{
get
{
Debug.Assert(VariantType == VarEnum.VT_I4);
return _typeUnion._unionTypes._i4;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_I4;
_typeUnion._unionTypes._i4 = value;
}
}
// VT_I8
public long AsI8
{
get
{
Debug.Assert(VariantType == VarEnum.VT_I8);
return _typeUnion._unionTypes._i8;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_I8;
_typeUnion._unionTypes._i8 = value;
}
}
// VT_UI1
public byte AsUi1
{
get
{
Debug.Assert(VariantType == VarEnum.VT_UI1);
return _typeUnion._unionTypes._ui1;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_UI1;
_typeUnion._unionTypes._ui1 = value;
}
}
// VT_UI2
public ushort AsUi2
{
get
{
Debug.Assert(VariantType == VarEnum.VT_UI2);
return _typeUnion._unionTypes._ui2;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_UI2;
_typeUnion._unionTypes._ui2 = value;
}
}
// VT_UI4
public uint AsUi4
{
get
{
Debug.Assert(VariantType == VarEnum.VT_UI4);
return _typeUnion._unionTypes._ui4;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_UI4;
_typeUnion._unionTypes._ui4 = value;
}
}
// VT_UI8
public ulong AsUi8
{
get
{
Debug.Assert(VariantType == VarEnum.VT_UI8);
return _typeUnion._unionTypes._ui8;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_UI8;
_typeUnion._unionTypes._ui8 = value;
}
}
// VT_INT
public int AsInt
{
get
{
Debug.Assert(VariantType == VarEnum.VT_INT);
return _typeUnion._unionTypes._int;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_INT;
_typeUnion._unionTypes._int = value;
}
}
// VT_UINT
public uint AsUint
{
get
{
Debug.Assert(VariantType == VarEnum.VT_UINT);
return _typeUnion._unionTypes._uint;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_UINT;
_typeUnion._unionTypes._uint = value;
}
}
// VT_BOOL
public bool AsBool
{
get
{
Debug.Assert(VariantType == VarEnum.VT_BOOL);
return _typeUnion._unionTypes._bool != 0;
}
set
{
Debug.Assert(IsEmpty);
// VARIANT_TRUE = -1
// VARIANT_FALSE = 0
VariantType = VarEnum.VT_BOOL;
_typeUnion._unionTypes._bool = value ? (short)-1 : (short)0;
}
}
// VT_ERROR
public int AsError
{
get
{
Debug.Assert(VariantType == VarEnum.VT_ERROR);
return _typeUnion._unionTypes._error;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_ERROR;
_typeUnion._unionTypes._error = value;
}
}
// VT_R4
public float AsR4
{
get
{
Debug.Assert(VariantType == VarEnum.VT_R4);
return _typeUnion._unionTypes._r4;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_R4;
_typeUnion._unionTypes._r4 = value;
}
}
// VT_R8
public double AsR8
{
get
{
Debug.Assert(VariantType == VarEnum.VT_R8);
return _typeUnion._unionTypes._r8;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_R8;
_typeUnion._unionTypes._r8 = value;
}
}
// VT_DECIMAL
public decimal AsDecimal
{
get
{
Debug.Assert(VariantType == VarEnum.VT_DECIMAL);
// The first byte of Decimal is unused, but usually set to 0
Variant v = this;
v._typeUnion._vt = 0;
return v._decimal;
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_DECIMAL;
_decimal = value;
// _vt overlaps with _decimal, and should be set after setting _decimal
_typeUnion._vt = (ushort)VarEnum.VT_DECIMAL;
}
}
// VT_CY
public decimal AsCy
{
get
{
Debug.Assert(VariantType == VarEnum.VT_CY);
return decimal.FromOACurrency(_typeUnion._unionTypes._cy);
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_CY;
_typeUnion._unionTypes._cy = decimal.ToOACurrency(value);
}
}
// VT_DATE
public DateTime AsDate
{
get
{
Debug.Assert(VariantType == VarEnum.VT_DATE);
return DateTime.FromOADate(_typeUnion._unionTypes._date);
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_DATE;
_typeUnion._unionTypes._date = value.ToOADate();
}
}
// VT_BSTR
public string AsBstr
{
get
{
Debug.Assert(VariantType == VarEnum.VT_BSTR);
return (string)Marshal.PtrToStringBSTR(this._typeUnion._unionTypes._bstr);
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_BSTR;
this._typeUnion._unionTypes._bstr = Marshal.StringToBSTR(value);
}
}
// VT_UNKNOWN
public object? AsUnknown
{
get
{
Debug.Assert(VariantType == VarEnum.VT_UNKNOWN);
if (_typeUnion._unionTypes._unknown == IntPtr.Zero)
{
return null;
}
return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._unknown);
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_UNKNOWN;
if (value == null)
{
_typeUnion._unionTypes._unknown = IntPtr.Zero;
}
else
{
_typeUnion._unionTypes._unknown = Marshal.GetIUnknownForObject(value);
}
}
}
// VT_DISPATCH
public object? AsDispatch
{
get
{
Debug.Assert(VariantType == VarEnum.VT_DISPATCH);
if (_typeUnion._unionTypes._dispatch == IntPtr.Zero)
{
return null;
}
return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._dispatch);
}
set
{
Debug.Assert(IsEmpty);
VariantType = VarEnum.VT_DISPATCH;
if (value == null)
{
_typeUnion._unionTypes._dispatch = IntPtr.Zero;
}
else
{
_typeUnion._unionTypes._dispatch = Marshal.GetComInterfaceForObject<object, IDispatch>(value);
}
}
}
public IntPtr AsByRefVariant
{
get
{
Debug.Assert(VariantType == (VarEnum.VT_BYREF | VarEnum.VT_VARIANT));
return _typeUnion._unionTypes._pvarVal;
}
}
}
}
| |
//-----------------------------------------------------------------------------
//Cortex
//Copyright (c) 2010-2015, Joshua Scoggins
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without
//modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Cortex nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
//DISCLAIMED. IN NO EVENT SHALL Joshua Scoggins BE LIABLE FOR ANY
//DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
//ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Cortex.Collections
{
public interface ICell<T> : IEnumerable<T>, ICloneable
{
T this[int index] { get; }
int Length { get; }
int Count { get; }
bool IsFull { get; }
void Expand(int newSize);
bool Exists(Predicate<T> predicate);
int IndexOf(T value);
bool Add(T value);
bool Remove(T value);
bool Contains(T value);
T[] ToArray();
void Clear();
}
public class Cell<T> : ICell<T>
{
public const int DEFAULT_CAPACITY = 7;
protected T[] backingStore;
private int count;
public T this[int index] { get { return backingStore[index]; } set { backingStore[index] = value; } }
public int Count { get { return count; } protected set { count = value; } }
public int Length { get { return backingStore.Length; } }
public bool IsFull { get { return backingStore.Length == Count; } }
public Cell(IEnumerable<T> elements)
: this(elements.Count())
{
foreach(T e in elements)
Add(e);
}
public Cell(int capacity)
{
backingStore = new T[capacity];
count = 0;
}
public Cell() : this(DEFAULT_CAPACITY) { }
public void Expand(int newSize)
{
if(newSize == Length)
return;
else if(newSize < Length)
throw new ArgumentException("Given expansion size is less than the current size");
else
{
T[] newBackingStore = new T[newSize];
for(int i = 0; i < Count; i++)
{
newBackingStore[i] = backingStore[i];
backingStore[i] = default(T);
}
backingStore = newBackingStore;
}
}
public bool Exists(Predicate<T> predicate)
{
for(int i = 0; i < Count; i++)
if(predicate(backingStore[i]))
return true;
return false;
}
public int IndexOf(T value)
{
int index = 0;
Predicate<T> pred = (x) =>
{
bool result = x.Equals(value);
if(!result)
index++;
return result;
};
if(Exists(pred))
return index;
else
return -1;
}
public bool Contains(T value)
{
return IndexOf(value) != -1;
}
public bool Add(T value)
{
bool result = !IsFull;
if(result)
{
backingStore[count] = value;
count++;
}
return result;
}
///<summary>
///Used to remove all intermediate empty cells and put them at the back
///This code assumes that there is at least one free cell, otherwise it will
///do nothing. It also assumes that the starting position is empty and that we are removing
///</summary>
protected void CompressCell(int startingAt)
{
if((startingAt < (Length - 1)))
{
for(int i = startingAt; (i + 1) < Length; i++)
backingStore[i] = backingStore[i + 1];
}
}
public bool Remove(T value)
{
int index = IndexOf(value);
bool result = (index != -1);
if(result)
{
backingStore[index] = default(T);
if(index != (Count - 1))
CompressCell(index);
count--;
}
return result;
}
public bool RemoveFirst()
{
bool result = Count == 0;
if(!result)
{
backingStore[0] = default(T);
if(Count > 1)
CompressCell(0);
count--;
}
return result;
}
public bool RemoveLast()
{
bool result = Count == 0;
if(!result)
{
backingStore[Count - 1] = default(T);
count--;
}
return result;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return new CellEnumerator(this);
}
public void SecureClear()
{
//linear operation to clear it
for(int i = 0; i < Count; i++)
this[i] = default(T);
count = 0;
}
public void Clear()
{
count = 0;
//we already have the block, lets not
//waste it
}
public T[] ToArray()
{
T[] newElements = new T[backingStore.Length];
for(int i = 0; i < Count; i++)
newElements[i] = backingStore[i];
return newElements;
}
public class CellEnumerator : IEnumerator<T>
{
private T[] backingStore;
private int index, count;
public T Current { get { return backingStore[index]; } }
object IEnumerator.Current { get { return backingStore[index]; } }
public CellEnumerator(Cell<T> cell)
{
this.backingStore = cell.backingStore;
this.count = cell.count;
this.index = -1;
}
public bool MoveNext()
{
index++;
return index < count;
}
public void Reset()
{
index = -1;
}
public void Dispose()
{
backingStore = null;
}
}
public virtual object Clone()
{
return new Cell<T>(this);
}
}
}
| |
// 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.CompilerServices;
namespace System.Numerics
{
// This file contains the definitions for all of the JIT intrinsic methods and properties that are recognized by the current x64 JIT compiler.
// The implementation defined here is used in any circumstance where the JIT fails to recognize these members as intrinsic.
// The JIT recognizes these methods and properties by name and signature: if either is changed, the JIT will no longer recognize the member.
// Some methods declared here are not strictly intrinsic, but delegate to an intrinsic method. For example, only one overload of CopyTo()
// is actually recognized by the JIT, but both are here for simplicity.
public partial struct Vector3
{
/// <summary>
/// The X component of the vector.
/// </summary>
public Single X;
/// <summary>
/// The Y component of the vector.
/// </summary>
public Single Y;
/// <summary>
/// The Z component of the vector.
/// </summary>
public Single Z;
#region Constructors
/// <summary>
/// Constructs a vector whose elements are all the single specified value.
/// </summary>
/// <param name="value">The element to fill the vector with.</param>
[JitIntrinsic]
public Vector3(Single value) : this(value, value, value) { }
/// <summary>
/// Constructs a Vector3 from the given Vector2 and a third value.
/// </summary>
/// <param name="value">The Vector to extract X and Y components from.</param>
/// <param name="z">The Z component.</param>
public Vector3(Vector2 value, float z) : this(value.X, value.Y, z) { }
/// <summary>
/// Constructs a vector with the given individual elements.
/// </summary>
/// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param>
/// <param name="z">The Z component.</param>
[JitIntrinsic]
public Vector3(Single x, Single y, Single z)
{
X = x;
Y = y;
Z = z;
}
#endregion Constructors
#region Public Instance Methods
/// <summary>
/// Copies the contents of the vector into the given array.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array)
{
CopyTo(array, 0);
}
/// <summary>
/// Copies the contents of the vector into the given array, starting from index.
/// </summary>
/// <exception cref="ArgumentNullException">If array is null.</exception>
/// <exception cref="RankException">If array is multidimensional.</exception>
/// <exception cref="ArgumentOutOfRangeException">If index is greater than end of the array or index is less than zero.</exception>
/// <exception cref="ArgumentException">If number of elements in source vector is greater than those available in destination array.</exception>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void CopyTo(Single[] array, int index)
{
if (array == null)
{
// Match the JIT's exception type here. For perf, a NullReference is thrown instead of an ArgumentNull.
throw new NullReferenceException(SR.Arg_NullArgumentNullRef);
}
if (index < 0 || index >= array.Length)
{
throw new ArgumentOutOfRangeException(SR.Format(SR.Arg_ArgumentOutOfRangeException, index));
}
if ((array.Length - index) < 3)
{
throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index));
}
array[index] = X;
array[index + 1] = Y;
array[index + 2] = Z;
}
/// <summary>
/// Returns a boolean indicating whether the given Vector3 is equal to this Vector3 instance.
/// </summary>
/// <param name="other">The Vector3 to compare this instance to.</param>
/// <returns>True if the other Vector3 is equal to this instance; False otherwise.</returns>
[JitIntrinsic]
public bool Equals(Vector3 other)
{
return X == other.X &&
Y == other.Y &&
Z == other.Z;
}
#endregion Public Instance Methods
#region Public Static Methods
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="vector1">The first vector.</param>
/// <param name="vector2">The second vector.</param>
/// <returns>The dot product.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Dot(Vector3 vector1, Vector3 vector2)
{
return vector1.X * vector2.X +
vector1.Y * vector2.Y +
vector1.Z * vector2.Z;
}
/// <summary>
/// Returns a vector whose elements are the minimum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The minimized vector.</returns>
[JitIntrinsic]
public static Vector3 Min(Vector3 value1, Vector3 value2)
{
return new Vector3(
(value1.X < value2.X) ? value1.X : value2.X,
(value1.Y < value2.Y) ? value1.Y : value2.Y,
(value1.Z < value2.Z) ? value1.Z : value2.Z);
}
/// <summary>
/// Returns a vector whose elements are the maximum of each of the pairs of elements in the two source vectors.
/// </summary>
/// <param name="value1">The first source vector.</param>
/// <param name="value2">The second source vector.</param>
/// <returns>The maximized vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Max(Vector3 value1, Vector3 value2)
{
return new Vector3(
(value1.X > value2.X) ? value1.X : value2.X,
(value1.Y > value2.Y) ? value1.Y : value2.Y,
(value1.Z > value2.Z) ? value1.Z : value2.Z);
}
/// <summary>
/// Returns a vector whose elements are the absolute values of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The absolute value vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 Abs(Vector3 value)
{
return new Vector3(Math.Abs(value.X), Math.Abs(value.Y), Math.Abs(value.Z));
}
/// <summary>
/// Returns a vector whose elements are the square root of each of the source vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The square root vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 SquareRoot(Vector3 value)
{
return new Vector3((Single)Math.Sqrt(value.X), (Single)Math.Sqrt(value.Y), (Single)Math.Sqrt(value.Z));
}
#endregion Public Static Methods
#region Public Static Operators
/// <summary>
/// Adds two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator +(Vector3 left, Vector3 right)
{
return new Vector3(left.X + right.X, left.Y + right.Y, left.Z + right.Z);
}
/// <summary>
/// Subtracts the second vector from the first.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator -(Vector3 left, Vector3 right)
{
return new Vector3(left.X - right.X, left.Y - right.Y, left.Z - right.Z);
}
/// <summary>
/// Multiplies two vectors together.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The product vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Vector3 left, Vector3 right)
{
return new Vector3(left.X * right.X, left.Y * right.Y, left.Z * right.Z);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar value.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Vector3 left, Single right)
{
return left * new Vector3(right);
}
/// <summary>
/// Multiplies a vector by the given scalar.
/// </summary>
/// <param name="left">The scalar value.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator *(Single left, Vector3 right)
{
return new Vector3(left) * right;
}
/// <summary>
/// Divides the first vector by the second.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The vector resulting from the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator /(Vector3 left, Vector3 right)
{
return new Vector3(left.X / right.X, left.Y / right.Y, left.Z / right.Z);
}
/// <summary>
/// Divides the vector by the given scalar.
/// </summary>
/// <param name="value1">The source vector.</param>
/// <param name="value2">The scalar value.</param>
/// <returns>The result of the division.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator /(Vector3 value1, float value2)
{
float invDiv = 1.0f / value2;
return new Vector3(
value1.X * invDiv,
value1.Y * invDiv,
value1.Z * invDiv);
}
/// <summary>
/// Negates a given vector.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector3 operator -(Vector3 value)
{
return Zero - value;
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are equal; False otherwise.</returns>
[JitIntrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Vector3 left, Vector3 right)
{
return (left.X == right.X &&
left.Y == right.Y &&
left.Z == right.Z);
}
/// <summary>
/// Returns a boolean indicating whether the two given vectors are not equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if the vectors are not equal; False if they are equal.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(Vector3 left, Vector3 right)
{
return (left.X != right.X ||
left.Y != right.Y ||
left.Z != right.Z);
}
#endregion Public Static Operators
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using System.Runtime.InteropServices;
using System.Collections;
using System.IO;
using Microsoft.Win32;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using IServiceProvider = System.IServiceProvider;
using System.Diagnostics;
using System.Xml;
using System.Text;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
using Microsoft.VisualStudio.FSharp.LanguageService.Resources;
namespace Microsoft.VisualStudio.FSharp.LanguageService {
internal class DefaultFieldValue {
private string field;
private string value;
internal DefaultFieldValue(string field, string value) {
this.field = field;
this.value = value;
}
internal string Field {
get { return this.field; }
}
internal string Value {
get { return this.value; }
}
}
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public class ExpansionProvider : IDisposable, IVsExpansionClient {
IVsTextView view;
ISource source;
IVsExpansion vsExpansion;
IVsExpansionSession expansionSession;
bool expansionActive;
bool expansionPrepared;
bool completorActiveDuringPreExec;
ArrayList fieldDefaults; // CDefaultFieldValues
string titleToInsert;
string pathToInsert;
internal ExpansionProvider(ISource src) {
if (src == null){
throw new ArgumentNullException("src");
}
this.fieldDefaults = new ArrayList();
if (src == null)
throw new System.ArgumentNullException();
this.source = src;
this.vsExpansion = null; // do we need a Close() method here?
// QI for IVsExpansion
IVsTextLines buffer = src.GetTextLines();
this.vsExpansion = (IVsExpansion)buffer;
if (this.vsExpansion == null) {
throw new ArgumentNullException("(IVsExpansion)src.GetTextLines()");
}
}
~ExpansionProvider() {
#if LANGTRACE
Trace.WriteLine("~ExpansionProvider");
#endif
}
public virtual void Dispose() {
EndTemplateEditing(true);
this.source = null;
this.vsExpansion = null;
this.view = null;
GC.SuppressFinalize(this);
}
internal ISource Source {
get { return this.source; }
}
internal IVsTextView TextView {
get { return this.view; }
}
internal IVsExpansion Expansion {
get { return this.vsExpansion; }
}
internal IVsExpansionSession ExpansionSession {
get { return this.expansionSession; }
}
internal virtual bool HandleQueryStatus(ref Guid guidCmdGroup, uint nCmdId, out int hr) {
// in case there's something to conditinally support later on...
hr = 0;
return false;
}
internal virtual bool InTemplateEditingMode {
get {
return this.expansionActive;
}
}
internal virtual TextSpan GetExpansionSpan() {
if (this.expansionSession == null){
throw new System.InvalidOperationException(SR.GetString(SR.NoExpansionSession));
}
TextSpan[] pts = new TextSpan[1];
int hr = this.expansionSession.GetSnippetSpan(pts);
if (NativeMethods.Succeeded(hr)) {
return pts[0];
}
return new TextSpan();
}
internal virtual bool HandlePreExec(ref Guid guidCmdGroup, uint nCmdId, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (!this.expansionActive || this.expansionSession == null) {
return false;
}
this.completorActiveDuringPreExec = this.IsCompletorActive(this.view);
if (guidCmdGroup == typeof(VsCommands2K).GUID) {
VsCommands2K cmd = (VsCommands2K)nCmdId;
#if TRACE_EXEC
Trace.WriteLine(String.Format("ExecCommand: {0}", cmd.ToString()));
#endif
switch (cmd) {
case VsCommands2K.CANCEL:
if (this.completorActiveDuringPreExec)
return false;
EndTemplateEditing(true);
return true;
case VsCommands2K.RETURN:
bool leaveCaret = false;
int line = 0, col = 0;
if (NativeMethods.Succeeded(this.view.GetCaretPos(out line, out col))) {
TextSpan span = GetExpansionSpan();
if (!TextSpanHelper.ContainsExclusive(span, line, col)) {
leaveCaret = true;
}
}
if (this.completorActiveDuringPreExec)
return false;
if (this.completorActiveDuringPreExec)
return false;
EndTemplateEditing(leaveCaret);
if (leaveCaret)
return false;
return true;
case VsCommands2K.BACKTAB:
if (this.completorActiveDuringPreExec)
return false;
this.expansionSession.GoToPreviousExpansionField();
return true;
case VsCommands2K.TAB:
if (this.completorActiveDuringPreExec)
return false;
this.expansionSession.GoToNextExpansionField(0); // fCommitIfLast=false
return true;
#if TRACE_EXEC
case VsCommands2K.TYPECHAR:
if (pvaIn != IntPtr.Zero) {
Variant v = Variant.ToVariant(pvaIn);
char ch = v.ToChar();
Trace.WriteLine(String.Format("TYPECHAR: {0}, '{1}', {2}", cmd.ToString(), ch.ToString(), (int)ch));
}
return true;
#endif
}
}
return false;
}
internal virtual bool HandlePostExec(ref Guid guidCmdGroup, uint nCmdId, uint nCmdexecopt, bool commit, IntPtr pvaIn, IntPtr pvaOut) {
if (guidCmdGroup == typeof(VsCommands2K).GUID) {
VsCommands2K cmd = (VsCommands2K)nCmdId;
switch (cmd) {
case VsCommands2K.RETURN:
if (this.completorActiveDuringPreExec && commit) {
// if the completor was active during the pre-exec we want to let it handle the command first
// so we didn't deal with this in pre-exec. If we now get the command, we want to end
// the editing of the expansion. We also return that we handled the command so auto-indenting doesn't happen
EndTemplateEditing(false);
this.completorActiveDuringPreExec = false;
return true;
}
break;
}
}
this.completorActiveDuringPreExec = false;
return false;
}
internal virtual bool DisplayExpansionBrowser(IVsTextView view, string prompt, string[] types, bool includeNullType, string[] kinds, bool includeNullKind) {
if (this.expansionActive) this.EndTemplateEditing(true);
if (this.source.IsCompletorActive) {
this.source.DismissCompletor();
}
this.view = view;
IServiceProvider site = this.source.LanguageService.Site;
IVsTextManager2 textmgr = site.GetService(typeof(SVsTextManager)) as IVsTextManager2;
if (textmgr == null) return false;
IVsExpansionManager exmgr;
textmgr.GetExpansionManager(out exmgr);
Guid languageSID = this.source.LanguageService.GetLanguageServiceGuid();
int hr = 0;
if (exmgr != null) {
hr = exmgr.InvokeInsertionUI(view, // pView
this, // pClient
languageSID, // guidLang
types, // bstrTypes
(types == null) ? 0 : types.Length, // iCountTypes
includeNullType ? 1 : 0, // fIncludeNULLType
kinds, // bstrKinds
(kinds == null) ? 0 : kinds.Length, // iCountKinds
includeNullKind ? 1 : 0, // fIncludeNULLKind
prompt, // bstrPrefixText
">" //bstrCompletionChar
);
if (NativeMethods.Succeeded(hr)) {
return true;
}
}
return false;
}
internal virtual bool InsertSpecificExpansion(IVsTextView view, XmlElement snippet, TextSpan pos, string relativePath) {
if (this.expansionActive) this.EndTemplateEditing(true);
if (this.source.IsCompletorActive) {
this.source.DismissCompletor();
}
this.view = view;
MSXML.IXMLDOMDocument doc = new MSXML.DOMDocumentClass();
if (!doc.loadXML(snippet.OuterXml)) {
throw new ArgumentException(doc.parseError.reason);
}
Guid guidLanguage = this.source.LanguageService.GetLanguageServiceGuid();
int hr = this.vsExpansion.InsertSpecificExpansion(doc, pos, this, guidLanguage, relativePath, out this.expansionSession);
if (hr != NativeMethods.S_OK || this.expansionSession == null) {
this.EndTemplateEditing(true);
} else {
this.expansionActive = true;
return true;
}
return false;
}
bool IsCompletorActive(IVsTextView view){
if (this.source.IsCompletorActive)
return true;
IVsTextViewEx viewex = view as IVsTextViewEx;
if (viewex != null) {
return viewex.IsCompletorWindowActive() == Microsoft.VisualStudio.VSConstants.S_OK;
}
return false;
}
internal virtual bool InsertNamedExpansion(IVsTextView view, string title, string path, TextSpan pos, bool showDisambiguationUI) {
if (this.source.IsCompletorActive) {
this.source.DismissCompletor();
}
this.view = view;
if (this.expansionActive) this.EndTemplateEditing(true);
Guid guidLanguage = this.source.LanguageService.GetLanguageServiceGuid();
int hr = this.vsExpansion.InsertNamedExpansion(title, path, pos, this, guidLanguage, showDisambiguationUI ? 1 : 0, out this.expansionSession);
if (hr != NativeMethods.S_OK || this.expansionSession == null) {
this.EndTemplateEditing(true);
return false;
} else if (hr == NativeMethods.S_OK) {
this.expansionActive = true;
return true;
}
return false;
}
/// <summary>Returns S_OK if match found, S_FALSE if expansion UI is shown, and error otherwise</summary>
internal virtual int FindExpansionByShortcut(IVsTextView view, string shortcut, TextSpan span, bool showDisambiguationUI, out string title, out string path) {
if (this.expansionActive) this.EndTemplateEditing(true);
this.view = view;
title = path = null;
LanguageService_DEPRECATED svc = this.source.LanguageService;
IVsExpansionManager mgr = svc.Site.GetService(typeof(SVsExpansionManager)) as IVsExpansionManager;
if (mgr == null) return NativeMethods.E_FAIL ;
Guid guidLanguage = svc.GetLanguageServiceGuid();
TextSpan[] pts = new TextSpan[1];
pts[0] = span;
int hr = mgr.GetExpansionByShortcut(this, guidLanguage, shortcut, this.TextView, pts, showDisambiguationUI ? 1 : 0, out path, out title);
return hr;
}
public virtual IVsExpansionFunction GetExpansionFunction(XmlElement xmlFunctionNode, string fieldName) {
string functionName = null;
ArrayList rgFuncParams = new ArrayList();
// first off, get the function string from the node
string function = xmlFunctionNode.InnerText;
if (function == null || function.Length == 0)
return null;
bool inIdent = false;
bool inParams = false;
int token = 0;
// initialize the vars needed for our super-complex function parser :-)
for (int i = 0, n = function.Length; i < n; i++) {
char ch = function[i];
// ignore and skip whitespace
if (!Char.IsWhiteSpace(ch)) {
switch (ch) {
case ',':
if (!inIdent || !inParams)
i = n; // terminate loop
else {
// we've hit a comma, so end this param and move on...
string name = function.Substring(token, i - token);
rgFuncParams.Add(name);
inIdent = false;
}
break;
case '(':
if (!inIdent || inParams)
i = n; // terminate loop
else {
// we've hit the (, so we know the token before this is the name of the function
functionName = function.Substring(token, i - token);
inIdent = false;
inParams = true;
}
break;
case ')':
if (!inParams)
i = n; // terminate loop
else {
if (inIdent) {
// save last param and stop
string name = function.Substring(token, i - token);
rgFuncParams.Add(name);
inIdent = false;
}
i = n; // terminate loop
}
break;
default:
if (!inIdent) {
inIdent = true;
token = i;
}
break;
}
}
}
if (functionName != null && functionName.Length > 0) {
ExpansionFunction func = this.source.LanguageService.CreateExpansionFunction(this, functionName);
if (func != null) {
func.FieldName = fieldName;
func.Arguments = (string[])rgFuncParams.ToArray(typeof(string));
return func;
}
}
return null;
}
internal virtual void PrepareTemplate(string title, string path) {
if (title == null)
throw new System.ArgumentNullException("title");
// stash the title and path for when we actually insert the template
this.titleToInsert = title;
this.pathToInsert = path;
this.expansionPrepared = true;
}
void SetFieldDefault(string field, string value) {
if (!this.expansionPrepared) {
throw new System.InvalidOperationException(SR.GetString(SR.TemplateNotPrepared));
}
if (field == null) throw new System.ArgumentNullException("field");
if (value == null) throw new System.ArgumentNullException("value");
// we have an expansion "prepared" to insert, so we can now save this
// field default to set when the expansion is actually inserted
this.fieldDefaults.Add(new DefaultFieldValue(field, value));
}
internal virtual void BeginTemplateEditing(int line, int col) {
if (!this.expansionPrepared) {
throw new System.InvalidOperationException(SR.GetString(SR.TemplateNotPrepared));
}
TextSpan tsInsert = new TextSpan();
tsInsert.iStartLine = tsInsert.iEndLine = line;
tsInsert.iStartIndex = tsInsert.iEndIndex = col;
Guid languageSID = this.source.LanguageService.GetType().GUID;
int hr = this.vsExpansion.InsertNamedExpansion(this.titleToInsert,
this.pathToInsert,
tsInsert,
(IVsExpansionClient)this,
languageSID,
0, // fShowDisambiguationUI,
out this.expansionSession);
if (hr != NativeMethods.S_OK) {
this.EndTemplateEditing(true);
}
this.pathToInsert = null;
this.titleToInsert = null;
}
internal virtual void EndTemplateEditing(bool leaveCaret) {
if (!this.expansionActive || this.expansionSession == null) {
this.expansionActive = false;
return;
}
this.expansionSession.EndCurrentExpansion(leaveCaret ? 1 : 0); // fLeaveCaret=true
this.expansionSession = null;
this.expansionActive = false;
}
internal virtual bool GetFieldSpan(string field, out TextSpan pts) {
if (this.expansionSession == null) {
throw new System.InvalidOperationException(SR.GetString(SR.NoExpansionSession));
}
if (this.expansionSession != null) {
TextSpan[] apt = new TextSpan[1];
this.expansionSession.GetFieldSpan(field, apt);
pts = apt[0];
return true;
} else {
pts = new TextSpan();
return false;
}
}
internal virtual bool GetFieldValue(string field, out string value) {
if (this.expansionSession == null) {
throw new System.InvalidOperationException(SR.GetString(SR.NoExpansionSession));
}
if (this.expansionSession != null) {
this.expansionSession.GetFieldValue(field, out value);
} else {
value = null;
}
return value != null;
}
public int EndExpansion() {
this.expansionActive = false;
this.expansionSession = null;
return NativeMethods.S_OK;
}
public virtual int FormatSpan(IVsTextLines buffer, TextSpan[] ts) {
if (this.source.GetTextLines() != buffer) {
throw new System.ArgumentException(SR.GetString(SR.UnknownBuffer), "buffer");
}
int rc = NativeMethods.E_NOTIMPL;
if (ts != null) {
for (int i = 0, n = ts.Length; i < n; i++) {
if (this.source.LanguageService.Preferences.EnableFormatSelection) {
TextSpan span = ts[i];
// We should not merge edits in this case because it might clobber the
// $varname$ spans which are markers for yellow boxes.
using (EditArray edits = new EditArray(this.source, this.view, false, SR.GetString(SR.FormatSpan))) {
this.source.ReformatSpan(edits, span);
edits.ApplyEdits();
}
rc = NativeMethods.S_OK;
}
}
}
return rc;
}
public virtual int IsValidKind(IVsTextLines buffer, TextSpan[] ts, string bstrKind, out int /*BOOL*/ fIsValid)
{
fIsValid = 0;
if (this.source.GetTextLines() != buffer)
{
throw new System.ArgumentException(SR.GetString(SR.UnknownBuffer), "buffer");
}
fIsValid = 1;
return NativeMethods.S_OK;
}
public virtual int IsValidType(IVsTextLines buffer, TextSpan[] ts, string[] rgTypes, int iCountTypes, out int /*BOOL*/ fIsValid)
{
fIsValid = 0;
if (this.source.GetTextLines() != buffer) {
throw new System.ArgumentException(SR.GetString(SR.UnknownBuffer), "buffer");
}
fIsValid = 1;
return NativeMethods.S_OK;
}
public virtual int OnItemChosen(string pszTitle, string pszPath) {
TextSpan ts;
view.GetCaretPos(out ts.iStartLine, out ts.iStartIndex);
ts.iEndLine = ts.iStartLine;
ts.iEndIndex = ts.iStartIndex;
if (this.expansionSession != null) { // previous session should have been ended by now!
EndTemplateEditing(true);
}
Guid languageSID = this.source.LanguageService.GetType().GUID;
// insert the expansion
int hr = this.vsExpansion.InsertNamedExpansion(pszTitle,
pszPath,
ts,
(IVsExpansionClient)this,
languageSID,
0, // fShowDisambiguationUI, (FALSE)
out this.expansionSession);
return hr;
}
public virtual int PositionCaretForEditing(IVsTextLines pBuffer, TextSpan[] ts) {
// NOP
return NativeMethods.S_OK;
}
public virtual int OnAfterInsertion(IVsExpansionSession session) {
return NativeMethods.S_OK;
}
public virtual int OnBeforeInsertion(IVsExpansionSession session) {
if (session == null)
return NativeMethods.E_UNEXPECTED;
this.expansionPrepared = false;
this.expansionActive = true;
// stash the expansion session pointer while the expansion is active
if (this.expansionSession == null) {
this.expansionSession = session;
} else {
// these better be the same!
Debug.Assert(this.expansionSession == session);
}
// now set any field defaults that we have.
foreach (DefaultFieldValue dv in this.fieldDefaults) {
this.expansionSession.SetFieldDefault(dv.Field, dv.Value);
}
this.fieldDefaults.Clear();
return NativeMethods.S_OK;
}
public virtual int GetExpansionFunction(MSXML.IXMLDOMNode xmlFunctionNode, string fieldName, out IVsExpansionFunction func) {
XmlDocument doc = new XmlDocument();
doc.XmlResolver = null;
using(StringReader stream = new StringReader(xmlFunctionNode.xml))
using (XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings() { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null }))
{
doc.Load(reader);
func = GetExpansionFunction(doc.DocumentElement, fieldName);
}
return NativeMethods.S_OK;
}
}
[CLSCompliant(false)]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class ExpansionFunction : IVsExpansionFunction {
ExpansionProvider provider;
string fieldName;
string[] args;
string[] list;
/// <summary>You must construct this object with an ExpansionProvider</summary>
private ExpansionFunction() {
}
internal ExpansionFunction(ExpansionProvider provider) {
this.provider = provider;
}
public ExpansionProvider ExpansionProvider {
get { return this.provider; }
}
public string[] Arguments {
get { return this.args; }
set { this.args = value; }
}
public string FieldName {
get { return this.fieldName; }
set { this.fieldName = value; }
}
public abstract string GetCurrentValue();
public virtual string GetDefaultValue() {
// This must call GetCurrentValue sincs during initialization of the snippet
// VS will call GetDefaultValue and not GetCurrentValue.
return GetCurrentValue();
}
/// <summary>Override this method if you want intellisense drop support on a list of possible values.</summary>
public virtual string[] GetIntellisenseList() {
return null;
}
/// <summary>
/// Gets the value of the specified argument, resolving any fields referenced in the argument.
/// In the substitution, "$$" is replaced with "$" and any floating '$' signs are left unchanged,
/// for example "$US 23.45" is returned as is. Only if the two dollar signs enclose a string of
/// letters or digits is this considered a field name (e.g. "$foo123$"). If the field is not found
/// then the unresolved string "$foo" is returned.
/// </summary>
public string GetArgument(int index) {
if (args == null || args.Length == 0 || index > args.Length) return null;
string arg = args[index];
if (arg == null) return null;
int i = arg.IndexOf('$');
if (i >= 0) {
StringBuilder sb = new StringBuilder();
int len = arg.Length;
int start = 0;
while (i >= 0 && i + 1 < len) {
sb.Append(arg.Substring(start, i - start));
start = i;
i++;
if (arg[i] == '$') {
sb.Append('$');
start = i + 1; // $$ is resolved to $.
} else {
// parse name of variable.
int j = i;
for (; j < len; j++) {
if (!Char.IsLetterOrDigit(arg[j]))
break;
}
if (j == len) {
// terminating '$' not found.
sb.Append('$');
start = i;
break;
} else if (arg[j] == '$') {
string name = arg.Substring(i, j - i);
string value;
if (GetFieldValue(name, out value)) {
sb.Append(value);
} else {
// just return the unresolved variable.
sb.Append('$');
sb.Append(name);
sb.Append('$');
}
start = j + 1;
} else {
// invalid syntax, e.g. "$US 23.45" or some such thing
sb.Append('$');
sb.Append(arg.Substring(i, j - i));
start = j;
}
}
i = arg.IndexOf('$', start);
}
if (start < len) {
sb.Append(arg.Substring(start, len - start));
}
arg = sb.ToString();
}
// remove quotes around string literals.
if (arg.Length > 2 && arg[0] == '"' && arg[arg.Length - 1] == '"') {
arg = arg.Substring(1, arg.Length - 2);
} else if (arg.Length > 2 && arg[0] == '\'' && arg[arg.Length - 1] == '\'') {
arg = arg.Substring(1, arg.Length - 2);
}
return arg;
}
public bool GetFieldValue(string name, out string value) {
value = null;
if (this.provider != null && this.provider.ExpansionSession != null) {
int hr = this.provider.ExpansionSession.GetFieldValue(name, out value);
return NativeMethods.Succeeded(hr);
}
return false;
}
public TextSpan GetSelection() {
TextSpan result = new TextSpan();
ExpansionProvider provider = this.ExpansionProvider;
if (provider != null && provider.TextView != null) {
NativeMethods.ThrowOnFailure(provider.TextView.GetSelection(out result.iStartLine,
out result.iStartIndex, out result.iEndLine, out result.iEndIndex));
}
return result;
}
public virtual int FieldChanged(string bstrField, out int fRequeryValue) {
// Returns true if we care about this field changing.
// We care if the field changes if one of the arguments refers to it.
if (this.args != null) {
string var = "$" + bstrField + "$";
foreach (string arg in this.args) {
if (arg == var) {
fRequeryValue = 1; // we care!
return NativeMethods.S_OK;
}
}
}
fRequeryValue = 0;
return NativeMethods.S_OK;
}
public int GetCurrentValue(out string bstrValue, out int hasDefaultValue) {
try {
bstrValue = this.GetCurrentValue();
} catch {
bstrValue = String.Empty;
}
hasDefaultValue = (bstrValue == null) ? 0 : 1;
return NativeMethods.S_OK;
}
public int GetDefaultValue(out string bstrValue, out int hasCurrentValue) {
try {
bstrValue = this.GetDefaultValue();
} catch {
bstrValue = String.Empty;
}
hasCurrentValue = (bstrValue == null) ? 0 : 1;
return NativeMethods.S_OK;
}
public virtual int GetFunctionType(out uint pFuncType) {
if (this.list == null) {
this.list = this.GetIntellisenseList();
}
pFuncType = (this.list == null) ? (uint)_ExpansionFunctionType.eft_Value : (uint)_ExpansionFunctionType.eft_List;
return NativeMethods.S_OK;
}
public virtual int GetListCount(out int iListCount) {
if (this.list == null) {
this.list = this.GetIntellisenseList();
}
if (this.list != null) {
iListCount = this.list.Length;
} else {
iListCount = 0;
}
return NativeMethods.S_OK;
}
public virtual int GetListText(int iIndex, out string ppszText) {
if (this.list == null) {
this.list = this.GetIntellisenseList();
}
if (this.list != null) {
ppszText = this.list[iIndex];
} else {
ppszText = null;
}
return NativeMethods.S_OK;
}
public virtual int ReleaseFunction() {
this.provider = null;
return NativeMethods.S_OK;
}
}
// todo: for some reason VsExpansionManager is wrong.
[Guid("4970C2BC-AF33-4a73-A34F-18B0584C40E4")]
internal class SVsExpansionManager {
}
}
| |
// 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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.IO
{
/// <summary>Provides an implementation of FileSystem for Unix systems.</summary>
internal sealed partial class UnixFileSystem : FileSystem
{
public override int MaxPath { get { return Interop.libc.MaxPath; } }
public override int MaxDirectoryPath { get { return Interop.libc.MaxName; } }
public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
{
return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent);
}
public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite)
{
// Note: we could consider using sendfile here, but it isn't part of the POSIX spec, and
// has varying degrees of support on different systems.
// The destination path may just be a directory into which the file should be copied.
// If it is, append the filename from the source onto the destination directory
if (DirectoryExists(destFullPath))
{
destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath));
}
// Copy the contents of the file from the source to the destination, creating the destination in the process
const int bufferSize = FileStream.DefaultBufferSize;
const bool useAsync = false;
using (Stream src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync))
using (Stream dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync))
{
src.CopyTo(dst);
}
// Now copy over relevant read/write/execute permissions from the source to the destination
Interop.libcoreclr.fileinfo fileinfo;
while (Interop.CheckIo(Interop.libcoreclr.GetFileInformationFromPath(sourceFullPath, out fileinfo), sourceFullPath)) ;
int newMode = fileinfo.mode & (int)Interop.libc.Permissions.Mask;
while (Interop.CheckIo(Interop.libc.chmod(destFullPath, newMode), destFullPath)) ;
}
public override void MoveFile(string sourceFullPath, string destFullPath)
{
while (Interop.libc.rename(sourceFullPath, destFullPath) < 0)
{
int errno = Marshal.GetLastWin32Error();
if (errno == Interop.Errors.EINTR) // interrupted; try again
{
continue;
}
else if (errno == Interop.Errors.EXDEV) // rename fails across devices / mount points
{
CopyFile(sourceFullPath, destFullPath, overwrite: false);
DeleteFile(sourceFullPath);
break;
}
else
{
throw Interop.GetExceptionForIoErrno(errno);
}
}
}
public override void DeleteFile(string fullPath)
{
while (Interop.libc.unlink(fullPath) < 0)
{
int errno = Marshal.GetLastWin32Error();
if (errno == Interop.Errors.EINTR) // interrupted; try again
{
continue;
}
else if (errno == Interop.Errors.ENOENT) // already doesn't exist; nop
{
break;
}
else
{
if (errno == Interop.Errors.EISDIR)
errno = Interop.Errors.EACCES;
throw Interop.GetExceptionForIoErrno(errno, fullPath);
}
}
}
public override void CreateDirectory(string fullPath)
{
// NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory.
int length = fullPath.Length;
// We need to trim the trailing slash or the code will try to create 2 directories of the same name.
if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath))
{
length--;
}
// For paths that are only // or ///
if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1]))
{
throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath));
}
// We can save a bunch of work if the directory we want to create already exists.
if (DirectoryExists(fullPath))
{
return;
}
// Attempt to figure out which directories don't exist, and only create the ones we need.
bool somepathexists = false;
Stack<string> stackDir = new Stack<string>();
int lengthRoot = PathInternal.GetRootLength(fullPath);
if (length > lengthRoot)
{
int i = length - 1;
while (i >= lengthRoot && !somepathexists)
{
string dir = fullPath.Substring(0, i + 1);
if (!DirectoryExists(dir)) // Create only the ones missing
{
stackDir.Push(dir);
}
else
{
somepathexists = true;
}
while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i]))
{
i--;
}
i--;
}
}
int count = stackDir.Count;
if (count == 0 && !somepathexists)
{
string root = Directory.InternalGetDirectoryRoot(fullPath);
if (!DirectoryExists(root))
{
throw Interop.GetExceptionForIoErrno(Interop.Errors.ENOENT, fullPath, isDirectory: true);
}
return;
}
// Create all the directories
int result = 0;
int firstError = 0;
string errorString = fullPath;
while (stackDir.Count > 0)
{
string name = stackDir.Pop();
if (name.Length >= MaxDirectoryPath)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
int errno = 0;
while ((result = Interop.libc.mkdir(name, (int)Interop.libc.Permissions.S_IRWXU)) < 0 && (errno = Marshal.GetLastWin32Error()) == Interop.Errors.EINTR) ;
if (result < 0 && firstError == 0)
{
// While we tried to avoid creating directories that don't
// exist above, there are a few cases that can fail, e.g.
// a race condition where another process or thread creates
// the directory first, or there's a file at the location.
if (errno != Interop.Errors.EEXIST)
{
firstError = errno;
}
else if (FileExists(name) || (!DirectoryExists(name, out errno) && errno == Interop.Errors.EACCES))
{
// If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw.
firstError = errno;
errorString = name;
}
}
}
// Only throw an exception if creating the exact directory we wanted failed to work correctly.
if (result < 0 && firstError != 0)
{
throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true);
}
}
public override void MoveDirectory(string sourceFullPath, string destFullPath)
{
while (Interop.libc.rename(sourceFullPath, destFullPath) < 0)
{
int errno = Marshal.GetLastWin32Error();
switch (errno)
{
case Interop.Errors.EINTR: // interrupted; try again
continue;
case Interop.Errors.EACCES: // match Win32 exception
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errno);
default:
throw Interop.GetExceptionForIoErrno(errno, sourceFullPath, isDirectory: true);
}
}
}
public override void RemoveDirectory(string fullPath, bool recursive)
{
if (!DirectoryExists(fullPath))
{
throw Interop.GetExceptionForIoErrno(Interop.Errors.ENOENT, fullPath, isDirectory: true);
}
RemoveDirectoryInternal(fullPath, recursive, throwOnTopLevelDirectoryNotFound: true);
}
private void RemoveDirectoryInternal(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound)
{
Exception firstException = null;
if (recursive)
{
try
{
foreach (string item in EnumeratePaths(fullPath, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
{
if (!ShouldIgnoreDirectory(Path.GetFileName(item)))
{
try
{
if (DirectoryExists(item))
{
RemoveDirectoryInternal(item, recursive, throwOnTopLevelDirectoryNotFound: false);
}
else
{
DeleteFile(item);
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
}
}
}
catch (Exception exc)
{
if (firstException != null)
{
firstException = exc;
}
}
if (firstException != null)
{
throw firstException;
}
}
while (Interop.libc.rmdir(fullPath) < 0)
{
int errno = Marshal.GetLastWin32Error();
switch (errno)
{
case Interop.Errors.EINTR: // interrupted; try again
continue;
case Interop.Errors.EACCES:
case Interop.Errors.EPERM:
case Interop.Errors.EROFS:
case Interop.Errors.EISDIR:
throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); // match Win32 exception
case Interop.Errors.ENOENT:
if (!throwOnTopLevelDirectoryNotFound)
{
return;
}
goto default;
default:
throw Interop.GetExceptionForIoErrno(errno, fullPath, isDirectory: true);
}
}
}
public override bool DirectoryExists(string fullPath)
{
int errno;
return DirectoryExists(fullPath, out errno);
}
private static bool DirectoryExists(string fullPath, out int errno)
{
return FileExists(fullPath, Interop.libcoreclr.FileTypes.S_IFDIR, out errno);
}
public override bool FileExists(string fullPath)
{
int errno;
return FileExists(fullPath, Interop.libcoreclr.FileTypes.S_IFREG, out errno);
}
private static bool FileExists(string fullPath, int fileType, out int errno)
{
Interop.libcoreclr.fileinfo fileinfo;
while (true)
{
errno = 0;
int result = Interop.libcoreclr.GetFileInformationFromPath(fullPath, out fileinfo);
if (result < 0)
{
errno = Marshal.GetLastWin32Error();
if (errno == Interop.Errors.EINTR)
{
continue;
}
return false;
}
return (fileinfo.mode & Interop.libcoreclr.FileTypes.S_IFMT) == fileType;
}
}
public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p);
}
public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
{
switch (searchTarget)
{
case SearchTarget.Files:
return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new FileInfo(path, new UnixFileSystemObject(path, isDir)));
case SearchTarget.Directories:
return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
new DirectoryInfo(path, new UnixFileSystemObject(path, isDir)));
default:
return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ?
(FileSystemInfo)new DirectoryInfo(path, new UnixFileSystemObject(path, isDir)) :
(FileSystemInfo)new FileInfo(path, new UnixFileSystemObject(path, isDir)));
}
}
private sealed class FileSystemEnumerable<T> : IEnumerable<T>
{
private readonly PathPair _initialDirectory;
private readonly string _searchPattern;
private readonly SearchOption _searchOption;
private readonly bool _includeFiles;
private readonly bool _includeDirectories;
private readonly Func<string, bool, T> _translateResult;
private IEnumerator<T> _firstEnumerator;
internal FileSystemEnumerable(
string userPath, string searchPattern,
SearchOption searchOption, SearchTarget searchTarget,
Func<string, bool, T> translateResult)
{
// Basic validation of the input path
if (userPath == null)
{
throw new ArgumentNullException("path");
}
if (string.IsNullOrWhiteSpace(userPath))
{
throw new ArgumentException(SR.Argument_EmptyPath, "path");
}
// Validate and normalize the search pattern. If after doing so it's empty,
// matching Win32 behavior we can skip all additional validation and effectively
// return an empty enumerable.
searchPattern = NormalizeSearchPattern(searchPattern);
if (searchPattern.Length > 0)
{
PathHelpers.CheckSearchPattern(searchPattern);
PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern);
// If the search pattern contains any paths, make sure we factor those into
// the user path, and then trim them off.
int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar);
if (lastSlash >= 0)
{
if (lastSlash >= 1)
{
userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash));
}
searchPattern = searchPattern.Substring(lastSlash + 1);
}
string fullPath = Path.GetFullPath(userPath);
// Store everything for the enumerator
_initialDirectory = new PathPair(userPath, fullPath);
_searchPattern = searchPattern;
_searchOption = searchOption;
_includeFiles = (searchTarget & SearchTarget.Files) != 0;
_includeDirectories = (searchTarget & SearchTarget.Directories) != 0;
_translateResult = translateResult;
}
// Open the first enumerator so that any errors are propagated synchronously.
_firstEnumerator = Enumerate();
}
public IEnumerator<T> GetEnumerator()
{
return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private IEnumerator<T> Enumerate()
{
return Enumerate(
_initialDirectory.FullPath != null ?
OpenDirectory(_initialDirectory.FullPath) :
null);
}
private IEnumerator<T> Enumerate(Interop.libc.SafeDirHandle dirHandle)
{
if (dirHandle == null)
{
// Empty search
yield break;
}
Debug.Assert(!dirHandle.IsInvalid);
Debug.Assert(!dirHandle.IsClosed);
// Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories
// Lazily-initialized only if we find subdirectories that will be explored.
Stack<PathPair> toExplore = null;
PathPair dirPath = _initialDirectory;
while (dirHandle != null)
{
try
{
// Read each entry from the enumerator
IntPtr curEntry;
while ((curEntry = Interop.libc.readdir(dirHandle)) != IntPtr.Zero) // no validation needed for readdir
{
string name = Interop.libc.GetDirEntName(curEntry);
// Get from the dir entry whether the entry is a file or directory.
// We classify everything as a file unless we know it to be a directory,
// e.g. a FIFO will be classified as a file.
bool isDir;
switch (Interop.libc.GetDirEntType(curEntry))
{
case Interop.libc.DType.DT_DIR:
// We know it's a directory.
isDir = true;
break;
case Interop.libc.DType.DT_LNK:
case Interop.libc.DType.DT_UNKNOWN:
// It's a symlink or unknown: stat to it to see if we can resolve it to a directory.
// If we can't (e.g.symlink to a file, broken symlink, etc.), we'll just treat it as a file.
int errnoIgnored;
isDir = DirectoryExists(Path.Combine(dirPath.FullPath, name), out errnoIgnored);
break;
default:
// Otherwise, treat it as a file. This includes regular files,
// FIFOs, etc.
isDir = false;
break;
}
// Yield the result if the user has asked for it. In the case of directories,
// always explore it by pushing it onto the stack, regardless of whether
// we're returning directories.
if (isDir)
{
if (!ShouldIgnoreDirectory(name))
{
if (_includeDirectories &&
Interop.libc.fnmatch(_searchPattern, name, Interop.libc.FnmatchFlags.None) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, name), /*isDirectory*/true);
}
if (_searchOption == SearchOption.AllDirectories)
{
if (toExplore == null)
{
toExplore = new Stack<PathPair>();
}
toExplore.Push(new PathPair(Path.Combine(dirPath.UserPath, name), Path.Combine(dirPath.FullPath, name)));
}
}
}
else if (_includeFiles &&
Interop.libc.fnmatch(_searchPattern, name, Interop.libc.FnmatchFlags.None) == 0)
{
yield return _translateResult(Path.Combine(dirPath.UserPath, name), /*isDirectory*/false);
}
}
}
finally
{
// Close the directory enumerator
dirHandle.Dispose();
dirHandle = null;
}
if (toExplore != null && toExplore.Count > 0)
{
// Open the next directory.
dirPath = toExplore.Pop();
dirHandle = OpenDirectory(dirPath.FullPath);
}
}
}
private static string NormalizeSearchPattern(string searchPattern)
{
if (searchPattern == "." || searchPattern == "*.*")
{
searchPattern = "*";
}
else if (PathHelpers.EndsInDirectorySeparator(searchPattern))
{
searchPattern += "*";
}
return searchPattern;
}
private static Interop.libc.SafeDirHandle OpenDirectory(string fullPath)
{
Interop.libc.SafeDirHandle handle = Interop.libc.opendir(fullPath);
if (handle.IsInvalid)
{
throw Interop.GetExceptionForIoErrno(Marshal.GetLastWin32Error(), fullPath, isDirectory: true);
}
return handle;
}
}
/// <summary>Determines whether the specified directory name should be ignored.</summary>
/// <param name="name">The name to evaluate.</param>
/// <returns>true if the name is "." or ".."; otherwise, false.</returns>
private static bool ShouldIgnoreDirectory(string name)
{
return name == "." || name == "..";
}
public override string GetCurrentDirectory()
{
return Interop.libc.getcwd();
}
public override void SetCurrentDirectory(string fullPath)
{
while (Interop.CheckIo(Interop.libc.chdir(fullPath), fullPath)) ;
}
public override FileAttributes GetAttributes(string fullPath)
{
return new UnixFileSystemObject(fullPath, false).Attributes;
}
public override void SetAttributes(string fullPath, FileAttributes attributes)
{
new UnixFileSystemObject(fullPath, false).Attributes = attributes;
}
public override DateTimeOffset GetCreationTime(string fullPath)
{
return new UnixFileSystemObject(fullPath, false).CreationTime;
}
public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
new UnixFileSystemObject(fullPath, asDirectory).CreationTime = time;
}
public override DateTimeOffset GetLastAccessTime(string fullPath)
{
return new UnixFileSystemObject(fullPath, false).LastAccessTime;
}
public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
new UnixFileSystemObject(fullPath, asDirectory).LastAccessTime = time;
}
public override DateTimeOffset GetLastWriteTime(string fullPath)
{
return new UnixFileSystemObject(fullPath, false).LastWriteTime;
}
public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory)
{
new UnixFileSystemObject(fullPath, asDirectory).LastWriteTime = time;
}
public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory)
{
return new UnixFileSystemObject(fullPath, asDirectory);
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Linq;
namespace ServiceStack.Text.Common
{
internal static class WriteListsOfElements<TSerializer>
where TSerializer : ITypeSerializer
{
private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
static Dictionary<Type, WriteObjectDelegate> ListCacheFns = new Dictionary<Type, WriteObjectDelegate>();
public static WriteObjectDelegate GetListWriteFn(Type elementType)
{
WriteObjectDelegate writeFn;
if (ListCacheFns.TryGetValue(elementType, out writeFn)) return writeFn;
var genericType = typeof(WriteListsOfElements<,>).MakeGenericType(elementType, typeof(TSerializer));
var mi = genericType.GetPublicStaticMethod("WriteList");
writeFn = (WriteObjectDelegate)mi.MakeDelegate(typeof(WriteObjectDelegate));
Dictionary<Type, WriteObjectDelegate> snapshot, newCache;
do
{
snapshot = ListCacheFns;
newCache = new Dictionary<Type, WriteObjectDelegate>(ListCacheFns);
newCache[elementType] = writeFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref ListCacheFns, newCache, snapshot), snapshot));
return writeFn;
}
static Dictionary<Type, WriteObjectDelegate> IListCacheFns = new Dictionary<Type, WriteObjectDelegate>();
public static WriteObjectDelegate GetIListWriteFn(Type elementType)
{
WriteObjectDelegate writeFn;
if (IListCacheFns.TryGetValue(elementType, out writeFn)) return writeFn;
var genericType = typeof(WriteListsOfElements<,>).MakeGenericType(elementType, typeof(TSerializer));
var mi = genericType.GetPublicStaticMethod("WriteIList");
writeFn = (WriteObjectDelegate)mi.MakeDelegate(typeof(WriteObjectDelegate));
Dictionary<Type, WriteObjectDelegate> snapshot, newCache;
do
{
snapshot = IListCacheFns;
newCache = new Dictionary<Type, WriteObjectDelegate>(IListCacheFns);
newCache[elementType] = writeFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref IListCacheFns, newCache, snapshot), snapshot));
return writeFn;
}
static Dictionary<Type, WriteObjectDelegate> CacheFns = new Dictionary<Type, WriteObjectDelegate>();
public static WriteObjectDelegate GetGenericWriteArray(Type elementType)
{
WriteObjectDelegate writeFn;
if (CacheFns.TryGetValue(elementType, out writeFn)) return writeFn;
var genericType = typeof(WriteListsOfElements<,>).MakeGenericType(elementType, typeof(TSerializer));
var mi = genericType.GetPublicStaticMethod("WriteArray");
writeFn = (WriteObjectDelegate)mi.MakeDelegate(typeof(WriteObjectDelegate));
Dictionary<Type, WriteObjectDelegate> snapshot, newCache;
do
{
snapshot = CacheFns;
newCache = new Dictionary<Type, WriteObjectDelegate>(CacheFns);
newCache[elementType] = writeFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref CacheFns, newCache, snapshot), snapshot));
return writeFn;
}
static Dictionary<Type, WriteObjectDelegate> EnumerableCacheFns = new Dictionary<Type, WriteObjectDelegate>();
public static WriteObjectDelegate GetGenericWriteEnumerable(Type elementType)
{
WriteObjectDelegate writeFn;
if (EnumerableCacheFns.TryGetValue(elementType, out writeFn)) return writeFn;
var genericType = typeof(WriteListsOfElements<,>).MakeGenericType(elementType, typeof(TSerializer));
var mi = genericType.GetPublicStaticMethod("WriteEnumerable");
writeFn = (WriteObjectDelegate)mi.MakeDelegate(typeof(WriteObjectDelegate));
Dictionary<Type, WriteObjectDelegate> snapshot, newCache;
do
{
snapshot = EnumerableCacheFns;
newCache = new Dictionary<Type, WriteObjectDelegate>(EnumerableCacheFns);
newCache[elementType] = writeFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref EnumerableCacheFns, newCache, snapshot), snapshot));
return writeFn;
}
static Dictionary<Type, WriteObjectDelegate> ListValueTypeCacheFns = new Dictionary<Type, WriteObjectDelegate>();
public static WriteObjectDelegate GetWriteListValueType(Type elementType)
{
WriteObjectDelegate writeFn;
if (ListValueTypeCacheFns.TryGetValue(elementType, out writeFn)) return writeFn;
var genericType = typeof(WriteListsOfElements<,>).MakeGenericType(elementType, typeof(TSerializer));
var mi = genericType.GetPublicStaticMethod("WriteListValueType");
writeFn = (WriteObjectDelegate)mi.MakeDelegate(typeof(WriteObjectDelegate));
Dictionary<Type, WriteObjectDelegate> snapshot, newCache;
do
{
snapshot = ListValueTypeCacheFns;
newCache = new Dictionary<Type, WriteObjectDelegate>(ListValueTypeCacheFns);
newCache[elementType] = writeFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref ListValueTypeCacheFns, newCache, snapshot), snapshot));
return writeFn;
}
static Dictionary<Type, WriteObjectDelegate> IListValueTypeCacheFns = new Dictionary<Type, WriteObjectDelegate>();
public static WriteObjectDelegate GetWriteIListValueType(Type elementType)
{
WriteObjectDelegate writeFn;
if (IListValueTypeCacheFns.TryGetValue(elementType, out writeFn)) return writeFn;
var genericType = typeof(WriteListsOfElements<,>).MakeGenericType(elementType, typeof(TSerializer));
var mi = genericType.GetPublicStaticMethod("WriteIListValueType");
writeFn = (WriteObjectDelegate)mi.MakeDelegate(typeof(WriteObjectDelegate));
Dictionary<Type, WriteObjectDelegate> snapshot, newCache;
do
{
snapshot = IListValueTypeCacheFns;
newCache = new Dictionary<Type, WriteObjectDelegate>(IListValueTypeCacheFns);
newCache[elementType] = writeFn;
} while (!ReferenceEquals(
Interlocked.CompareExchange(ref IListValueTypeCacheFns, newCache, snapshot), snapshot));
return writeFn;
}
public static void WriteIEnumerable(TextWriter writer, object oValueCollection)
{
WriteObjectDelegate toStringFn = null;
writer.Write(JsWriter.ListStartChar);
var valueCollection = (IEnumerable)oValueCollection;
var ranOnce = false;
foreach (var valueItem in valueCollection)
{
if (toStringFn == null)
toStringFn = Serializer.GetWriteFn(valueItem.GetType());
JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce);
toStringFn(writer, valueItem);
}
writer.Write(JsWriter.ListEndChar);
}
}
internal static class WriteListsOfElements<T, TSerializer>
where TSerializer : ITypeSerializer
{
private static readonly WriteObjectDelegate ElementWriteFn;
static WriteListsOfElements()
{
ElementWriteFn = JsWriter.GetTypeSerializer<TSerializer>().GetWriteFn<T>();
}
public static void WriteList(TextWriter writer, object oList)
{
WriteGenericIList(writer, (IList<T>)oList);
}
public static void WriteGenericList(TextWriter writer, List<T> list)
{
writer.Write(JsWriter.ListStartChar);
var ranOnce = false;
var listLength = list.Count;
for (var i = 0; i < listLength; i++)
{
JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce);
ElementWriteFn(writer, list[i]);
}
writer.Write(JsWriter.ListEndChar);
}
public static void WriteListValueType(TextWriter writer, object list)
{
WriteGenericListValueType(writer, (List<T>)list);
}
public static void WriteGenericListValueType(TextWriter writer, List<T> list)
{
if (list == null) return; //AOT
writer.Write(JsWriter.ListStartChar);
var ranOnce = false;
var listLength = list.Count;
for (var i = 0; i < listLength; i++)
{
JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce);
ElementWriteFn(writer, list[i]);
}
writer.Write(JsWriter.ListEndChar);
}
public static void WriteIList(TextWriter writer, object oList)
{
WriteGenericIList(writer, (IList<T>)oList);
}
public static void WriteGenericIList(TextWriter writer, IList<T> list)
{
if (list == null) return;
writer.Write(JsWriter.ListStartChar);
var ranOnce = false;
var listLength = list.Count;
try
{
for (var i = 0; i < listLength; i++)
{
JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce);
ElementWriteFn(writer, list[i]);
}
}
catch (Exception ex)
{
Tracer.Instance.WriteError(ex);
throw;
}
writer.Write(JsWriter.ListEndChar);
}
public static void WriteIListValueType(TextWriter writer, object list)
{
WriteGenericIListValueType(writer, (IList<T>)list);
}
public static void WriteGenericIListValueType(TextWriter writer, IList<T> list)
{
if (list == null) return; //AOT
writer.Write(JsWriter.ListStartChar);
var ranOnce = false;
var listLength = list.Count;
for (var i = 0; i < listLength; i++)
{
JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce);
ElementWriteFn(writer, list[i]);
}
writer.Write(JsWriter.ListEndChar);
}
public static void WriteArray(TextWriter writer, object oArrayValue)
{
if (oArrayValue == null) return;
WriteGenericArray(writer, (Array)oArrayValue);
}
public static void WriteGenericArrayValueType(TextWriter writer, object oArray)
{
WriteGenericArrayValueType(writer, (T[])oArray);
}
public static void WriteGenericArrayValueType(TextWriter writer, T[] array)
{
if (array == null) return;
writer.Write(JsWriter.ListStartChar);
var ranOnce = false;
var arrayLength = array.Length;
for (var i = 0; i < arrayLength; i++)
{
JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce);
ElementWriteFn(writer, array[i]);
}
writer.Write(JsWriter.ListEndChar);
}
private static void WriteGenericArrayMultiDimension(TextWriter writer, Array array, int rank, int[] indices)
{
var ranOnce = false;
writer.Write(JsWriter.ListStartChar);
for (int i = 0; i < array.GetLength(rank); i++)
{
JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce);
indices[rank] = i;
if (rank < (array.Rank - 1))
WriteGenericArrayMultiDimension(writer, array, rank + 1, indices);
else
ElementWriteFn(writer, array.GetValue(indices));
}
writer.Write(JsWriter.ListEndChar);
}
public static void WriteGenericArray(TextWriter writer, Array array)
{
WriteGenericArrayMultiDimension(writer, array, 0, new int[array.Rank]);
}
public static void WriteEnumerable(TextWriter writer, object oEnumerable)
{
WriteGenericEnumerable(writer, (IEnumerable<T>)oEnumerable);
}
public static void WriteGenericEnumerable(TextWriter writer, IEnumerable<T> enumerable)
{
if (enumerable == null) return;
writer.Write(JsWriter.ListStartChar);
var ranOnce = false;
foreach (var value in enumerable)
{
JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce);
ElementWriteFn(writer, value);
}
writer.Write(JsWriter.ListEndChar);
}
public static void WriteGenericEnumerableValueType(TextWriter writer, IEnumerable<T> enumerable)
{
writer.Write(JsWriter.ListStartChar);
var ranOnce = false;
foreach (var value in enumerable)
{
JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce);
ElementWriteFn(writer, value);
}
writer.Write(JsWriter.ListEndChar);
}
}
internal static class WriteLists
{
public static void WriteListString(ITypeSerializer serializer, TextWriter writer, object list)
{
WriteListString(serializer, writer, (List<string>)list);
}
public static void WriteListString(ITypeSerializer serializer, TextWriter writer, List<string> list)
{
writer.Write(JsWriter.ListStartChar);
var ranOnce = false;
foreach (var x in list)
{
JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce);
serializer.WriteString(writer, x);
}
writer.Write(JsWriter.ListEndChar);
}
public static void WriteIListString(ITypeSerializer serializer, TextWriter writer, object list)
{
WriteIListString(serializer, writer, (IList<string>)list);
}
public static void WriteIListString(ITypeSerializer serializer, TextWriter writer, IList<string> list)
{
writer.Write(JsWriter.ListStartChar);
var ranOnce = false;
var listLength = list.Count;
for (var i = 0; i < listLength; i++)
{
JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce);
serializer.WriteString(writer, list[i]);
}
writer.Write(JsWriter.ListEndChar);
}
public static void WriteBytes(ITypeSerializer serializer, TextWriter writer, object byteValue)
{
if (byteValue == null) return;
serializer.WriteBytes(writer, byteValue);
}
public static void WriteStringArray(ITypeSerializer serializer, TextWriter writer, object oList)
{
writer.Write(JsWriter.ListStartChar);
var list = (string[])oList;
var ranOnce = false;
var listLength = list.Length;
for (var i = 0; i < listLength; i++)
{
JsWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce);
serializer.WriteString(writer, list[i]);
}
writer.Write(JsWriter.ListEndChar);
}
}
internal static class WriteLists<T, TSerializer>
where TSerializer : ITypeSerializer
{
private static readonly WriteObjectDelegate CacheFn;
private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>();
static WriteLists()
{
CacheFn = GetWriteFn();
}
public static WriteObjectDelegate Write
{
get { return CacheFn; }
}
public static WriteObjectDelegate GetWriteFn()
{
var type = typeof(T);
var listInterface = type.GetTypeWithGenericTypeDefinitionOf(typeof(IList<>));
if (listInterface == null)
throw new ArgumentException(string.Format("Type {0} is not of type IList<>", type.FullName));
//optimized access for regularly used types
if (type == typeof(List<string>))
return (w, x) => WriteLists.WriteListString(Serializer, w, x);
if (type == typeof(IList<string>))
return (w, x) => WriteLists.WriteIListString(Serializer, w, x);
if (type == typeof(List<int>))
return WriteListsOfElements<int, TSerializer>.WriteListValueType;
if (type == typeof(IList<int>))
return WriteListsOfElements<int, TSerializer>.WriteIListValueType;
if (type == typeof(List<long>))
return WriteListsOfElements<long, TSerializer>.WriteListValueType;
if (type == typeof(IList<long>))
return WriteListsOfElements<long, TSerializer>.WriteIListValueType;
var elementType = listInterface.GenericTypeArguments()[0];
var isGenericList = typeof(T).IsGeneric()
&& typeof(T).GenericTypeDefinition() == typeof(List<>);
if (elementType.IsValueType()
&& JsWriter.ShouldUseDefaultToStringMethod(elementType))
{
if (isGenericList)
return WriteListsOfElements<TSerializer>.GetWriteListValueType(elementType);
return WriteListsOfElements<TSerializer>.GetWriteIListValueType(elementType);
}
return isGenericList
? WriteListsOfElements<TSerializer>.GetListWriteFn(elementType)
: WriteListsOfElements<TSerializer>.GetIListWriteFn(elementType);
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter.Default;
namespace Microsoft.PythonTools.Interpreter {
/// <summary>
/// Provides access to an on-disk store of cached intellisense information.
/// </summary>
public sealed class PythonTypeDatabase : ITypeDatabaseReader {
private readonly PythonInterpreterFactoryWithDatabase _factory;
private readonly SharedDatabaseState _sharedState;
/// <summary>
/// Gets the version of the analysis format that this class reads.
/// </summary>
public static readonly int CurrentVersion = 25;
private static string _completionDatabasePath;
private static string _referencesDatabasePath;
private static string _baselineDatabasePath;
public PythonTypeDatabase(
PythonInterpreterFactoryWithDatabase factory,
IEnumerable<string> databaseDirectories = null,
PythonTypeDatabase innerDatabase = null
) {
if (innerDatabase != null && factory.Configuration.Version != innerDatabase.LanguageVersion) {
throw new InvalidOperationException("Language versions do not match");
}
_factory = factory;
if (innerDatabase != null) {
_sharedState = new SharedDatabaseState(innerDatabase._sharedState);
} else {
_sharedState = new SharedDatabaseState(_factory.Configuration.Version);
}
if (databaseDirectories != null) {
foreach (var d in databaseDirectories) {
LoadDatabase(d);
}
}
_sharedState.ListenForCorruptDatabase(this);
}
private PythonTypeDatabase(
PythonInterpreterFactoryWithDatabase factory,
string databaseDirectory,
bool isDefaultDatabase
) {
_factory = factory;
_sharedState = new SharedDatabaseState(
factory.Configuration.Version,
databaseDirectory,
defaultDatabase: isDefaultDatabase
);
}
public PythonTypeDatabase Clone() {
return new PythonTypeDatabase(_factory, null, this);
}
public PythonTypeDatabase CloneWithNewFactory(PythonInterpreterFactoryWithDatabase newFactory) {
return new PythonTypeDatabase(newFactory, null, this);
}
public PythonTypeDatabase CloneWithNewBuiltins(IBuiltinPythonModule newBuiltins) {
var newDb = new PythonTypeDatabase(_factory, null, this);
newDb._sharedState.BuiltinModule = newBuiltins;
return newDb;
}
public IPythonInterpreterFactoryWithDatabase InterpreterFactory {
get {
return _factory;
}
}
/// <summary>
/// Gets the Python version associated with this database.
/// </summary>
public Version LanguageVersion {
get {
return _factory.Configuration.Version;
}
}
/// <summary>
/// Loads modules from the specified path. Except for a builtins module,
/// these will override any currently loaded modules.
/// </summary>
public void LoadDatabase(string databasePath) {
_sharedState.LoadDatabase(databasePath);
}
/// <summary>
/// Asynchrously loads the specified extension module into the type
/// database making the completions available.
///
/// If the module has not already been analyzed it will be analyzed and
/// then loaded.
///
/// If the specified module was already loaded it replaces the existing
/// module.
///
/// Returns a new Task which can be blocked upon until the analysis of
/// the new extension module is available.
///
/// If the extension module cannot be analyzed an exception is reproted.
/// </summary>
/// <param name="cancellationToken">A cancellation token which can be
/// used to cancel the async loading of the module</param>
/// <param name="extensionModuleFilename">The filename of the extension
/// module to be loaded</param>
/// <param name="interpreter">The Python interprefer which will be used
/// to analyze the extension module.</param>
/// <param name="moduleName">The module name of the extension module.</param>
public Task LoadExtensionModuleAsync(string moduleName, string extensionModuleFilename, CancellationToken cancellationToken = default(CancellationToken)) {
return Task.Factory.StartNew(
new ExtensionModuleLoader(
this,
_factory,
moduleName,
extensionModuleFilename,
cancellationToken
).LoadExtensionModule
);
}
public bool UnloadExtensionModule(string moduleName) {
IPythonModule dummy;
return _sharedState.Modules.TryRemove(moduleName, out dummy);
}
private static Task MakeExceptionTask(Exception e) {
var res = new TaskCompletionSource<Task>();
res.SetException(e);
return res.Task;
}
class ExtensionModuleLoader {
private readonly PythonTypeDatabase _typeDb;
private readonly IPythonInterpreterFactory _factory;
private readonly string _moduleName;
private readonly string _extensionFilename;
private readonly CancellationToken _cancel;
const string _extensionModuleInfoFile = "extensions.$list";
public ExtensionModuleLoader(PythonTypeDatabase typeDb, IPythonInterpreterFactory factory, string moduleName, string extensionFilename, CancellationToken cancel) {
_typeDb = typeDb;
_factory = factory;
_moduleName = moduleName;
_extensionFilename = extensionFilename;
_cancel = cancel;
}
public void LoadExtensionModule() {
List<string> existingModules = new List<string>();
string dbFile = null;
// open the file locking it - only one person can look at the "database" of per-project analysis.
using (var fs = OpenProjectExtensionList()) {
dbFile = FindDbFile(_factory, _extensionFilename, existingModules, dbFile, fs);
if (dbFile == null) {
dbFile = GenerateDbFile(_factory, _moduleName, _extensionFilename, existingModules, dbFile, fs);
}
}
_typeDb._sharedState.Modules[_moduleName] = new CPythonModule(_typeDb, _moduleName, dbFile, false);
}
private void PublishModule(object state) {
}
private FileStream OpenProjectExtensionList() {
Directory.CreateDirectory(ReferencesDatabasePath);
for (int i = 0; i < 50 && !_cancel.IsCancellationRequested; i++) {
try {
return new FileStream(Path.Combine(ReferencesDatabasePath, _extensionModuleInfoFile), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
} catch (IOException) {
if (_cancel.CanBeCanceled) {
_cancel.WaitHandle.WaitOne(100);
} else {
System.Threading.Thread.Sleep(100);
}
}
}
throw new CannotAnalyzeExtensionException("Cannot access per-project extension registry.");
}
private string GenerateDbFile(IPythonInterpreterFactory interpreter, string moduleName, string extensionModuleFilename, List<string> existingModules, string dbFile, FileStream fs) {
// we need to generate the DB file
dbFile = Path.Combine(ReferencesDatabasePath, moduleName + ".$project.idb");
int retryCount = 0;
while (File.Exists(dbFile)) {
dbFile = Path.Combine(ReferencesDatabasePath, moduleName + "." + ++retryCount + ".$project.idb");
}
using (var output = interpreter.Run(
PythonToolsInstallPath.GetFile("ExtensionScraper.py"),
"scrape",
"-", // do not use __import__
extensionModuleFilename, // extension module path
Path.ChangeExtension(dbFile, null) // output file path (minus .idb)
)) {
if (_cancel.CanBeCanceled) {
if (WaitHandle.WaitAny(new[] { _cancel.WaitHandle, output.WaitHandle }) != 1) {
// we were cancelled
return null;
}
} else {
output.Wait();
}
if (output.ExitCode == 0) {
// [FileName]|interpGuid|interpVersion|DateTimeStamp|[db_file.idb]
// save the new entry in the DB file
existingModules.Add(
String.Format("{0}|{1}|{2}|{3}",
extensionModuleFilename,
interpreter.Configuration.Id,
new FileInfo(extensionModuleFilename).LastWriteTime.ToString("O"),
dbFile
)
);
fs.Seek(0, SeekOrigin.Begin);
fs.SetLength(0);
using (var sw = new StreamWriter(fs)) {
sw.Write(String.Join(Environment.NewLine, existingModules));
sw.Flush();
}
} else {
throw new CannotAnalyzeExtensionException(string.Join(Environment.NewLine, output.StandardErrorLines));
}
}
return dbFile;
}
const int extensionModuleFilenameIndex = 0;
const int interpreteIdIndex = 1;
const int extensionTimeStamp = 2;
const int dbFileIndex = 3;
/// <summary>
/// Finds the appropriate entry in our database file and returns the name of the .idb file to be loaded or null
/// if we do not have a generated .idb file.
/// </summary>
private static string FindDbFile(IPythonInterpreterFactory interpreter, string extensionModuleFilename, List<string> existingModules, string dbFile, FileStream fs) {
var reader = new StreamReader(fs);
string line;
while ((line = reader.ReadLine()) != null) {
// [FileName]|interpId|DateTimeStamp|[db_file.idb]
string[] columns = line.Split('|');
if (columns.Length != 5) {
// malformed data...
continue;
}
if (File.Exists(columns[dbFileIndex])) {
// db file still exists
DateTime lastModified;
if (!File.Exists(columns[extensionModuleFilenameIndex]) || // extension has been deleted
!DateTime.TryParseExact(columns[extensionTimeStamp], "O", null, System.Globalization.DateTimeStyles.RoundtripKind, out lastModified) ||
lastModified != File.GetLastWriteTime(columns[extensionModuleFilenameIndex])) { // extension has been modified
// cleanup the stale DB files as we go...
try {
File.Delete(columns[dbFileIndex]);
} catch (IOException) {
} catch (UnauthorizedAccessException) {
}
continue;
}
} else {
continue;
}
// check if this is the file we're looking for...
if (columns[interpreteIdIndex] != interpreter.Configuration.Id ||
String.Compare(columns[extensionModuleFilenameIndex], extensionModuleFilename, StringComparison.OrdinalIgnoreCase) != 0) { // not our interpreter
// nope, but remember the line for when we re-write out the DB.
existingModules.Add(line);
continue;
}
// this is our file, but continue reading the other lines for when we write out the DB...
dbFile = columns[dbFileIndex];
}
return dbFile;
}
}
public static PythonTypeDatabase CreateDefaultTypeDatabase(PythonInterpreterFactoryWithDatabase factory) {
return new PythonTypeDatabase(factory, BaselineDatabasePath, isDefaultDatabase: true);
}
internal static PythonTypeDatabase CreateDefaultTypeDatabase(Version languageVersion) {
return new PythonTypeDatabase(InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(languageVersion),
BaselineDatabasePath, isDefaultDatabase: true);
}
public IEnumerable<string> GetModuleNames() {
return _sharedState.GetModuleNames();
}
public IPythonModule GetModule(string name) {
return _sharedState.GetModule(name);
}
public string DatabaseDirectory {
get {
return _sharedState.DatabaseDirectory;
}
}
public IBuiltinPythonModule BuiltinModule {
get {
return _sharedState.BuiltinModule;
}
}
/// <summary>
/// The exit code returned when database generation fails due to an
/// invalid argument.
/// </summary>
public const int InvalidArgumentExitCode = -1;
/// <summary>
/// The exit code returned when database generation fails due to a
/// non-specific error.
/// </summary>
public const int InvalidOperationExitCode = -2;
/// <summary>
/// The exit code returned when a database is already being generated
/// for the interpreter factory.
/// </summary>
public const int AlreadyGeneratingExitCode = -3;
/// <summary>
/// The exit code returned when a database cannot be created for the
/// interpreter factory.
/// </summary>
public const int NotSupportedExitCode = -4;
public static async Task<int> GenerateAsync(PythonTypeDatabaseCreationRequest request) {
var fact = request.Factory;
var evt = request.OnExit;
if (fact == null || !Directory.Exists(fact.Configuration.LibraryPath)) {
if (evt != null) {
evt(NotSupportedExitCode);
}
return NotSupportedExitCode;
}
var outPath = request.OutputPath;
var analyzerPath = PythonToolsInstallPath.GetFile("Microsoft.PythonTools.Analyzer.exe");
Directory.CreateDirectory(CompletionDatabasePath);
var baseDb = BaselineDatabasePath;
if (request.ExtraInputDatabases.Any()) {
baseDb = baseDb + ";" + string.Join(";", request.ExtraInputDatabases);
}
var logPath = Path.Combine(outPath, "AnalysisLog.txt");
var glogPath = Path.Combine(CompletionDatabasePath, "AnalysisLog.txt");
using (var output = ProcessOutput.RunHiddenAndCapture(
analyzerPath,
"/id", fact.Configuration.Id,
"/version", fact.Configuration.Version.ToString(),
"/python", fact.Configuration.InterpreterPath,
request.DetectLibraryPath ? null : "/library",
request.DetectLibraryPath ? null : fact.Configuration.LibraryPath,
"/outdir", outPath,
"/basedb", baseDb,
(request.SkipUnchanged ? null : "/all"), // null will be filtered out; empty strings are quoted
"/log", logPath,
"/glog", glogPath,
"/wait", (request.WaitFor != null ? AnalyzerStatusUpdater.GetIdentifier(request.WaitFor) : "")
)) {
output.PriorityClass = ProcessPriorityClass.BelowNormal;
int exitCode = await output;
if (exitCode > -10 && exitCode < 0) {
try {
File.AppendAllLines(
glogPath,
new[] { string.Format("FAIL_STDLIB: ({0}) {1}", exitCode, output.Arguments) }
.Concat(output.StandardErrorLines)
);
} catch (IOException) {
} catch (ArgumentException) {
} catch (SecurityException) {
} catch (UnauthorizedAccessException) {
}
}
if (evt != null) {
evt(exitCode);
}
return exitCode;
}
}
/// <summary>
/// Invokes Analyzer.exe for the specified factory.
/// </summary>
[Obsolete("Use GenerateAsync instead")]
public static void Generate(PythonTypeDatabaseCreationRequest request) {
var onExit = request.OnExit;
GenerateAsync(request).ContinueWith(t => {
var exc = t.Exception;
if (exc == null) {
return;
}
try {
var message = string.Format(
"ERROR_STDLIB: {0}\\{1}{2}",
request.Factory.Configuration.Id,
Environment.NewLine,
(exc.InnerException ?? exc).ToString()
);
Debug.WriteLine(message);
var glogPath = Path.Combine(CompletionDatabasePath, "AnalysisLog.txt");
File.AppendAllText(glogPath, message);
} catch (IOException) {
} catch (ArgumentException) {
} catch (SecurityException) {
} catch (UnauthorizedAccessException) {
}
if (onExit != null) {
onExit(PythonTypeDatabase.InvalidOperationExitCode);
}
}, TaskContinuationOptions.OnlyOnFaulted);
}
private static bool DatabaseExists(string path) {
string versionFile = Path.Combine(path, "database.ver");
if (File.Exists(versionFile)) {
try {
string allLines = File.ReadAllText(versionFile);
int version;
return Int32.TryParse(allLines, out version) && version == PythonTypeDatabase.CurrentVersion;
} catch (IOException) {
}
}
return false;
}
public static string GlobalLogFilename {
get {
return Path.Combine(CompletionDatabasePath, "AnalysisLog.txt");
}
}
internal static string BaselineDatabasePath {
get {
if (_baselineDatabasePath == null) {
_baselineDatabasePath = Path.GetDirectoryName(
PythonToolsInstallPath.GetFile("CompletionDB\\__builtin__.idb")
);
}
return _baselineDatabasePath;
}
}
public static string CompletionDatabasePath {
get {
if (_completionDatabasePath == null) {
_completionDatabasePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Python Tools",
"CompletionDB",
#if DEBUG
"Debug",
#endif
AssemblyVersionInfo.Version
);
}
return _completionDatabasePath;
}
}
private static string ReferencesDatabasePath {
get {
if (_referencesDatabasePath == null) {
_referencesDatabasePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Python Tools",
"ReferencesDB",
#if DEBUG
"Debug",
#endif
AssemblyVersionInfo.Version
);
}
return _referencesDatabasePath;
}
}
void ITypeDatabaseReader.LookupType(object type, Action<IPythonType> assign) {
_sharedState.LookupType(type, assign);
}
string ITypeDatabaseReader.GetBuiltinTypeName(BuiltinTypeId id) {
return _sharedState.GetBuiltinTypeName(id);
}
void ITypeDatabaseReader.ReadMember(string memberName, Dictionary<string, object> memberValue, Action<string, IMember> assign, IMemberContainer container) {
_sharedState.ReadMember(memberName, memberValue, assign, container);
}
void ITypeDatabaseReader.OnDatabaseCorrupt() {
OnDatabaseCorrupt();
}
public void OnDatabaseCorrupt() {
_factory.NotifyCorruptDatabase();
}
internal CPythonConstant GetConstant(IPythonType type) {
return _sharedState.GetConstant(type);
}
internal static bool TryGetLocation(Dictionary<string, object> table, ref int line, ref int column) {
object value;
if (table.TryGetValue("location", out value)) {
object[] locationInfo = value as object[];
if (locationInfo != null && locationInfo.Length == 2 && locationInfo[0] is int && locationInfo[1] is int) {
line = (int)locationInfo[0];
column = (int)locationInfo[1];
return true;
}
}
return false;
}
public bool BeginModuleLoad(IPythonModule module, int millisecondsTimeout) {
return _sharedState.BeginModuleLoad(module, millisecondsTimeout);
}
public void EndModuleLoad(IPythonModule module) {
_sharedState.EndModuleLoad(module);
}
/// <summary>
/// Returns true if the specified database has a version specified that
/// matches the current build of PythonTypeDatabase. If false, attempts
/// to load the database may fail with an exception.
/// </summary>
public static bool IsDatabaseVersionCurrent(string databasePath) {
if (// Also ensures databasePath won't crash Path.Combine()
Directory.Exists(databasePath) &&
// Ensures that the database is not currently regenerating
!File.Exists(Path.Combine(databasePath, "database.pid"))) {
string versionFile = Path.Combine(databasePath, "database.ver");
if (File.Exists(versionFile)) {
try {
return int.Parse(File.ReadAllText(versionFile)) == CurrentVersion;
} catch (IOException) {
} catch (UnauthorizedAccessException) {
} catch (SecurityException) {
} catch (InvalidOperationException) {
} catch (ArgumentException) {
} catch (OverflowException) {
} catch (FormatException) {
}
}
}
return false;
}
/// <summary>
/// Returns true if the specified database is currently regenerating.
/// </summary>
public static bool IsDatabaseRegenerating(string databasePath) {
return Directory.Exists(databasePath) &&
File.Exists(Path.Combine(databasePath, "database.pid"));
}
/// <summary>
/// Gets the default set of search paths based on the path to the root
/// of the standard library.
/// </summary>
/// <param name="library">Root of the standard library.</param>
/// <returns>A list of search paths for the interpreter.</returns>
/// <remarks>New in 2.2</remarks>
public static List<PythonLibraryPath> GetDefaultDatabaseSearchPaths(string library) {
var result = new List<PythonLibraryPath>();
if (!Directory.Exists(library)) {
return result;
}
result.Add(new PythonLibraryPath(library, true, null));
var sitePackages = Path.Combine(library, "site-packages");
if (!Directory.Exists(sitePackages)) {
return result;
}
result.Add(new PythonLibraryPath(sitePackages, false, null));
result.AddRange(ModulePath.ExpandPathFiles(sitePackages)
.Select(p => new PythonLibraryPath(p, false, null))
);
return result;
}
/// <summary>
/// Gets the set of search paths by running the interpreter.
/// </summary>
/// <param name="interpreter">Path to the interpreter.</param>
/// <returns>A list of search paths for the interpreter.</returns>
/// <remarks>Added in 2.2</remarks>
public static async Task<List<PythonLibraryPath>> GetUncachedDatabaseSearchPathsAsync(string interpreter) {
List<string> lines;
// sys.path will include the working directory, so we make an empty
// path that we can filter out later
var tempWorkingDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
Directory.CreateDirectory(tempWorkingDir);
try {
using (var proc = ProcessOutput.Run(
interpreter,
new[] {
"-S", // don't import site - we do that in code
"-E", // ignore environment
"-c", "import sys;print('\\n'.join(sys.path));print('-');import site;site.main();print('\\n'.join(sys.path))"
},
tempWorkingDir,
null,
false,
null
)) {
if (await proc != 0) {
throw new InvalidOperationException(string.Format(
"Cannot obtain list of paths{0}{1}",
Environment.NewLine,
string.Join(Environment.NewLine, proc.StandardErrorLines))
);
}
lines = proc.StandardOutputLines.ToList();
}
} finally {
try {
Directory.Delete(tempWorkingDir, true);
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
}
}
var result = new List<PythonLibraryPath>();
var treatPathsAsStandardLibrary = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
bool builtinLibraries = true;
foreach (var p in lines) {
if (p == "-") {
if (builtinLibraries) {
// Seen all the builtins
builtinLibraries = false;
continue;
} else {
// Extra hyphen, so stop processing
break;
}
}
if (string.IsNullOrEmpty(p) || p == ".") {
continue;
}
string path;
try {
if (!Path.IsPathRooted(p)) {
path = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(interpreter), p));
} else {
path = Path.GetFullPath(p);
}
} catch (ArgumentException) {
continue;
} catch (PathTooLongException) {
continue;
}
if (string.Equals(p, tempWorkingDir, StringComparison.OrdinalIgnoreCase)) {
continue;
}
if (Directory.Exists(path)) {
if (builtinLibraries) {
// Looking at first section of output, which are
// considered to be the "standard library"
treatPathsAsStandardLibrary.Add(path);
} else {
// Looking at second section of output, which
// includes site-packages and .pth files
result.Add(new PythonLibraryPath(path, treatPathsAsStandardLibrary.Contains(path), null));
}
}
}
return result;
}
/// <summary>
/// Gets the set of search paths that were last saved for a database.
/// </summary>
/// <param name="databasePath">Path containing the database.</param>
/// <returns>The cached list of search paths.</returns>
/// <remarks>Added in 2.2</remarks>
public static List<PythonLibraryPath> GetCachedDatabaseSearchPaths(string databasePath) {
try {
var result = new List<PythonLibraryPath>();
using (var file = File.OpenText(Path.Combine(databasePath, "database.path"))) {
string line;
while ((line = file.ReadLine()) != null) {
try {
result.Add(PythonLibraryPath.Parse(line));
} catch (FormatException) {
Debug.Fail("Invalid format: " + line);
}
}
}
return result;
} catch (IOException) {
return null;
}
}
/// <summary>
/// Saves search paths for a database.
/// </summary>
/// <param name="databasePath">The path to the database.</param>
/// <param name="paths">The list of search paths.</param>
/// <remarks>Added in 2.2</remarks>
public static void WriteDatabaseSearchPaths(string databasePath, IEnumerable<PythonLibraryPath> paths) {
using (var file = new StreamWriter(Path.Combine(databasePath, "database.path"))) {
foreach (var path in paths) {
file.WriteLine(path.ToString());
}
}
}
/// <summary>
/// Returns ModulePaths representing the modules that should be analyzed
/// for the given search paths.
/// </summary>
/// <param name="languageVersion">
/// The Python language version to assume. This affects whether
/// namespace packages are supported or not.
/// </param>
/// <param name="searchPaths">A sequence of paths to search.</param>
/// <returns>
/// All the expected modules, grouped based on codependency. When
/// analyzing modules, all those in the same list should be analyzed
/// together.
/// </returns>
/// <remarks>Added in 2.2</remarks>
public static IEnumerable<List<ModulePath>> GetDatabaseExpectedModules(
Version languageVersion,
IEnumerable<PythonLibraryPath> searchPaths
) {
var requireInitPy = ModulePath.PythonVersionRequiresInitPyFiles(languageVersion);
var stdlibGroup = new List<ModulePath>();
var packages = new List<List<ModulePath>> { stdlibGroup };
foreach (var path in searchPaths ?? Enumerable.Empty<PythonLibraryPath>()) {
if (path.IsStandardLibrary) {
stdlibGroup.AddRange(ModulePath.GetModulesInPath(
path.Path,
includeTopLevelFiles: true,
recurse: true,
// Always require __init__.py for stdlib folders
// Otherwise we will probably include libraries multiple
// times, and while Python 3.3+ allows this, it's really
// not a good idea.
requireInitPy: true
));
} else {
packages.Add(ModulePath.GetModulesInPath(
path.Path,
includeTopLevelFiles: true,
recurse: false,
basePackage: path.ModulePrefix
).ToList());
packages.AddRange(ModulePath.GetModulesInPath(
path.Path,
includeTopLevelFiles: false,
recurse: true,
basePackage: path.ModulePrefix,
requireInitPy: requireInitPy
).GroupBy(g => g.LibraryPath).Select(g => g.ToList()));
}
}
return packages;
}
}
}
| |
/*
* EmfPlusRecordType.cs - Implementation of the
* "System.Drawing.Imaging.EmfPlusRecordType" 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
*/
namespace System.Drawing.Imaging
{
public enum EmfPlusRecordType
{
None = 0,
EmfMin = 1,
EmfHeader = 1,
EmfPolyBezier = 2,
EmfPolygon = 3,
EmfPolyline = 4,
EmfPolyBezierTo = 5,
EmfPolyLineTo = 6,
EmfPolyPolyline = 7,
EmfPolyPolygon = 8,
EmfSetWindowExtEx = 9,
EmfSetWindowOrgEx = 10,
EmfSetViewportExtEx = 11,
EmfSetViewportOrgEx = 12,
EmfSetBrushOrgEx = 13,
EmfEof = 14,
EmfSetPixelV = 15,
EmfSetMapperFlags = 16,
EmfSetMapMode = 17,
EmfSetBkMode = 18,
EmfSetPolyFillMode = 19,
EmfSetROP2 = 20,
EmfSetStretchBltMode = 21,
EmfSetTextAlign = 22,
EmfSetColorAdjustment = 23,
EmfSetTextColor = 24,
EmfSetBkColor = 25,
EmfOffsetClipRgn = 26,
EmfMoveToEx = 27,
EmfSetMetaRgn = 28,
EmfExcludeClipRect = 29,
EmfIntersectClipRect = 30,
EmfScaleViewportExtEx = 31,
EmfScaleWindowExtEx = 32,
EmfSaveDC = 33,
EmfRestoreDC = 34,
EmfSetWorldTransform = 35,
EmfModifyWorldTransform = 36,
EmfSelectObject = 37,
EmfCreatePen = 38,
EmfCreateBrushIndirect = 39,
EmfDeleteObject = 40,
EmfAngleArc = 41,
EmfEllipse = 42,
EmfRectangle = 43,
EmfRoundRect = 44,
EmfRoundArc = 45,
EmfChord = 46,
EmfPie = 47,
EmfSelectPalette = 48,
EmfCreatePalette = 49,
EmfSetPaletteEntries = 50,
EmfResizePalette = 51,
EmfRealizePalette = 52,
EmfExtFloodFill = 53,
EmfLineTo = 54,
EmfArcTo = 55,
EmfPolyDraw = 56,
EmfSetArcDirection = 57,
EmfSetMiterLimit = 58,
EmfBeginPath = 59,
EmfEndPath = 60,
EmfCloseFigure = 61,
EmfFillPath = 62,
EmfStrokeAndFillPath = 63,
EmfStrokePath = 64,
EmfFlattenPath = 65,
EmfWidenPath = 66,
EmfSelectClipPath = 67,
EmfAbortPath = 68,
EmfReserved069 = 69,
EmfGdiComment = 70,
EmfFillRgn = 71,
EmfFrameRgn = 72,
EmfInvertRgn = 73,
EmfPaintRgn = 74,
EmfExtSelectClipRgn = 75,
EmfBitBlt = 76,
EmfStretchBlt = 77,
EmfMaskBlt = 78,
EmfPlgBlt = 79,
EmfSetDIBitsToDevice = 80,
EmfStretchDIBits = 81,
EmfExtCreateFontIndirect = 82,
EmfExtTextOutA = 83,
EmfExtTextOutW = 84,
EmfPolyBezier16 = 85,
EmfPolygon16 = 86,
EmfPolyline16 = 87,
EmfPolyBezierTo16 = 88,
EmfPolylineTo16 = 89,
EmfPolyPolyline16 = 90,
EmfPolyPolygon16 = 91,
EmfPolyDraw16 = 92,
EmfCreateMonoBrush = 93,
EmfCreateDibPatternBrushPt = 94,
EmfExtCreatePen = 95,
EmfPolyTextOutA = 96,
EmfPolyTextOutW = 97,
EmfSetIcmMode = 98,
EmfCreateColorSpace = 99,
EmfSetColorSpace = 100,
EmfDeleteColorSpace = 101,
EmfGlsRecord = 102,
EmfGlsBoundedRecord = 103,
EmfPixelFormat = 104,
EmfDrawEscape = 105,
EmfExtEscape = 106,
EmfStartDoc = 107,
EmfSmallTextOut = 108,
EmfForceUfiMapping = 109,
EmfNamedEscpae = 110,
EmfColorCorrectPalette = 111,
EmfSetIcmProfileA = 112,
EmfSetIcmProfileW = 113,
EmfAlphaBlend = 114,
EmfSetLayout = 115,
EmfTransparentBlt = 116,
EmfReserved117 = 117,
EmfGradientFill = 118,
EmfSetLinkedUfis = 119,
EmfSetTextJustification = 120,
EmfColorMatchToTargetW = 121,
EmfCreateColorSpaceW = 122,
EmfPlusRecordBase = 16384,
Invalid = 16384,
Min = 16385,
Header = 16385,
EndOfFile = 16386,
Comment = 16387,
GetDC = 16388,
MultiFormatStart = 16389,
MultiFormatSection = 16390,
MultiFormatEnd = 16391,
Object = 16392,
Clear = 16393,
FillRects = 16394,
DrawRects = 16395,
FillPolygon = 16396,
DrawLines = 16397,
FillEllipse = 16398,
DrawEllipse = 16399,
FillPie = 16400,
DrawPie = 16401,
DrawArc = 16402,
FillRegion = 16403,
FillPath = 16404,
DrawPath = 16405,
FillClosedCurve = 16406,
DrawClosedCurve = 16407,
DrawCurve = 16408,
DrawBeziers = 16409,
DrawImage = 16410,
DrawImagePoints = 16411,
DrawString = 16412,
SetRenderingOrigin = 16413,
SetAntiAliasMode = 16414,
SetTextRenderingHint = 16415,
SetTextContrast = 16416,
SetInterpolationMode = 16417,
SetPixelOffsetMode = 16418,
SetCompositingMode = 16419,
SetCompositingQuality = 16420,
Save = 16421,
Restore = 16422,
BeginContainer = 16423,
BeginContainerNoParams = 16424,
EndContainer = 16425,
SetWorldTransform = 16426,
ResetWorldTransform = 16427,
MultiplyWorldTransform = 16428,
TranslateWorldTransform = 16429,
ScaleWorldTransform = 16430,
RotateWorldTransform = 16431,
SetPageTransform = 16432,
ResetClip = 16433,
SetClipRect = 16434,
SetClipPath = 16435,
SetClipRegion = 16436,
OffsetClip = 16437,
DrawDriverString = 16438,
Max = 16438,
Total = 16439,
WmfRecordBase = 65536,
WmfSaveDC = 65566,
WmfRealizePalette = 65589,
WmfSetPalEntries = 65591,
WmfCreatePalette = 65783,
WmfSetBkMode = 65794,
WmfSetMapMode = 65795,
WmfSetROP2 = 65796,
WmfSetRelAbs = 65797,
WmfSetPolyFillMode = 65798,
WmfSetStretchBltMode = 65799,
WmfSetTextCharExtra = 65800,
WmfRestoreDC = 65831,
WmfInvertRegion = 65834,
WmfPaintRegion = 65835,
WmfSelectClipRegion = 65836,
WmfSelectObject = 65837,
WmfSetTextAlign = 65838,
WmfResizePalette = 65849,
WmfDibCreatePatternBrush = 65858,
WmfSetLayout = 65865,
WmfDeleteObject = 66032,
WmfCreatePatternBrush = 66041,
WmfSetBkColor = 66049,
WmfSetTextColor = 66057,
WmfSetTextJustification = 66058,
WmfSetWindowOrg = 66059,
WmfSetWindowExt = 66060,
WmfSetViewportOrg = 66061,
WmfSetViewportExt = 66062,
WmfOffsetWindowOrg = 66063,
WmfOffsetViewportOrg = 66065,
WmfLineTo = 66067,
WmfMoveTo = 66068,
WmfOffsetCilpRgn = 66080,
WmfFillRegion = 66088,
WmfSetMapperFlags = 66097,
WmfSelectPalette = 66100,
WmfCreatePenIndirect = 66298,
WmfCreateFontIndirect = 66299,
WmfCreateBrushIndirect = 66300,
WmfPolygon = 66340,
WmfPolyline = 66341,
WmfScaleWindowExt = 66576,
WmfScaleViewportExt = 66578,
WmfExcludeClipRect = 66581,
WmfIntersectClipRect = 66582,
WmfFloodFill = 66585,
WmfEllipse = 66584,
WmfRectangle = 66587,
WmfSetPixel = 66591,
WmfFrameRegion = 66601,
WmfAnimatePalette = 66614,
WmfTextOut = 66849,
WmfPolyPolygon = 66872,
WmfExtFloodFill = 66888,
WmfRoundRect = 67100,
WmfPatBlt = 67101,
WmfEscape = 67110,
WmfCreateRegion = 67327,
WmfArc = 67607,
WmfPie = 67610,
WmfChord = 67632,
WmfBitBlt = 67874,
WmfDibBitBlt = 67904,
WmfExtTextOut = 68146,
WmfStretchBlt = 68387,
WmfDibStretchBlt = 68417,
WmfSetDibToDev = 68915,
WmfStretchDib = 69443
}; // enum EmfPlusRecordType
}; // namespace System.Drawing.Imaging
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using GitVersion.Logging;
using LibGit2Sharp;
namespace GitVersion.Extensions
{
public static class RepositoryExtensions
{
public static string GetRepositoryDirectory(this IRepository repository, bool omitGitPostFix = true)
{
var gitDirectory = repository.Info.Path;
gitDirectory = gitDirectory.TrimEnd(Path.DirectorySeparatorChar);
if (omitGitPostFix && gitDirectory.EndsWith(".git"))
{
gitDirectory = gitDirectory.Substring(0, gitDirectory.Length - ".git".Length);
gitDirectory = gitDirectory.TrimEnd(Path.DirectorySeparatorChar);
}
return gitDirectory;
}
public static Branch FindBranch(this IRepository repository, string branchName)
{
return repository.Branches.FirstOrDefault(x => x.NameWithoutRemote() == branchName);
}
public static void DumpGraph(this IRepository repository, Action<string> writer = null, int? maxCommits = null)
{
LibGitExtensions.DumpGraph(repository.Info.Path, writer, maxCommits);
}
public static void EnsureLocalBranchExistsForCurrentBranch(this IGitRepository repo, ILog log, Remote remote, string currentBranch)
{
if (log is null)
{
throw new ArgumentNullException(nameof(log));
}
if (remote is null)
{
throw new ArgumentNullException(nameof(remote));
}
if (string.IsNullOrEmpty(currentBranch)) return;
var isRef = currentBranch.Contains("refs");
var isBranch = currentBranch.Contains("refs/heads");
var localCanonicalName = !isRef
? "refs/heads/" + currentBranch
: isBranch
? currentBranch
: currentBranch.Replace("refs/", "refs/heads/");
var repoTip = repo.Head.Tip;
// We currently have the rep.Head of the *default* branch, now we need to look up the right one
var originCanonicalName = $"{remote.Name}/{currentBranch}";
var originBranch = repo.Branches[originCanonicalName];
if (originBranch != null)
{
repoTip = originBranch.Tip;
}
var repoTipId = repoTip.Id;
if (repo.Branches.All(b => !b.CanonicalName.IsEquivalentTo(localCanonicalName)))
{
log.Info(isBranch ? $"Creating local branch {localCanonicalName}"
: $"Creating local branch {localCanonicalName} pointing at {repoTipId}");
repo.Refs.Add(localCanonicalName, repoTipId);
}
else
{
log.Info(isBranch ? $"Updating local branch {localCanonicalName} to point at {repoTip.Sha}"
: $"Updating local branch {localCanonicalName} to match ref {currentBranch}");
var localRef = repo.Refs[localCanonicalName];
repo.Refs.UpdateTarget(localRef, repoTipId);
}
repo.Commands.Checkout(localCanonicalName);
}
public static void AddMissingRefSpecs(this IRepository repo, ILog log, Remote remote)
{
if (remote.FetchRefSpecs.Any(r => r.Source == "refs/heads/*"))
return;
var allBranchesFetchRefSpec = $"+refs/heads/*:refs/remotes/{remote.Name}/*";
log.Info($"Adding refspec: {allBranchesFetchRefSpec}");
repo.Network.Remotes.Update(remote.Name,
r => r.FetchRefSpecs.Add(allBranchesFetchRefSpec));
}
public static void CreateFakeBranchPointingAtThePullRequestTip(this IGitRepository repo, ILog log, AuthenticationInfo authentication)
{
var remote = repo.Network.Remotes.Single();
log.Info("Fetching remote refs to see if there is a pull request ref");
var remoteTips = (string.IsNullOrEmpty(authentication.Username) ?
repo.GetRemoteTipsForAnonymousUser(remote) :
repo.GetRemoteTipsUsingUsernamePasswordCredentials(remote, authentication.Username, authentication.Password))
.ToList();
log.Info($"Remote Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, remoteTips.Select(r => r.CanonicalName)));
var headTipSha = repo.Head.Tip.Sha;
var refs = remoteTips.Where(r => r.TargetIdentifier == headTipSha).ToList();
if (refs.Count == 0)
{
var message = $"Couldn't find any remote tips from remote '{remote.Url}' pointing at the commit '{headTipSha}'.";
throw new WarningException(message);
}
if (refs.Count > 1)
{
var names = string.Join(", ", refs.Select(r => r.CanonicalName));
var message = $"Found more than one remote tip from remote '{remote.Url}' pointing at the commit '{headTipSha}'. Unable to determine which one to use ({names}).";
throw new WarningException(message);
}
var reference = refs[0];
var canonicalName = reference.CanonicalName;
log.Info($"Found remote tip '{canonicalName}' pointing at the commit '{headTipSha}'.");
if (canonicalName.StartsWith("refs/tags"))
{
log.Info($"Checking out tag '{canonicalName}'");
repo.Commands.Checkout(reference.Target.Sha);
return;
}
if (!canonicalName.StartsWith("refs/pull/") && !canonicalName.StartsWith("refs/pull-requests/"))
{
var message = $"Remote tip '{canonicalName}' from remote '{remote.Url}' doesn't look like a valid pull request.";
throw new WarningException(message);
}
var fakeBranchName = canonicalName.Replace("refs/pull/", "refs/heads/pull/").Replace("refs/pull-requests/", "refs/heads/pull-requests/");
log.Info($"Creating fake local branch '{fakeBranchName}'.");
repo.Refs.Add(fakeBranchName, new ObjectId(headTipSha));
log.Info($"Checking local branch '{fakeBranchName}' out.");
repo.Commands.Checkout(fakeBranchName);
}
public static void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(this IRepository repo, ILog log, string remoteName)
{
var prefix = $"refs/remotes/{remoteName}/";
var remoteHeadCanonicalName = $"{prefix}HEAD";
var remoteTrackingReferences = repo.Refs
.FromGlob(prefix + "*")
.Where(r => !r.CanonicalName.IsEquivalentTo(remoteHeadCanonicalName));
foreach (var remoteTrackingReference in remoteTrackingReferences)
{
var remoteTrackingReferenceName = remoteTrackingReference.CanonicalName;
var branchName = remoteTrackingReferenceName.Substring(prefix.Length);
var localCanonicalName = "refs/heads/" + branchName;
// We do not want to touch our current branch
if (branchName.IsEquivalentTo(repo.Head.FriendlyName)) continue;
if (repo.Refs.Any(x => x.CanonicalName.IsEquivalentTo(localCanonicalName)))
{
var localRef = repo.Refs[localCanonicalName];
var remotedirectReference = remoteTrackingReference.ResolveToDirectReference();
if (localRef.ResolveToDirectReference().TargetIdentifier == remotedirectReference.TargetIdentifier)
{
log.Info($"Skipping update of '{remoteTrackingReference.CanonicalName}' as it already matches the remote ref.");
continue;
}
var remoteRefTipId = remotedirectReference.Target.Id;
log.Info($"Updating local ref '{localRef.CanonicalName}' to point at {remoteRefTipId}.");
repo.Refs.UpdateTarget(localRef, remoteRefTipId);
continue;
}
log.Info($"Creating local branch from remote tracking '{remoteTrackingReference.CanonicalName}'.");
repo.Refs.Add(localCanonicalName, new ObjectId(remoteTrackingReference.ResolveToDirectReference().TargetIdentifier), true);
var branch = repo.Branches[branchName];
repo.Branches.Update(branch, b => b.TrackedBranch = remoteTrackingReferenceName);
}
}
public static Remote EnsureOnlyOneRemoteIsDefined(this IRepository repo, ILog log)
{
var remotes = repo.Network.Remotes;
var howMany = remotes.Count();
if (howMany == 1)
{
var remote = remotes.Single();
log.Info($"One remote found ({remote.Name} -> '{remote.Url}').");
return remote;
}
var message = $"{howMany} remote(s) have been detected. When being run on a build server, the Git repository is expected to bear one (and no more than one) remote.";
throw new WarningException(message);
}
private static IEnumerable<DirectReference> GetRemoteTipsUsingUsernamePasswordCredentials(this IRepository repository, Remote remote, string username, string password)
{
return repository.Network.ListReferences(remote, (url, fromUrl, types) => new UsernamePasswordCredentials
{
Username = username,
Password = password ?? string.Empty
}).Select(r => r.ResolveToDirectReference());
}
private static IEnumerable<DirectReference> GetRemoteTipsForAnonymousUser(this IRepository repository, Remote remote)
{
return repository.Network.ListReferences(remote).Select(r => r.ResolveToDirectReference());
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using DotSpatial.Symbology;
using NetTopologySuite.Geometries;
using Point = System.Drawing.Point;
namespace DotSpatial.Modeling.Forms
{
/// <summary>
/// Defines the base class for all model components.
/// </summary>
public class ModelElement : ICloneable
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ModelElement"/> class.
/// </summary>
/// <param name="modelElements">A list of all the elements in the model.</param>
public ModelElement(List<ModelElement> modelElements)
{
Location = new Point(0, 0);
Height = 100;
Width = 170;
Color = Color.Wheat;
Shape = ModelShape.Triangle;
Font = SystemFonts.MessageBoxFont;
Name = string.Empty;
Highlight = 1;
ModelElements = modelElements;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the base color of the shapes gradient.
/// </summary>
public Color Color { get; set; }
/// <summary>
/// Gets or sets the font used to draw the text on the element.
/// </summary>
public Font Font { get; set; }
/// <summary>
/// Gets or sets the shape of the element.
/// </summary>
public int Height { get; set; }
/// <summary>
/// Gets or sets the highlight. Returns 1 if the object is not highlighted less than 1 if it is highlighted.
/// </summary>
public double Highlight { get; set; }
/// <summary>
/// Gets or sets the location of the element in the parent form.
/// </summary>
public Point Location { get; set; }
/// <summary>
/// Gets or sets the text that is drawn on the element.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets a rectangle representing the element, top left corner being the location of the parent form of the element.
/// </summary>
public Rectangle Rectangle => new Rectangle(Location.X, Location.Y, Width, Height);
/// <summary>
/// Gets or sets the shape of the model component.
/// </summary>
public ModelShape Shape { get; set; }
/// <summary>
/// Gets or sets the width of the element.
/// </summary>
public int Width { get; set; }
/// <summary>
/// Gets or sets a list of all elements in the model.
/// </summary>
internal List<ModelElement> ModelElements { get; set; }
#endregion
#region Methods
/// <summary>
/// This returns a duplicate of this object.
/// </summary>
/// <returns>The copy.</returns>
public object Clone()
{
return Copy();
}
/// <summary>
/// Returns a shallow copy of the Parameter class.
/// </summary>
/// <returns>A new Parameters class that is a shallow copy of the original parameters class.</returns>
public ModelElement Copy()
{
return MemberwiseClone() as ModelElement;
}
/// <summary>
/// When a double click is caught by the parent class call this method.
/// </summary>
/// <returns>True.</returns>
public virtual bool DoubleClick()
{
return true;
}
/// <summary>
/// Returns true if the element intersects the rectangle from the parent class.
/// </summary>
/// <param name="rect">The rectangle to test must be in the virtual modeling coordinant plane.</param>
/// <returns>True, if the element intersects the rectangle from the parent class.</returns>
public virtual bool ElementInRectangle(Rectangle rect)
{
Geometry rectanglePoly;
if (rect.Height == 0 && rect.Width == 0)
{
rectanglePoly = new NetTopologySuite.Geometries.Point(rect.X, rect.Y);
}
else if (rect.Width == 0)
{
Coordinate[] rectanglePoints = new Coordinate[2];
rectanglePoints[0] = new Coordinate(rect.X, rect.Y);
rectanglePoints[1] = new Coordinate(rect.X, rect.Y + rect.Height);
rectanglePoly = new LineString(rectanglePoints);
}
else if (rect.Height == 0)
{
Coordinate[] rectanglePoints = new Coordinate[2];
rectanglePoints[0] = new Coordinate(rect.X, rect.Y);
rectanglePoints[1] = new Coordinate(rect.X + rect.Width, rect.Y);
rectanglePoly = new LineString(rectanglePoints);
}
else
{
Coordinate[] rectanglePoints = new Coordinate[5];
rectanglePoints[0] = new Coordinate(rect.X, rect.Y);
rectanglePoints[1] = new Coordinate(rect.X, rect.Y + rect.Height);
rectanglePoints[2] = new Coordinate(rect.X + rect.Width, rect.Y + rect.Height);
rectanglePoints[3] = new Coordinate(rect.X + rect.Width, rect.Y);
rectanglePoints[4] = new Coordinate(rect.X, rect.Y);
rectanglePoly = new Polygon(new LinearRing(rectanglePoints));
}
switch (Shape)
{
case ModelShape.Rectangle:
return rect.IntersectsWith(Rectangle);
case ModelShape.Ellipse:
int b = Height / 2;
int a = Width / 2;
Coordinate[] ellipsePoints = new Coordinate[(4 * a) + 1];
for (int x = -a; x <= a; x++)
{
if (x == 0)
{
ellipsePoints[x + a] = new Coordinate(Location.X + x + a, Location.Y);
ellipsePoints[(3 * a) - x] = new Coordinate(Location.X + x + a, Location.Y + Height);
}
else
{
ellipsePoints[x + a] = new Coordinate(Location.X + x + a, Location.Y + b - Math.Sqrt(Math.Abs(((b * b * x * x) / (a * a)) - (b * b))));
ellipsePoints[(3 * a) - x] = new Coordinate(Location.X + x + a, Location.Y + b + Math.Sqrt(Math.Abs(((b * b * x * x) / (a * a)) - (b * b))));
}
}
Polygon ellipsePoly = new Polygon(new LinearRing(ellipsePoints));
return ellipsePoly.Intersects(rectanglePoly);
case ModelShape.Triangle:
Coordinate[] trianglePoints = new Coordinate[4];
trianglePoints[0] = new Coordinate(Location.X, Location.Y);
trianglePoints[1] = new Coordinate(Location.X, Location.Y + Height);
trianglePoints[2] = new Coordinate(Location.X + Width - 5, Location.Y + ((Height - 5) / 2));
trianglePoints[3] = new Coordinate(Location.X, Location.Y);
Polygon trianglePoly = new Polygon(new LinearRing(trianglePoints));
return trianglePoly.Intersects(rectanglePoly);
default:
return false;
}
}
/// <summary>
/// Returns a list of all model elements that are direct children of this element.
/// </summary>
/// <returns>A list of all model element that are direct children of this element.</returns>
public List<ModelElement> GetChildren()
{
return GetChildren(this);
}
/// <summary>
/// Returns a list of all model elements that are direct parents of this element.
/// </summary>
/// <returns>A list of all model elements that are direct parents of this element.</returns>
public List<ModelElement> GetParents()
{
return GetParents(this);
}
/// <summary>
/// Darkens the component slightly.
/// </summary>
/// <param name="highlighted">Darkens if true returns to normal if false.</param>
public virtual void Highlighted(bool highlighted)
{
Highlight = highlighted ? 0.85 : 1.0;
}
/// <summary>
/// Returns true if this model element is downstram of the potentialUpstream element.
/// </summary>
/// <param name="potentialUpstream">Element to check against.</param>
/// <returns>True if this model element is downstram of the potentialUpstream element.</returns>
public bool IsDownstreamOf(ModelElement potentialUpstream)
{
return IsDownstreamOf(potentialUpstream, this);
}
/// <summary>
/// Returns true if this model element is downstream of the potentialUpstream element.
/// </summary>
/// <param name="potentialDownstream">Element to check against.</param>
/// <returns>True if this model element is downstream of the potentialUpstream element.</returns>
public bool IsUpstreamOf(ModelElement potentialDownstream)
{
return IsUpstreamOf(potentialDownstream, this);
}
/// <summary>
/// Repaints the form with cool background and stuff.
/// </summary>
/// <param name="graph">The graphics object to paint to, the element will be drawn to 0, 0.</param>
public virtual void Paint(Graphics graph)
{
// Sets up the colors to use
Pen outlinePen = new Pen(SymbologyGlobal.ColorFromHsl(Color.GetHue(), Color.GetSaturation(), Color.GetBrightness() * 0.6 * Highlight), 1.75F);
Color gradientTop = SymbologyGlobal.ColorFromHsl(Color.GetHue(), Color.GetSaturation(), Color.GetBrightness() * 0.7 * Highlight);
Color gradientBottom = SymbologyGlobal.ColorFromHsl(Color.GetHue(), Color.GetSaturation(), Color.GetBrightness() * 1.0 * Highlight);
// The path used for drop shadows
GraphicsPath shadowPath = new GraphicsPath();
ColorBlend colorBlend = new ColorBlend(3)
{
Colors = new[] { Color.Transparent, Color.FromArgb(180, Color.DarkGray), Color.FromArgb(180, Color.DimGray) },
Positions = new[] { 0f, 0.125f, 1f }
};
// Draws Rectangular Shapes
if (Shape == ModelShape.Rectangle)
{
// Draws the shadow
shadowPath.AddPath(GetRoundedRect(new Rectangle(5, 5, Width, Height), 10), true);
PathGradientBrush shadowBrush = new PathGradientBrush(shadowPath)
{
WrapMode = WrapMode.Clamp,
InterpolationColors = colorBlend
};
graph.FillPath(shadowBrush, shadowPath);
// Draws the basic shape
Rectangle fillRectange = new Rectangle(0, 0, Width - 5, Height - 5);
GraphicsPath fillArea = GetRoundedRect(fillRectange, 5);
LinearGradientBrush myBrush = new LinearGradientBrush(fillRectange, gradientBottom, gradientTop, LinearGradientMode.Vertical);
graph.FillPath(myBrush, fillArea);
graph.DrawPath(outlinePen, fillArea);
// Draws the status light
DrawStatusLight(graph);
// Draws the text
SizeF textSize = graph.MeasureString(Name, Font, Width);
RectangleF textRect;
if ((textSize.Width < Width) || (textSize.Height < Height))
textRect = new RectangleF((Width - textSize.Width) / 2, (Height - textSize.Height) / 2, textSize.Width, textSize.Height);
else
textRect = new RectangleF(0, (Height - textSize.Height) / 2, Width, textSize.Height);
graph.DrawString(Name, Font, new SolidBrush(Color.FromArgb(50, Color.Black)), textRect);
textRect.X = textRect.X - 1;
textRect.Y = textRect.Y - 1;
graph.DrawString(Name, Font, Brushes.Black, textRect);
// Garbage collection
fillArea.Dispose();
myBrush.Dispose();
}
// Draws Ellipse Shapes
if (Shape == ModelShape.Ellipse)
{
// Draws the shadow
shadowPath.AddEllipse(0, 5, Width + 5, Height);
PathGradientBrush shadowBrush = new PathGradientBrush(shadowPath)
{
WrapMode = WrapMode.Clamp,
InterpolationColors = colorBlend
};
graph.FillPath(shadowBrush, shadowPath);
// Draws the Ellipse
Rectangle fillArea = new Rectangle(0, 0, Width, Height);
LinearGradientBrush myBrush = new LinearGradientBrush(fillArea, gradientBottom, gradientTop, LinearGradientMode.Vertical);
graph.FillEllipse(myBrush, 1, 1, Width - 5, Height - 5);
graph.DrawEllipse(outlinePen, 1, 1, Width - 5, Height - 5);
// Draws the text
SizeF textSize = graph.MeasureString(Name, Font, Width);
RectangleF textRect;
if ((textSize.Width < Width) || (textSize.Height < Height))
textRect = new RectangleF((Width - textSize.Width) / 2, (Height - textSize.Height) / 2, textSize.Width, textSize.Height);
else
textRect = new RectangleF(0, (Height - textSize.Height) / 2, Width, textSize.Height);
graph.DrawString(Name, Font, new SolidBrush(Color.FromArgb(50, Color.Black)), textRect);
textRect.X = textRect.X - 1;
textRect.Y = textRect.Y - 1;
graph.DrawString(Name, Font, Brushes.Black, textRect);
// Garbage collection
myBrush.Dispose();
}
// Draws Triangular Shapes
if (Shape == ModelShape.Triangle)
{
// Draws the shadow
Point[] ptShadow = new Point[4];
ptShadow[0] = new Point(5, 5);
ptShadow[1] = new Point(Width + 5, ((Height - 5) / 2) + 5);
ptShadow[2] = new Point(5, Height + 2);
ptShadow[3] = new Point(5, 5);
shadowPath.AddLines(ptShadow);
PathGradientBrush shadowBrush = new PathGradientBrush(shadowPath)
{
WrapMode = WrapMode.Clamp,
InterpolationColors = colorBlend
};
graph.FillPath(shadowBrush, shadowPath);
// Draws the shape
Point[] pt = new Point[4];
pt[0] = new Point(0, 0);
pt[1] = new Point(Width - 5, (Height - 5) / 2);
pt[2] = new Point(0, Height - 5);
pt[3] = new Point(0, 0);
GraphicsPath myPath = new GraphicsPath();
myPath.AddLines(pt);
Rectangle fillArea = new Rectangle(1, 1, Width - 5, Height - 5);
LinearGradientBrush myBrush = new LinearGradientBrush(fillArea, gradientBottom, gradientTop, LinearGradientMode.Vertical);
graph.FillPath(myBrush, myPath);
graph.DrawPath(outlinePen, myPath);
// Draws the text
SizeF textSize = graph.MeasureString(Name, Font, Width);
RectangleF textRect;
if ((textSize.Width < Width) || (textSize.Height < Height))
textRect = new RectangleF((Width - textSize.Width) / 2, (Height - textSize.Height) / 2, textSize.Width, textSize.Height);
else
textRect = new RectangleF(0, (Height - textSize.Height) / 2, Width, textSize.Height);
graph.DrawString(Name, Font, Brushes.Black, textRect);
// Garbage collection
myBrush.Dispose();
}
// Garbage collection
shadowPath.Dispose();
outlinePen.Dispose();
}
/// <summary>
/// Calculates if a point is within the shape that defines the element.
/// </summary>
/// <param name="point">A point to test in the virtual modeling plane.</param>
/// <returns>True, if the point is within the shape that defines the element.</returns>
public virtual bool PointInElement(Point point)
{
Point pt = new Point(point.X - Location.X, point.Y - Location.Y);
switch (Shape)
{
case ModelShape.Rectangle:
if (pt.X > 0 && pt.X < Width && pt.Y > 0 && pt.Y < Height)
return true;
break;
case ModelShape.Ellipse:
double a = Width / 2.0;
double b = Height / 2.0;
double x = pt.X - a;
double y = pt.Y - b;
if (((x * x) / (a * a)) + ((y * y) / (b * b)) <= 1)
return true;
break;
case ModelShape.Triangle:
if ((pt.X >= 0) && (pt.X < Width))
{
double y1 = (((Height / 2.0) / Width) * pt.X) + 0;
double y2 = (-((Height / 2.0) / Width) * pt.X) + Height;
if ((pt.Y < y2) && (pt.Y > y1))
return true;
}
break;
default:
return false;
}
return false;
}
/// <summary>
/// This does nothing in the base class but child classes may override it.
/// </summary>
/// <param name="graph">The graphics object used for drawing.</param>
protected virtual void DrawStatusLight(Graphics graph)
{
}
/// <summary>
/// Returns true if the point is in the extents rectangle of the element.
/// </summary>
/// <param name="pt">A point to test, assuming 0, 0 is the top left corner of the shapes drawing rectangle.</param>
/// <returns>True if the point is in the extents rectangle of the element.</returns>
protected virtual bool PointInExtents(Point pt)
{
return pt.X > 0 && pt.X < Width && pt.Y > 0 && pt.Y < Height;
}
/// <summary>
/// Returns true if a point is in a rectangle.
/// </summary>
/// <param name="pt">Point to check.</param>
/// <param name="rect">Rectangle to check.</param>
/// <returns>True if a point is in a rectangle.</returns>
protected virtual bool PointInRectangle(Point pt, Rectangle rect)
{
return (pt.X >= rect.X && pt.X <= (rect.X + rect.Width)) && (pt.Y >= rect.Y && pt.Y <= (rect.Y + rect.Height));
}
/// <summary>
/// Creates a rounded corner rectangle from a regular rectangle.
/// </summary>
/// <param name="baseRect">Rectangle used for creation.</param>
/// <param name="radius">Radius for rounding the corners.</param>
/// <returns>The round cornered rectangle.</returns>
private static GraphicsPath GetRoundedRect(RectangleF baseRect, float radius)
{
if ((radius <= 0.0F) || radius >= (Math.Min(baseRect.Width, baseRect.Height) / 2.0))
{
GraphicsPath mPath = new GraphicsPath();
mPath.AddRectangle(baseRect);
mPath.CloseFigure();
return mPath;
}
float diameter = radius * 2.0F;
SizeF sizeF = new SizeF(diameter, diameter);
RectangleF arc = new RectangleF(baseRect.Location, sizeF);
GraphicsPath path = new GraphicsPath();
// top left arc
path.AddArc(arc, 180, 90);
// top right arc
arc.X = baseRect.Right - diameter;
path.AddArc(arc, 270, 90);
// bottom right arc
arc.Y = baseRect.Bottom - diameter;
path.AddArc(arc, 0, 90);
// bottom left arc
arc.X = baseRect.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
return path;
}
private List<ModelElement> GetChildren(ModelElement parent)
{
List<ModelElement> listChildren = new List<ModelElement>();
foreach (ModelElement mEl in ModelElements)
{
ArrowElement mAr = mEl as ArrowElement;
if (mAr?.StartElement != null && mAr.StartElement == parent)
listChildren.Add(mAr.StopElement);
}
return listChildren;
}
private List<ModelElement> GetParents(ModelElement child)
{
List<ModelElement> listParents = new List<ModelElement>();
foreach (ModelElement mEl in ModelElements)
{
ArrowElement mAr = mEl as ArrowElement;
if (mAr?.StopElement != null && mAr.StopElement == child)
listParents.Add(mAr.StartElement);
}
return listParents;
}
private bool IsDownstreamOf(ModelElement potentialUpstream, ModelElement child)
{
foreach (ModelElement mEl in ModelElements)
{
ArrowElement mAr = mEl as ArrowElement;
if (mAr != null)
{
if (mAr.StopElement == null) continue;
if (mAr.StopElement == child)
{
if (mAr.StartElement == null) continue;
if (mAr.StartElement == potentialUpstream) return true;
foreach (ModelElement parents in GetParents(mAr.StartElement))
{
if (IsDownstreamOf(potentialUpstream, parents)) return true;
}
return false;
}
}
}
return false;
}
private bool IsUpstreamOf(ModelElement potentialDownstream, ModelElement parent)
{
foreach (ModelElement mEl in ModelElements)
{
ArrowElement mAr = mEl as ArrowElement;
if (mAr?.StartElement != null)
{
if (mAr.StartElement == parent)
{
if (mAr.StopElement == null) continue;
if (mAr.StopElement == potentialDownstream) return true;
foreach (ModelElement children in GetChildren(mAr.StartElement))
{
if (IsUpstreamOf(potentialDownstream, children)) return true;
}
return false;
}
}
}
return false;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
namespace SharpFileSystem.IO
{
// CircularBuffer from http://circularbuffer.codeplex.com/.
public class CircularBuffer<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable
{
private int capacity;
private int size;
private int head;
private int tail;
private T[] buffer;
[NonSerialized]
private object syncRoot;
public CircularBuffer(int capacity)
: this(capacity, false)
{
}
public CircularBuffer(int capacity, bool allowOverflow)
{
if (capacity < 0)
throw new ArgumentException("capacity must be greater than or equal to zero.",
"capacity");
this.capacity = capacity;
size = 0;
head = 0;
tail = 0;
buffer = new T[capacity];
AllowOverflow = allowOverflow;
}
public bool AllowOverflow
{
get;
set;
}
public int Capacity
{
get { return capacity; }
set
{
if (value == capacity)
return;
if (value < size)
throw new ArgumentOutOfRangeException("value",
"value must be greater than or equal to the buffer size.");
var dst = new T[value];
if (size > 0)
CopyTo(dst);
buffer = dst;
capacity = value;
}
}
public int Size
{
get { return size; }
}
public bool Contains(T item)
{
int bufferIndex = head;
var comparer = EqualityComparer<T>.Default;
for (int i = 0; i < size; i++, bufferIndex++)
{
if (bufferIndex == capacity)
bufferIndex = 0;
if (item == null && buffer[bufferIndex] == null)
return true;
else if ((buffer[bufferIndex] != null) &&
comparer.Equals(buffer[bufferIndex], item))
return true;
}
return false;
}
public void Clear()
{
size = 0;
head = 0;
tail = 0;
}
public int Put(T[] src)
{
return Put(src, 0, src.Length);
}
public int Put(T[] src, int offset, int count)
{
int realCount = AllowOverflow ? count : Math.Min(count, capacity - size);
int srcIndex = offset;
for (int i = 0; i < realCount; i++, tail++, srcIndex++)
{
if (tail == capacity)
tail = 0;
buffer[tail] = src[srcIndex];
}
size = Math.Min(size + realCount, capacity);
return realCount;
}
public void Put(T item)
{
if (!AllowOverflow && size == capacity)
throw new InternalBufferOverflowException("Buffer is full.");
buffer[tail] = item;
if (tail++ == capacity)
tail = 0;
size++;
}
public void Skip(int count)
{
head += count;
if (head >= capacity)
head -= capacity;
}
public T[] Get(int count)
{
var dst = new T[count];
Get(dst);
return dst;
}
public int Get(T[] dst)
{
return Get(dst, 0, dst.Length);
}
public int Get(T[] dst, int offset, int count)
{
int realCount = Math.Min(count, size);
int dstIndex = offset;
for (int i = 0; i < realCount; i++, head++, dstIndex++)
{
if (head == capacity)
head = 0;
dst[dstIndex] = buffer[head];
}
size -= realCount;
return realCount;
}
public T Get()
{
if (size == 0)
throw new InvalidOperationException("Buffer is empty.");
var item = buffer[head];
if (head++ == capacity)
head = 0;
size--;
return item;
}
public void CopyTo(T[] array)
{
CopyTo(array, 0);
}
public void CopyTo(T[] array, int arrayIndex)
{
CopyTo(0, array, arrayIndex, size);
}
public void CopyTo(int index, T[] array, int arrayIndex, int count)
{
if (count > size)
throw new ArgumentOutOfRangeException("count",
"count cannot be greater than the buffer size.");
int bufferIndex = head;
for (int i = 0; i < count; i++, bufferIndex++, arrayIndex++)
{
if (bufferIndex == capacity)
bufferIndex = 0;
array[arrayIndex] = buffer[bufferIndex];
}
}
public IEnumerator<T> GetEnumerator()
{
int bufferIndex = head;
for (int i = 0; i < size; i++, bufferIndex++)
{
if (bufferIndex == capacity)
bufferIndex = 0;
yield return buffer[bufferIndex];
}
}
public T[] GetBuffer()
{
return buffer;
}
public T[] ToArray()
{
var dst = new T[size];
CopyTo(dst);
return dst;
}
#region ICollection<T> Members
int ICollection<T>.Count
{
get { return Size; }
}
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
void ICollection<T>.Add(T item)
{
Put(item);
}
bool ICollection<T>.Remove(T item)
{
if (size == 0)
return false;
Get();
return true;
}
#endregion
#region IEnumerable<T> Members
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region ICollection Members
int ICollection.Count
{
get { return Size; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (syncRoot == null)
Interlocked.CompareExchange(ref syncRoot, new object(), null);
return syncRoot;
}
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
CopyTo((T[])array, arrayIndex);
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
#endregion
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// 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.
//
///////////////////////////////////////////////////////////////////////////////////////////////
namespace CallButler.Manager.ViewControls
{
partial class PBXView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PBXView));
this.wizard1 = new global::Controls.Wizard.Wizard();
this.pgSummry = new global::Controls.Wizard.WizardPage();
this.dgPhones = new System.Windows.Forms.DataGridView();
this.colPhoneImage = new System.Windows.Forms.DataGridViewImageColumn();
this.colExtensionNumber = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colAddress = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colStatus = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.colConfigure = new System.Windows.Forms.DataGridViewLinkColumn();
this.header6 = new global::Controls.Wizard.Header();
this.pgSettings = new global::Controls.Wizard.WizardPage();
this.label1 = new System.Windows.Forms.Label();
this.numRegister = new System.Windows.Forms.NumericUpDown();
this.smoothLabel15 = new global::Controls.SmoothLabel();
this.header1 = new global::Controls.Wizard.Header();
this.wizardPage1 = new global::Controls.Wizard.WizardPage();
this.txtDialPrefix = new System.Windows.Forms.TextBox();
this.smoothLabel1 = new global::Controls.SmoothLabel();
this.header2 = new global::Controls.Wizard.Header();
this.pgSecurity = new global::Controls.Wizard.WizardPage();
this.txtRegDomain = new System.Windows.Forms.TextBox();
this.smoothLabel2 = new global::Controls.SmoothLabel();
this.header3 = new global::Controls.Wizard.Header();
this.panel1 = new System.Windows.Forms.Panel();
this.btnCancel = new System.Windows.Forms.Button();
this.btnApply = new System.Windows.Forms.Button();
this.btnRefresh = new global::Controls.LinkButton();
this.wizard1.SuspendLayout();
this.pgSummry.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgPhones)).BeginInit();
this.pgSettings.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numRegister)).BeginInit();
this.wizardPage1.SuspendLayout();
this.pgSecurity.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// wizard1
//
this.wizard1.AlwaysShowFinishButton = false;
this.wizard1.CloseOnCancel = true;
this.wizard1.CloseOnFinish = true;
this.wizard1.Controls.Add(this.pgSummry);
this.wizard1.Controls.Add(this.pgSettings);
this.wizard1.Controls.Add(this.wizardPage1);
this.wizard1.Controls.Add(this.pgSecurity);
this.wizard1.DisplayButtons = false;
this.wizard1.Dock = System.Windows.Forms.DockStyle.Fill;
this.wizard1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.wizard1.Location = new System.Drawing.Point(0, 22);
this.wizard1.Name = "wizard1";
this.wizard1.PageIndex = 0;
this.wizard1.Pages.AddRange(new global::Controls.Wizard.WizardPage[] {
this.pgSummry,
this.pgSettings,
this.wizardPage1,
this.pgSecurity});
this.wizard1.ShowTabs = true;
this.wizard1.Size = new System.Drawing.Size(627, 265);
this.wizard1.TabBackColor = System.Drawing.Color.WhiteSmoke;
this.wizard1.TabBackgroundImageLayout = System.Windows.Forms.ImageLayout.Tile;
this.wizard1.TabDividerLineType = global::Controls.Wizard.WizardTabDividerLineType.SingleLine;
this.wizard1.TabIndex = 2;
this.wizard1.TablPanelTopMargin = 0;
this.wizard1.TabPanelWidth = 120;
this.wizard1.TabWidth = 120;
//
// pgSummry
//
this.pgSummry.Controls.Add(this.dgPhones);
this.pgSummry.Controls.Add(this.btnRefresh);
this.pgSummry.Controls.Add(this.header6);
this.pgSummry.Dock = System.Windows.Forms.DockStyle.Fill;
this.pgSummry.Icon = global::CallButler.Manager.Properties.Resources.about_16;
this.pgSummry.IsFinishPage = false;
this.pgSummry.Location = new System.Drawing.Point(120, 0);
this.pgSummry.Name = "pgSummry";
this.pgSummry.Padding = new System.Windows.Forms.Padding(10, 0, 0, 0);
this.pgSummry.Size = new System.Drawing.Size(507, 217);
this.pgSummry.TabIndex = 2;
this.pgSummry.TabLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.pgSummry.Text = "Status";
//
// dgPhones
//
this.dgPhones.AllowUserToAddRows = false;
this.dgPhones.AllowUserToDeleteRows = false;
this.dgPhones.AllowUserToResizeRows = false;
this.dgPhones.BackgroundColor = System.Drawing.Color.WhiteSmoke;
this.dgPhones.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.dgPhones.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.dgPhones.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle1.BackColor = System.Drawing.Color.WhiteSmoke;
dataGridViewCellStyle1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dgPhones.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
this.dgPhones.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgPhones.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.colPhoneImage,
this.colExtensionNumber,
this.colName,
this.colAddress,
this.colStatus,
this.colConfigure});
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle2.BackColor = System.Drawing.Color.WhiteSmoke;
dataGridViewCellStyle2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
dataGridViewCellStyle2.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(225)))), ((int)(((byte)(244)))));
dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dgPhones.DefaultCellStyle = dataGridViewCellStyle2;
this.dgPhones.Dock = System.Windows.Forms.DockStyle.Fill;
this.dgPhones.Location = new System.Drawing.Point(10, 47);
this.dgPhones.MultiSelect = false;
this.dgPhones.Name = "dgPhones";
this.dgPhones.ReadOnly = true;
this.dgPhones.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None;
this.dgPhones.RowHeadersVisible = false;
this.dgPhones.RowTemplate.DefaultCellStyle.BackColor = System.Drawing.Color.WhiteSmoke;
this.dgPhones.RowTemplate.DefaultCellStyle.SelectionBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(225)))), ((int)(((byte)(244)))));
this.dgPhones.RowTemplate.Height = 32;
this.dgPhones.RowTemplate.ReadOnly = true;
this.dgPhones.RowTemplate.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.dgPhones.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dgPhones.ShowEditingIcon = false;
this.dgPhones.Size = new System.Drawing.Size(497, 148);
this.dgPhones.TabIndex = 5;
this.dgPhones.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgPhones_CellDoubleClick);
this.dgPhones.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgPhones_CellContentClick);
//
// colPhoneImage
//
this.colPhoneImage.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
this.colPhoneImage.HeaderText = "";
this.colPhoneImage.Image = global::CallButler.Manager.Properties.Resources.telephone_24;
this.colPhoneImage.Name = "colPhoneImage";
this.colPhoneImage.ReadOnly = true;
this.colPhoneImage.Width = 5;
//
// colExtensionNumber
//
this.colExtensionNumber.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
this.colExtensionNumber.HeaderText = "Extension";
this.colExtensionNumber.Name = "colExtensionNumber";
this.colExtensionNumber.ReadOnly = true;
this.colExtensionNumber.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.colExtensionNumber.Width = 79;
//
// colName
//
this.colName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.colName.HeaderText = "Name";
this.colName.Name = "colName";
this.colName.ReadOnly = true;
//
// colAddress
//
this.colAddress.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
this.colAddress.HeaderText = "Address";
this.colAddress.Name = "colAddress";
this.colAddress.ReadOnly = true;
this.colAddress.Width = 71;
//
// colStatus
//
this.colStatus.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
this.colStatus.HeaderText = "Status";
this.colStatus.Name = "colStatus";
this.colStatus.ReadOnly = true;
this.colStatus.Width = 63;
//
// colConfigure
//
this.colConfigure.ActiveLinkColor = System.Drawing.Color.RoyalBlue;
this.colConfigure.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
this.colConfigure.HeaderText = "";
this.colConfigure.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.colConfigure.LinkColor = System.Drawing.Color.RoyalBlue;
this.colConfigure.Name = "colConfigure";
this.colConfigure.ReadOnly = true;
this.colConfigure.Text = "";
this.colConfigure.ToolTipText = "Configure the selected phone";
this.colConfigure.TrackVisitedState = false;
this.colConfigure.VisitedLinkColor = System.Drawing.Color.RoyalBlue;
this.colConfigure.Width = 5;
//
// header6
//
this.header6.CausesValidation = false;
this.header6.Description = "View the status of IP phones connected to the PBX.";
this.header6.Dock = System.Windows.Forms.DockStyle.Top;
this.header6.Image = global::CallButler.Manager.Properties.Resources.about_32;
this.header6.Location = new System.Drawing.Point(10, 0);
this.header6.Name = "header6";
this.header6.Size = new System.Drawing.Size(497, 47);
this.header6.TabIndex = 4;
this.header6.Title = "Extension IP Phone Status";
//
// pgSettings
//
this.pgSettings.Controls.Add(this.label1);
this.pgSettings.Controls.Add(this.numRegister);
this.pgSettings.Controls.Add(this.smoothLabel15);
this.pgSettings.Controls.Add(this.header1);
this.pgSettings.Dock = System.Windows.Forms.DockStyle.Fill;
this.pgSettings.Icon = global::CallButler.Manager.Properties.Resources.nut_and_bolt_16;
this.pgSettings.IsFinishPage = false;
this.pgSettings.Location = new System.Drawing.Point(120, 0);
this.pgSettings.Name = "pgSettings";
this.pgSettings.Padding = new System.Windows.Forms.Padding(10, 0, 0, 0);
this.pgSettings.Size = new System.Drawing.Size(507, 217);
this.pgSettings.TabIndex = 3;
this.pgSettings.TabLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.pgSettings.Text = "General Settings";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(256, 70);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(50, 13);
this.label1.TabIndex = 38;
this.label1.Text = "seconds.";
//
// numRegister
//
this.numRegister.Location = new System.Drawing.Point(197, 68);
this.numRegister.Maximum = new decimal(new int[] {
65535,
0,
0,
0});
this.numRegister.Name = "numRegister";
this.numRegister.Size = new System.Drawing.Size(57, 21);
this.numRegister.TabIndex = 37;
this.numRegister.ValueChanged += new System.EventHandler(this.SettingChanged);
//
// smoothLabel15
//
this.smoothLabel15.AntiAliasText = false;
this.smoothLabel15.AutoSize = true;
this.smoothLabel15.BackColor = System.Drawing.Color.Transparent;
this.smoothLabel15.Cursor = System.Windows.Forms.Cursors.Hand;
this.smoothLabel15.EnableHelp = true;
this.smoothLabel15.HelpText = "This setting determines how long CallButler will wait to hear from an IP phone be" +
"fore it determines that it is offline.";
this.smoothLabel15.HelpTitle = "IP Phone Registration";
this.smoothLabel15.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.smoothLabel15.Location = new System.Drawing.Point(18, 70);
this.smoothLabel15.Name = "smoothLabel15";
this.smoothLabel15.Size = new System.Drawing.Size(192, 13);
this.smoothLabel15.TabIndex = 36;
this.smoothLabel15.Text = "Require IP phones to register every";
//
// header1
//
this.header1.CausesValidation = false;
this.header1.Description = "General PBX settings.";
this.header1.Dock = System.Windows.Forms.DockStyle.Top;
this.header1.Image = global::CallButler.Manager.Properties.Resources.nut_and_bolt_48_shadow;
this.header1.Location = new System.Drawing.Point(10, 0);
this.header1.Name = "header1";
this.header1.Size = new System.Drawing.Size(497, 47);
this.header1.TabIndex = 5;
this.header1.Title = "General PBX Settings";
//
// wizardPage1
//
this.wizardPage1.Controls.Add(this.txtDialPrefix);
this.wizardPage1.Controls.Add(this.smoothLabel1);
this.wizardPage1.Controls.Add(this.header2);
this.wizardPage1.Dock = System.Windows.Forms.DockStyle.Fill;
this.wizardPage1.Icon = global::CallButler.Manager.Properties.Resources.telephone_16;
this.wizardPage1.IsFinishPage = false;
this.wizardPage1.Location = new System.Drawing.Point(120, 0);
this.wizardPage1.Name = "wizardPage1";
this.wizardPage1.Padding = new System.Windows.Forms.Padding(10, 0, 0, 0);
this.wizardPage1.Size = new System.Drawing.Size(507, 217);
this.wizardPage1.TabIndex = 4;
this.wizardPage1.TabLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.wizardPage1.Text = "Dial Settings";
//
// txtDialPrefix
//
this.txtDialPrefix.Location = new System.Drawing.Point(239, 66);
this.txtDialPrefix.Name = "txtDialPrefix";
this.txtDialPrefix.Size = new System.Drawing.Size(57, 21);
this.txtDialPrefix.TabIndex = 38;
this.txtDialPrefix.TextChanged += new System.EventHandler(this.SettingChanged);
this.txtDialPrefix.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtDialPrefix_KeyPress);
//
// smoothLabel1
//
this.smoothLabel1.AntiAliasText = false;
this.smoothLabel1.AutoSize = true;
this.smoothLabel1.BackColor = System.Drawing.Color.Transparent;
this.smoothLabel1.Cursor = System.Windows.Forms.Cursors.Hand;
this.smoothLabel1.EnableHelp = true;
this.smoothLabel1.HelpText = resources.GetString("smoothLabel1.HelpText");
this.smoothLabel1.HelpTitle = "Outbound Call Prefix";
this.smoothLabel1.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.smoothLabel1.Location = new System.Drawing.Point(21, 69);
this.smoothLabel1.Name = "smoothLabel1";
this.smoothLabel1.Size = new System.Drawing.Size(231, 13);
this.smoothLabel1.TabIndex = 37;
this.smoothLabel1.Text = "All outbound numbers must be prefixed with";
//
// header2
//
this.header2.CausesValidation = false;
this.header2.Description = "Settings for phone dialing.";
this.header2.Dock = System.Windows.Forms.DockStyle.Top;
this.header2.Image = global::CallButler.Manager.Properties.Resources.telephone_48_shadow;
this.header2.Location = new System.Drawing.Point(10, 0);
this.header2.Name = "header2";
this.header2.Size = new System.Drawing.Size(497, 47);
this.header2.TabIndex = 6;
this.header2.Title = "Dial Settings";
//
// pgSecurity
//
this.pgSecurity.Controls.Add(this.txtRegDomain);
this.pgSecurity.Controls.Add(this.smoothLabel2);
this.pgSecurity.Controls.Add(this.header3);
this.pgSecurity.Dock = System.Windows.Forms.DockStyle.Fill;
this.pgSecurity.Enabled = false;
this.pgSecurity.Icon = global::CallButler.Manager.Properties.Resources.lock_16;
this.pgSecurity.IsFinishPage = false;
this.pgSecurity.Location = new System.Drawing.Point(120, 0);
this.pgSecurity.Name = "pgSecurity";
this.pgSecurity.Padding = new System.Windows.Forms.Padding(10, 0, 0, 0);
this.pgSecurity.Size = new System.Drawing.Size(507, 217);
this.pgSecurity.TabIndex = 5;
this.pgSecurity.TabLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.pgSecurity.Text = "Security Settings";
//
// txtRegDomain
//
this.txtRegDomain.Location = new System.Drawing.Point(21, 82);
this.txtRegDomain.Name = "txtRegDomain";
this.txtRegDomain.Size = new System.Drawing.Size(295, 21);
this.txtRegDomain.TabIndex = 39;
this.txtRegDomain.TextChanged += new System.EventHandler(this.SettingChanged);
//
// smoothLabel2
//
this.smoothLabel2.AntiAliasText = false;
this.smoothLabel2.AutoSize = true;
this.smoothLabel2.BackColor = System.Drawing.Color.Transparent;
this.smoothLabel2.Cursor = System.Windows.Forms.Cursors.Hand;
this.smoothLabel2.EnableHelp = true;
this.smoothLabel2.HelpText = "This setting requires that IP telephones registering with this PBX use the value " +
"specified here when they authenticate their registration.";
this.smoothLabel2.HelpTitle = "SIP Registration Domain";
this.smoothLabel2.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.smoothLabel2.Location = new System.Drawing.Point(18, 66);
this.smoothLabel2.Name = "smoothLabel2";
this.smoothLabel2.Size = new System.Drawing.Size(131, 13);
this.smoothLabel2.TabIndex = 38;
this.smoothLabel2.Text = "SIP registration domain";
//
// header3
//
this.header3.CausesValidation = false;
this.header3.Description = "PBX security settings.";
this.header3.Dock = System.Windows.Forms.DockStyle.Top;
this.header3.Image = global::CallButler.Manager.Properties.Resources.lock_32_shadow;
this.header3.Location = new System.Drawing.Point(10, 0);
this.header3.Name = "header3";
this.header3.Size = new System.Drawing.Size(497, 47);
this.header3.TabIndex = 7;
this.header3.Title = "Security Settings";
//
// panel1
//
this.panel1.Controls.Add(this.btnCancel);
this.panel1.Controls.Add(this.btnApply);
this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel1.Location = new System.Drawing.Point(0, 287);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(627, 26);
this.panel1.TabIndex = 4;
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnCancel.Location = new System.Drawing.Point(549, 3);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 1;
this.btnCancel.Text = "&Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnApply
//
this.btnApply.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnApply.Enabled = false;
this.btnApply.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.btnApply.Location = new System.Drawing.Point(468, 3);
this.btnApply.Name = "btnApply";
this.btnApply.Size = new System.Drawing.Size(75, 23);
this.btnApply.TabIndex = 0;
this.btnApply.Text = "&Apply";
this.btnApply.UseVisualStyleBackColor = true;
this.btnApply.Click += new System.EventHandler(this.btnApply_Click);
//
// btnRefresh
//
this.btnRefresh.AntiAliasText = false;
this.btnRefresh.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.btnRefresh.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnRefresh.Dock = System.Windows.Forms.DockStyle.Bottom;
this.btnRefresh.Font = new System.Drawing.Font("Tahoma", 8.25F);
this.btnRefresh.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnRefresh.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnRefresh.LinkImage = global::CallButler.Manager.Properties.Resources.refresh_16;
this.btnRefresh.Location = new System.Drawing.Point(10, 195);
this.btnRefresh.Name = "btnRefresh";
this.btnRefresh.Size = new System.Drawing.Size(497, 22);
this.btnRefresh.TabIndex = 6;
this.btnRefresh.Text = "Refresh";
this.btnRefresh.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnRefresh.UnderlineOnHover = true;
this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
//
// PBXView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.Controls.Add(this.wizard1);
this.Controls.Add(this.panel1);
this.HeaderCaption = "Configure CallButler for use in an office environment";
this.HeaderIcon = global::CallButler.Manager.Properties.Resources.node_48_shadow;
this.HeaderTitle = "PBX";
this.Name = "PBXView";
this.Controls.SetChildIndex(this.panel1, 0);
this.Controls.SetChildIndex(this.wizard1, 0);
this.wizard1.ResumeLayout(false);
this.pgSummry.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dgPhones)).EndInit();
this.pgSettings.ResumeLayout(false);
this.pgSettings.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numRegister)).EndInit();
this.wizardPage1.ResumeLayout(false);
this.wizardPage1.PerformLayout();
this.pgSecurity.ResumeLayout(false);
this.pgSecurity.PerformLayout();
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private global::Controls.Wizard.Wizard wizard1;
private global::Controls.Wizard.WizardPage pgSummry;
private global::Controls.Wizard.WizardPage pgSettings;
private global::Controls.Wizard.Header header6;
private global::Controls.Wizard.Header header1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown numRegister;
private global::Controls.SmoothLabel smoothLabel15;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnApply;
private global::Controls.Wizard.WizardPage wizardPage1;
private global::Controls.Wizard.Header header2;
private global::Controls.SmoothLabel smoothLabel1;
private System.Windows.Forms.TextBox txtDialPrefix;
private global::Controls.Wizard.WizardPage pgSecurity;
private global::Controls.Wizard.Header header3;
private global::Controls.SmoothLabel smoothLabel2;
private System.Windows.Forms.TextBox txtRegDomain;
private System.Windows.Forms.DataGridView dgPhones;
private System.Windows.Forms.DataGridViewImageColumn colPhoneImage;
private System.Windows.Forms.DataGridViewTextBoxColumn colExtensionNumber;
private System.Windows.Forms.DataGridViewTextBoxColumn colName;
private System.Windows.Forms.DataGridViewTextBoxColumn colAddress;
private System.Windows.Forms.DataGridViewTextBoxColumn colStatus;
private System.Windows.Forms.DataGridViewLinkColumn colConfigure;
private global::Controls.LinkButton btnRefresh;
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Globalization;
using FlatRedBall;
using FlatRedBall.Content;
using FlatRedBall.Content.Particle;
using FlatRedBall.Graphics;
using FlatRedBall.Graphics.Particle;
using FlatRedBall.Gui;
using FlatRedBall.Instructions;
using FlatRedBall.IO;
using FlatRedBall.ManagedSpriteGroups;
using FlatRedBall.Content.Scene;
namespace ParticleEditor.GUI
{
/// <summary>
/// Summary description for FileMenuWindow.
/// </summary>
public static class FileMenuWindow
{
static SpriteList blueprintSprites = new SpriteList();
#region Methods
#region load
public static void LoadEmittersClick(FlatRedBall.Gui.Window callingWindow)
{
FileWindow tempWindow = GuiManager.AddFileWindow();
tempWindow.Filter = "XML Emitter (*.emix)|*.emix";
tempWindow.CurrentFileType = "emix";
tempWindow.OkClick += new GuiMessage(LoadEmitterOK);
}
public static void LoadEmitterOK(FlatRedBall.Gui.Window callingWindow)
{
string fileName = ((FileWindow)callingWindow).Results[0];
AppCommands.Self.File.LoadEmitters(fileName);
}
public static void LoadScnxButtonClick(FlatRedBall.Gui.Window callingWindow)
{
FileWindow tempWindow = GuiManager.AddFileWindow();
tempWindow.SetFileType("scnx");
tempWindow.OkClick += new GuiMessage(LoadScnxFileWindowOK);
}
public static void LoadScnxFileWindowOK(FlatRedBall.Gui.Window callingWindow)
{
EditorData.LoadScene(((FileWindow)callingWindow).Results[0]);
}
public static void AttemptEmitterAttachment(string scnFileName)
{
if (EditorData.lastLoadedFile != null)
{
for (int i = EditorData.lastLoadedFile.emitters.Count - 1; i > -1; i--)
{
if (EditorData.lastLoadedFile.emitters[i].ParentSpriteName != null)
{
Sprite tempParentSprite = EditorData.Scene.Sprites.FindWithNameContaining(
EditorData.lastLoadedFile.emitters[i].ParentSpriteName);
if(tempParentSprite != null)
{
EditorData.Emitters.FindWithNameContaining(EditorData.lastLoadedFile.emitters[i].Name).AttachTo(tempParentSprite, false);
EditorData.lastLoadedFile.emitters.RemoveAt(i);
}
}
else
EditorData.lastLoadedFile.emitters.RemoveAt(i);
}
if (EditorData.lastLoadedFile.emitters.Count == 0)
EditorData.lastLoadedFile = null;
List<string> particlesAttached = new List<string>();
List<string> spritesAttachedTo = new List<string>();
foreach (Emitter e in EditorData.Emitters)
{
if(e.Parent != null)
{
particlesAttached.Add(e.Name);
spritesAttachedTo.Add(e.Parent.Name);
}
}
string message;
if(particlesAttached.Count == 0)
message = "No particles were attached to the loaded scene.\n";
else
{
message = "The following particles were attached to parent Sprites: \n\n";
for(int i = 0; i < particlesAttached.Count; i++)
{
message += particlesAttached[i] + " attached to " + spritesAttachedTo[i] + "\n";
}
}
if (EditorData.lastLoadedFile == null)
{
message += "\nAll attachments made successfully!";
}
else
{
message += "\nThe following Emitters could not find the appropriate parent Sprites: \n\n";
foreach (EmitterSave es in EditorData.lastLoadedFile.emitters)
{
message += es.Name + " could not find " + es.ParentSpriteName + "\n";
}
}
if(scnFileName != "")
GuiManager.ShowMessageBox(message, FlatRedBall.IO.FileManager.MakeRelative(scnFileName) + " loaded");
else
GuiManager.ShowMessageBox(message, "");
}
}
#region emi with attachments loaded, but no Sprites in scene messages
public static void ForgetAttachmentInfo(Window callingWindow)
{
EditorData.lastLoadedFile = null;
callingWindow.Parent.CloseWindow();
}
public static void RememberAttachmentInfo(Window callingWindow)
{
callingWindow.Parent.CloseWindow();
}
public static void AbsRelToZero(Window callingWindow)
{
foreach (Emitter e in EditorData.Emitters)
{
e.X = e.RelativeX = 0;
e.Y = e.RelativeY = 0;
e.Z = e.RelativeZ = 0;
}
callingWindow.Parent.CloseWindow();
}
public static void AbsToZeroKeepRel(Window callingWindow)
{
foreach (Emitter e in EditorData.Emitters)
{
e.X = 0;
e.Y = 0;
e.Z = 0;
}
callingWindow.Parent.CloseWindow();
}
public static void KeepAbsRel(Window callingWindow)
{
callingWindow.Parent.CloseWindow();
}
public static void ManuallyLoadScn(Window callingWindow)
{
LoadScnxButtonClick(callingWindow);
callingWindow.Parent.CloseWindow();
}
public static void AutoSearchScn(Window callingWindow)
{
callingWindow.Parent.CloseWindow();
List<string> allFiles = FileManager.GetAllFilesInDirectory(System.IO.Directory.GetCurrentDirectory());
for(int i = allFiles.Count - 1; i > -1; i--)
{
if(FlatRedBall.IO.FileManager.GetExtension(allFiles[i]) != "scnx")
allFiles.RemoveAt(i);
}
//throw new NotImplementedException("Feature not implemented. Complain on FlatRedBall forums");
foreach(string scnFile in allFiles)
{
SpriteEditorScene ses = SpriteEditorScene.FromFile(scnFile);
foreach(SpriteSave ss in ses.SpriteList)
{
for (int i = EditorData.lastLoadedFile.emitters.Count - 1; i > -1; i--)
{
if (EditorData.lastLoadedFile.emitters[i].ParentSpriteName != null)
{
if (ss.Name == EditorData.lastLoadedFile.emitters[i].ParentSpriteName)
{
EditorData.LoadScene(scnFile);
return;
}
}
}
}
}
}
#endregion
#endregion
public static void NewWorkspace(FlatRedBall.Gui.Window callingWindow)
{
// TODO: Support unloading Scene;
EditorData.CreateNewWorkspace();
}
#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.
namespace System.IO
{
partial class FileSystemInfo : IFileSystemObject
{
/// <summary>The last cached stat information about the file.</summary>
private Interop.Sys.FileStatus _fileStatus;
/// <summary>true if <see cref="_fileStatus"/> represents a symlink and the target of that symlink is a directory.</summary>
private bool _targetOfSymlinkIsDirectory;
/// <summary>
/// Whether we've successfully cached a stat structure.
/// -1 if we need to refresh _fileStatus, 0 if we've successfully cached one,
/// or any other value that serves as an errno error code from the
/// last time we tried and failed to refresh _fileStatus.
/// </summary>
private int _fileStatusInitialized = -1;
internal IFileSystemObject FileSystemObject
{
get { return this; }
}
internal void Invalidate()
{
_fileStatusInitialized = -1;
}
FileAttributes IFileSystemObject.Attributes
{
get
{
EnsureStatInitialized();
FileAttributes attrs = default(FileAttributes);
if (IsDirectoryAssumesInitialized) // this is the one attribute where we follow symlinks
{
attrs |= FileAttributes.Directory;
}
if (IsReadOnlyAssumesInitialized)
{
attrs |= FileAttributes.ReadOnly;
}
if (IsSymlinkAssumesInitialized)
{
attrs |= FileAttributes.ReparsePoint;
}
if (Path.GetFileName(FullPath).StartsWith("."))
{
attrs |= FileAttributes.Hidden;
}
return attrs != default(FileAttributes) ?
attrs :
FileAttributes.Normal;
}
set
{
// Validate that only flags from the attribute are being provided. This is an
// approximation for the validation done by the Win32 function.
const FileAttributes allValidFlags =
FileAttributes.Archive | FileAttributes.Compressed | FileAttributes.Device |
FileAttributes.Directory | FileAttributes.Encrypted | FileAttributes.Hidden |
FileAttributes.Hidden | FileAttributes.IntegrityStream | FileAttributes.Normal |
FileAttributes.NoScrubData | FileAttributes.NotContentIndexed | FileAttributes.Offline |
FileAttributes.ReadOnly | FileAttributes.ReparsePoint | FileAttributes.SparseFile |
FileAttributes.System | FileAttributes.Temporary;
if ((value & ~allValidFlags) != 0)
{
throw new ArgumentException(SR.Arg_InvalidFileAttrs, nameof(value));
}
// The only thing we can reasonably change is whether the file object is readonly,
// just changing its permissions accordingly.
EnsureStatInitialized();
IsReadOnlyAssumesInitialized = (value & FileAttributes.ReadOnly) != 0;
_fileStatusInitialized = -1;
}
}
/// <summary>Gets whether stat reported this system object as a directory.</summary>
private bool IsDirectoryAssumesInitialized =>
(_fileStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR ||
(IsSymlinkAssumesInitialized && _targetOfSymlinkIsDirectory);
/// <summary>Gets whether stat reported this system object as a symlink.</summary>
private bool IsSymlinkAssumesInitialized =>
(_fileStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFLNK;
/// <summary>
/// Gets or sets whether the file is read-only. This is based on the read/write/execute
/// permissions of the object.
/// </summary>
private bool IsReadOnlyAssumesInitialized
{
get
{
Interop.Sys.Permissions readBit, writeBit;
if (_fileStatus.Uid == Interop.Sys.GetEUid()) // does the user effectively own the file?
{
readBit = Interop.Sys.Permissions.S_IRUSR;
writeBit = Interop.Sys.Permissions.S_IWUSR;
}
else if (_fileStatus.Gid == Interop.Sys.GetEGid()) // does the user belong to a group that effectively owns the file?
{
readBit = Interop.Sys.Permissions.S_IRGRP;
writeBit = Interop.Sys.Permissions.S_IWGRP;
}
else // everyone else
{
readBit = Interop.Sys.Permissions.S_IROTH;
writeBit = Interop.Sys.Permissions.S_IWOTH;
}
return
(_fileStatus.Mode & (int)readBit) != 0 && // has read permission
(_fileStatus.Mode & (int)writeBit) == 0; // but not write permission
}
set
{
int newMode = _fileStatus.Mode;
if (value) // true if going from writable to readable, false if going from readable to writable
{
// Take away all write permissions from user/group/everyone
newMode &= ~(int)(Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IWOTH);
}
else if ((newMode & (int)Interop.Sys.Permissions.S_IRUSR) != 0)
{
// Give write permission to the owner if the owner has read permission
newMode |= (int)Interop.Sys.Permissions.S_IWUSR;
}
// Change the permissions on the file
if (newMode != _fileStatus.Mode)
{
bool isDirectory = this is DirectoryInfo;
Interop.CheckIo(Interop.Sys.ChMod(FullPath, newMode), FullPath, isDirectory);
}
}
}
bool IFileSystemObject.Exists
{
get
{
if (_fileStatusInitialized == -1)
{
Refresh();
}
return
_fileStatusInitialized == 0 && // avoid throwing if Refresh failed; instead just return false
(this is DirectoryInfo) == IsDirectoryAssumesInitialized;
}
}
DateTimeOffset IFileSystemObject.CreationTime
{
get
{
EnsureStatInitialized();
return (_fileStatus.Flags & Interop.Sys.FileStatusFlags.HasBirthTime) != 0 ?
DateTimeOffset.FromUnixTimeSeconds(_fileStatus.BirthTime).ToLocalTime() :
default(DateTimeOffset);
}
set
{
// The ctime in Unix can be interpreted differently by different formats so there isn't
// a reliable way to set this; however, we can't just do nothing since the FileSystemWatcher
// specifically looks for this call to make a Metatdata Change, so we should set the
// LastAccessTime of the file to cause the metadata change we need.
LastAccessTime = LastAccessTime;
}
}
DateTimeOffset IFileSystemObject.LastAccessTime
{
get
{
EnsureStatInitialized();
return DateTimeOffset.FromUnixTimeSeconds(_fileStatus.ATime).ToLocalTime();
}
set { SetAccessWriteTimes(value.ToUnixTimeSeconds(), null); }
}
DateTimeOffset IFileSystemObject.LastWriteTime
{
get
{
EnsureStatInitialized();
return DateTimeOffset.FromUnixTimeSeconds(_fileStatus.MTime).ToLocalTime();
}
set { SetAccessWriteTimes(null, value.ToUnixTimeSeconds()); }
}
private void SetAccessWriteTimes(long? accessTime, long? writeTime)
{
_fileStatusInitialized = -1; // force a refresh so that we have an up-to-date times for values not being overwritten
EnsureStatInitialized();
Interop.Sys.UTimBuf buf;
buf.AcTime = accessTime ?? _fileStatus.ATime;
buf.ModTime = writeTime ?? _fileStatus.MTime;
bool isDirectory = this is DirectoryInfo;
Interop.CheckIo(Interop.Sys.UTime(FullPath, ref buf), FullPath, isDirectory);
_fileStatusInitialized = -1;
}
long IFileSystemObject.Length
{
get
{
EnsureStatInitialized();
return _fileStatus.Size;
}
}
void IFileSystemObject.Refresh()
{
// This should not throw, instead we store the result so that we can throw it
// when someone actually accesses a property.
// Use lstat to get the details on the object, without following symlinks.
// If it is a symlink, then subsequently get details on the target of the symlink,
// storing those results separately. We only report failure if the initial
// lstat fails, as a broken symlink should still report info on exists, attributs, etc.
_targetOfSymlinkIsDirectory = false;
int result = Interop.Sys.LStat(FullPath, out _fileStatus);
if (result < 0)
{
Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
_fileStatusInitialized = errorInfo.RawErrno;
return;
}
Interop.Sys.FileStatus targetStatus;
if ((_fileStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFLNK &&
Interop.Sys.Stat(FullPath, out targetStatus) >= 0)
{
_targetOfSymlinkIsDirectory = (targetStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR;
}
_fileStatusInitialized = 0;
}
private void EnsureStatInitialized()
{
if (_fileStatusInitialized == -1)
{
Refresh();
}
if (_fileStatusInitialized != 0)
{
int errno = _fileStatusInitialized;
_fileStatusInitialized = -1;
var errorInfo = new Interop.ErrorInfo(errno);
// Windows distinguishes between whether the directory or the file isn't found,
// and throws a different exception in these cases. We attempt to approximate that
// here; there is a race condition here, where something could change between
// when the error occurs and our checks, but it's the best we can do, and the
// worst case in such a race condition (which could occur if the file system is
// being manipulated concurrently with these checks) is that we throw a
// FileNotFoundException instead of DirectoryNotFoundexception.
// directoryError is true only if a FileNotExists error was provided and the parent
// directory of the file represented by _fullPath is nonexistent
bool directoryError = (errorInfo.Error == Interop.Error.ENOENT && !Directory.Exists(Path.GetDirectoryName(PathHelpers.TrimEndingDirectorySeparator(FullPath)))); // The destFile's path is invalid
throw Interop.GetExceptionForIoErrno(errorInfo, FullPath, directoryError);
}
}
}
}
| |
// Copyright 2009-2012 Matvei Stefarov <me@matvei.org>
// Modified 2012-2013 LegendCraft Team
using System;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Text;
using System.Threading;
namespace fCraft.HeartbeatSaver
{
static class HeartbeatSaver
{
const int ProtocolVersion = 7;
static readonly Uri MinecraftNetUri = new Uri("https://minecraft.net/heartbeat.jsp");
static readonly TimeSpan Delay = TimeSpan.FromSeconds(10),
Timeout = TimeSpan.FromSeconds(10),
ErrorDelay = TimeSpan.FromSeconds(30),
RefreshDataDelay = TimeSpan.FromSeconds(60);
static readonly RequestCachePolicy CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.BypassCache);
const string UrlFileName = "externalurl.txt",
DefaultDataFileName = "heartbeatdata.txt",
UserAgent = "fCraft HeartbeatSaver";
static string heartbeatDataFileName;
static HeartbeatData data;
static int Main(string[] args)
{
if (args.Length == 0)
{
heartbeatDataFileName = DefaultDataFileName;
}
else if (args.Length == 1 && File.Exists(args[0]))
{
heartbeatDataFileName = args[0];
}
else
{
Console.WriteLine(@"Usage: fHeartbeat ""path/to/datafile""");
return (int)ReturnCode.UsageError;
}
if (!RefreshData())
{
return (int)ReturnCode.HeartbeatDataReadingError;
}
new Thread(BeatThreadMinecraftNet) { IsBackground = true }.Start();
while (true)
{
Thread.Sleep(RefreshDataDelay);
RefreshData();
}
}
// fetches fresh data from the given file. Should not throw any exceptions. Runs in the main thread.
static bool RefreshData()
{
try
{
string[] rawData = File.ReadAllLines(heartbeatDataFileName, Encoding.ASCII);
//take the data from heartbeatdata.txt that was created from Network/HeartBeat.cs, make sure the orders match up on each :3
HeartbeatData newData = new HeartbeatData
{
Salt = rawData[0],
ServerIP = IPAddress.Parse(rawData[1]),
Port = Int32.Parse(rawData[2]),
PlayerCount = Int32.Parse(rawData[3]),
MaxPlayers = Int32.Parse(rawData[4]),
ServerName = rawData[5],
IsPublic = Boolean.Parse(rawData[6])
};
data = newData;
return true;
}
catch (Exception ex)
{
if (ex is UnauthorizedAccessException || ex is IOException)
{
Console.Error.WriteLine("{0}: UnauthorizedAccessException - Error reading {1}: {2} {3}",
Timestamp(),
heartbeatDataFileName, ex.GetType().Name, ex.Message);
}
else if (ex is FormatException || ex is ArgumentException)
{
Console.Error.WriteLine("{0}: FormatException - Cannot parse one of the data fields of {1}: {2} {3}",
Timestamp(),
heartbeatDataFileName, ex.GetType().Name, ex.Message);
}
else
{
Console.Error.WriteLine("{0}: Unexpected error - {1} {2}",
Timestamp(),
ex.GetType().Name, ex.Message);
}
return false;
}
}
// Sends a heartbeat to Minecraft.net, and saves response. Runs in its own background thread.
static void BeatThreadMinecraftNet()
{
UriBuilder ub = new UriBuilder(MinecraftNetUri);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(" ***Welcome to LegendCraft HeartbeatSaver***\n");
Console.WriteLine(" ...:: The program is designed to send ::...\n .:: a Heartbeat to Minecraft/ClassiCube!::. \n");
Console.WriteLine(" .::.:.:.:.:.:.:.:.:.:.:.:.:.:.:.:.:.:.:.::.\n");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.White;
while (true)
{
try
{
HeartbeatData freshData = data;
ub.Query = String.Format("public={0}&max={1}&users={2}&port={3}&version={4}&salt={5}&name={6}",
freshData.IsPublic,
freshData.MaxPlayers,
freshData.PlayerCount,
freshData.Port,
ProtocolVersion,
Uri.EscapeDataString(freshData.Salt),
Uri.EscapeDataString(freshData.ServerName));
//start the heartbeat loop here
CreateRequest(ub.Uri);
}
catch (Exception ex)
{
if (ex is WebException)
{
Console.Error.WriteLine("{0}: Minecraft.net is probably down :( ({1})", Timestamp(), ex.Message);
}
else
{
Console.Error.WriteLine("{0}: {1}", Timestamp(), ex);
}
Thread.Sleep(ErrorDelay);
return;
}
Console.WriteLine("{0}: Sent!", Timestamp());
Console.WriteLine("");
Thread.Sleep(Delay);
}
}
public static int count = 1;
// Creates an HTTP GET request to the given Uri. Optionally saves the response, to UrlFileName.
// Throws all kinds of exceptions on failure
//sends the actual heartbeat
static void CreateRequest(Uri uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.ServicePoint.BindIPEndPointDelegate = BindIPEndPointCallback;
request.Method = "GET";
request.Timeout = (int)Timeout.TotalMilliseconds;
request.ReadWriteTimeout = (int)Timeout.TotalMilliseconds;
request.CachePolicy = CachePolicy;
request.UserAgent = UserAgent;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
{
string responseText = responseReader.ReadToEnd();
File.WriteAllText(UrlFileName, responseText.Trim(), Encoding.ASCII);
if (count == 69)
{
Console.WriteLine("{0}: Sending HeartBeat... Count 69...Lol, I said 69...hehe", Timestamp());
}
else if (count == 9001)
{
Console.WriteLine("{0}: Sending HeartBeat... Count 9001...ITS OVAR 9000!", Timestamp());
}
else
{
Console.WriteLine("{0}: Sending HeartBeat... Count {1}", Timestamp(), count);
}
count++;
}
}
}
//end heartbeat loop
// Timestamp, used for logging
static string Timestamp()
{
return DateTime.Now.ToString("hh:mm tt");
}
// delegate used to ensure that heartbeats get sent from the correct NIC/IP
static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
return new IPEndPoint(data.ServerIP, 0);
}
// container class for all the heartbeat data
sealed class HeartbeatData
{
public string Salt { get; set; }
public IPAddress ServerIP { get; set; }
public int Port { get; set; }
public int PlayerCount { get; set; }
public int MaxPlayers { get; set; }
public string ServerName { get; set; }
public bool IsPublic { get; set; }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using JetBrains.Annotations;
namespace Jasily.Extensions.System.Collections.Generic
{
/// <summary>
/// extensions for <see cref="List{T}"/> or <see cref="IList{T}"/>.
/// </summary>
public static class ListExtensions
{
/// <summary>
/// create a <see cref="ReadOnlyCollection{T}"/> list as a readonly wrapper.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
[PublicAPI]
public static IReadOnlyList<T> AsReadOnly<T>([NotNull] this IList<T> list) => new ReadOnlyCollection<T>(list);
/// <summary>
/// return a simple synchronized list (use lock).
/// if you looking for lockfree solution, try namespace `System.Collections.Concurrent`.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
[PublicAPI]
public static IList<T> AsSynchronized<T>([NotNull] IList<T> list) => new SynchronizedList<T>(list);
/// <summary>
/// copy from http://referencesource.microsoft.com/.
/// </summary>
/// <typeparam name="T"></typeparam>
private class SynchronizedList<T> : IList<T>, ICollection
{
private readonly IList<T> _list;
internal SynchronizedList(IList<T> list)
{
this._list = list ?? throw new ArgumentNullException(nameof(list));
this.SyncRoot = (list as ICollection)?.SyncRoot ?? new object();
}
public void CopyTo(Array array, int index)
{
lock (this.SyncRoot)
{
this._list.CopyTo(array, index);
}
}
public int Count
{
get
{
lock (this.SyncRoot)
{
return this._list.Count;
}
}
}
public bool IsSynchronized => true;
public object SyncRoot { get; }
public bool IsReadOnly => this._list.IsReadOnly;
public void Add(T item)
{
lock (this.SyncRoot)
{
this._list.Add(item);
}
}
public void Clear()
{
lock (this.SyncRoot)
{
this._list.Clear();
}
}
public bool Contains(T item)
{
lock (this.SyncRoot)
{
return this._list.Contains(item);
}
}
public void CopyTo(T[] array, int arrayIndex)
{
lock (this.SyncRoot)
{
this._list.CopyTo(array, arrayIndex);
}
}
public bool Remove(T item)
{
lock (this.SyncRoot)
{
return this._list.Remove(item);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
lock (this.SyncRoot)
{
return this._list.GetEnumerator();
}
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
lock (this.SyncRoot)
{
return this._list.GetEnumerator();
}
}
public T this[int index]
{
get
{
lock (this.SyncRoot)
{
return this._list[index];
}
}
set
{
lock (this.SyncRoot)
{
this._list[index] = value;
}
}
}
public int IndexOf(T item)
{
lock (this.SyncRoot)
{
return this._list.IndexOf(item);
}
}
public void Insert(int index, T item)
{
lock (this.SyncRoot)
{
this._list.Insert(index, item);
}
}
public void RemoveAt(int index)
{
lock (this.SyncRoot)
{
this._list.RemoveAt(index);
}
}
}
/// <summary>
/// copy items from data source, make list equals to data source.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="dataSource"></param>
public static void MakeEqualsTo<T>([NotNull] this IList<T> list, [NotNull] IList<T> dataSource)
{
if (list == null) throw new ArgumentNullException(nameof(list));
if (dataSource == null) throw new ArgumentNullException(nameof(dataSource));
if (ReferenceEquals(list, dataSource)) throw new InvalidOperationException();
var comparer = EqualityComparer<T>.Default;
var listCount = list.Count;
var dataSourceCount = dataSource.Count;
var count = Math.Min(listCount, dataSourceCount);
for (var i = 0; i < count; i++)
{
var item = dataSource[i];
if (!comparer.Equals(item, list[i])) list[i] = item;
}
if (listCount > dataSourceCount)
{
do
{
list.RemoveAt(listCount - 1);
} while (--listCount > dataSourceCount);
}
else if (listCount < dataSourceCount)
{
do
{
list.Add(dataSource[count]);
} while (++count < dataSourceCount);
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Diagnostics.Contracts;
using Microsoft.Research.DataStructures;
namespace Microsoft.Research.CodeAnalysis
{
[ContractVerification(true)]
class QuantitativeOutput<Method, Assembly> : DerivableOutputFullResults<Method, Assembly>
{
#region Object invariant
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(this.warnings != null);
Contract.Invariant(this.warningLevel != null);
Contract.Invariant(this.swallowedCount != null);
Contract.Invariant(this.scoresManager != null);
Contract.Invariant(this.finalStatsMessage == null || this.finalStatsAssembly != null);
}
#endregion
// warninglevel is used to filter the warnings according their score, and the thresholds.
// We keep a function because the warning level can be changed dynamically
private readonly Func<WarningLevelOptions> warningLevel;
private readonly WarningScoresManager scoresManager;
private readonly SortedDictionary<double, List<Bucket>> warnings;
private readonly bool sortWarnings;
private readonly int maxWarnings;
private readonly bool showScores;
private readonly bool showJustification;
/// <summary>
/// We count how many warnings we emitted and how many were signaled
/// </summary>
private int emitCount;
private int outcomeCount;
private SwallowedBuckets swallowedCount;
/// <summary>
/// Used here so we can emit the final stats after all the errors
/// </summary>
private string finalStatsAssembly;
private string finalStatsMessage;
#region Constructor
public QuantitativeOutput(
bool SortWarnings, bool ShowScores, bool showJustification,
Func<WarningLevelOptions> WarningLevel, WarningScoresManager scoresManager,
int MaxWarnings, IOutputFullResults<Method, Assembly> output)
: base(output)
{
Contract.Requires(scoresManager != null);
Contract.Requires(output != null);
this.sortWarnings = SortWarnings;
this.showJustification = showJustification;
this.showScores = ShowScores;
this.warningLevel = WarningLevel;
this.maxWarnings = MaxWarnings;
this.scoresManager = scoresManager;
this.warnings = new SortedDictionary<double, List<Bucket>>(new InverseNaturalOrder());
this.emitCount = 0;
this.outcomeCount = 0;
this.swallowedCount = new SwallowedBuckets();
}
#endregion
#region IOutputFullResults<Method> Members
public override int SwallowedMessagesCount(ProofOutcome outcome)
{
return this.swallowedCount.GetCounter(outcome);
}
#endregion
#region IOutputResults Members
public override bool EmitOutcome(Witness witness, string format, params object[] args)
{
return EmitOutcomeInternal(Bucket.Kind.EmitOutcome, witness, format, args);
}
public override bool EmitOutcomeAndRelated(Witness witness, string format, params object[] args)
{
return EmitOutcomeInternal(Bucket.Kind.EmitOutcomeAndRelated, witness, format, args);
}
private bool EmitOutcomeInternal(Bucket.Kind kind, Witness witness, string format, params object[] args)
{
Contract.Requires(witness != null);
Contract.Requires(format != null);
// First we check if the score of the witness is too low.
// If it is, then we ignore this warning message at all
if (!this.HasGoodScore(witness.GetScore(this.scoresManager)))
{
this.swallowedCount.UpdateCounter(witness.Outcome);
return false;
}
this.outcomeCount++;
// Prefix the Justification
if (this.showJustification)
{
format = String.Format("(justification: {0}) {1}", witness.GetJustificationString(this.scoresManager), format);
}
// Prefix the Score
if (this.showScores)
{
format = String.Format("(score: {0}) {1}", witness.GetScore(this.scoresManager).ToString(), format);
}
if (this.sortWarnings)
{
var bucket = new Bucket(kind, witness, format, args);
Insert(witness.GetScore(this.scoresManager), bucket);
}
else
{
if (this.emitCount <= this.maxWarnings)
{
this.emitCount++;
return kind == Bucket.Kind.EmitOutcome ?
base.EmitOutcome(witness, format, args) :
base.EmitOutcomeAndRelated(witness, format, args);
}
}
return true;
}
private void Insert(double Score, Bucket bucket)
{
if (this.warnings.ContainsKey(Score))
{
Contract.Assume(this.warnings[Score] != null);
this.warnings[Score].Add(bucket);
}
else
{
this.warnings[Score] = new List<Bucket>() { bucket };
}
}
public override void FinalStatistic(string assemblyName, string msg)
{
// hold for emission after errors
this.finalStatsAssembly = assemblyName;
this.finalStatsMessage = msg;
}
public override void Close()
{
this.Flush();
base.Close();
}
private void Flush()
{
if (this.sortWarnings)
{
var emitted = 0;
var toSkip = new List<string>();
foreach (var pair in this.warnings)
{
Contract.Assume(pair.Value != null);
foreach (var bucket in pair.Value)
{
// At most MaxWarnings
if (emitted >= this.maxWarnings)
{
goto end;
}
var warningIncrease = 1;
var format = bucket.Format;
// Group together the bottoms at the same PC
if (bucket.Witness.Outcome == ProofOutcome.Bottom)
{
var pc = bucket.Witness.PC.PrimaryMethodLocation().PrimarySourceContext();
if (pc != null)
{
if (!toSkip.Contains(pc))
{
toSkip.Add(pc);
warningIncrease = pair.Value.Where(b => b.Witness.Outcome == ProofOutcome.Bottom && pc.Equals(b.Witness.PC.PrimaryMethodLocation().PrimarySourceContext())).Count();
if (warningIncrease > 1)
{
format = string.Format("{0} ({1} more unreached assertion(s) at the same location)", format, warningIncrease);
}
}
else
{// We already emitted a warning for this source location, so we give up
continue;
}
}
}
emitted += warningIncrease;
switch (bucket.CallKind)
{
case Bucket.Kind.EmitOutcome:
base.EmitOutcome(bucket.Witness, format, bucket.Args);
break;
case Bucket.Kind.EmitOutcomeAndRelated:
base.EmitOutcomeAndRelated(bucket.Witness, format, bucket.Args);
break;
default:
#if DEBUG
Contract.Assert(false);
#endif
// do nothing ... Should be unreachable
break;
}
}
}
}
end: ;
EmitFinalStats();
}
private void EmitFinalStats()
{
if (finalStatsMessage != null)
{
base.FinalStatistic(this.finalStatsAssembly, this.finalStatsMessage);
if (this.outcomeCount > this.maxWarnings)
{
base.FinalStatistic(this.finalStatsAssembly, "(Additional warnings not shown. Increase -maxWarnings to show.)");
}
}
}
#endregion
#region Filtering Logic
[ContractVerification(true)]
[Pure]
private bool HasGoodScore(double score)
{
switch (this.warningLevel())
{
case WarningLevelOptions.full:
return true;
case WarningLevelOptions.mediumlow:
return score > this.scoresManager.MEDIUMLOWSCORE;
case WarningLevelOptions.medium:
return score > this.scoresManager.MEDIUMSCORE;
case WarningLevelOptions.low:
return score > this.scoresManager.LOWSCORE;
default:
// Should be unreachable
Contract.Assume(false);
return true;
}
}
#endregion
internal struct Bucket
{
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(witness != null);
Contract.Invariant(format != null);
}
public enum Kind { EmitOutcome, EmitOutcomeAndRelated }
readonly public Kind CallKind;
readonly private Witness witness;
readonly private string format;
readonly public object[] Args;
public Witness Witness
{
get
{
Contract.Ensures(Contract.Result<Witness>() != null);
return this.witness;
}
}
public string Format
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return this.format;
}
}
public Bucket(Kind callkind, Witness witness, string format, object[] args)
{
Contract.Requires(witness != null);
Contract.Requires(format != null);
this.CallKind = callkind;
this.witness = witness;
this.format = format;
this.Args = args;
}
}
internal class InverseNaturalOrder : IComparer<double>
{
#region IComparer<double> Members
public int Compare(double x, double y)
{
return x == y ? 0 : ((x < y) ? 1 : -1);
}
#endregion
}
}
}
| |
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;
public class PanelResizer : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IBeginDragHandler, IDragHandler, IEndDragHandler
{
#region Constants
const string XPosKey = ":x";
const string YPosKey = ":y";
const string WidthKey = ":w";
const string HeightKey = ":h";
const string LastUsedResKey = "LastUsedRes";
[System.Serializable]
public class RectResizer
{
[SerializeField] public RectTransform m_Rect;
[SerializeField] public bool m_HorizontalMovement;
[SerializeField] public bool m_VerticalMovement;
[SerializeField] public bool m_PositionDisplacement;
}
#endregion
#region Variables
[SerializeField] bool m_SavePosition = false;
[SerializeField] Texture2D m_MouseCursor = null;
[SerializeField] RectResizer[] m_Targets = null;
[SerializeField] Rect m_NormalizedDragBounds = new Rect(0, 0, 1, 1);
#endregion
#region Functions
void Start()
{
/*
foreach (RectResizer target in m_Targets)
{
target.m_NormalizedScreenBounds.x *= Screen.width;
target.m_NormalizedScreenBounds.y *= Screen.height;
target.m_NormalizedScreenBounds.width *= Screen.width;
target.m_NormalizedScreenBounds.height *= Screen.height;
}
*/
//m_NormalizedDragBounds.x *= Screen.width;
//m_NormalizedDragBounds.y *= Screen.height;
//m_NormalizedDragBounds.width *= Screen.width;
//m_NormalizedDragBounds.height *= Screen.height;
LoadPanelSettings();
}
void LoadPanelSettings()
{
if (StringifyResolution() != PlayerPrefs.GetString(LastUsedResKey))
{
// they are using a different resolution, so things won't look correct, so just use the defaults
return;
}
if (m_SavePosition)
{
foreach (RectResizer target in m_Targets)
{
Vector2 localPos = target.m_Rect.anchoredPosition;
Vector2 size = target.m_Rect.sizeDelta;
if (PlayerPrefs.HasKey(target.m_Rect.name + XPosKey))
{
localPos.x = PlayerPrefs.GetFloat(target.m_Rect.name + XPosKey);
}
if (PlayerPrefs.HasKey(target.m_Rect.name + YPosKey))
{
localPos.y = PlayerPrefs.GetFloat(target.m_Rect.name + YPosKey);
}
if (PlayerPrefs.HasKey(target.m_Rect.name + WidthKey))
{
size.x = PlayerPrefs.GetFloat(target.m_Rect.name + WidthKey);
}
if (PlayerPrefs.HasKey(target.m_Rect.name + HeightKey))
{
size.y = PlayerPrefs.GetFloat(target.m_Rect.name + HeightKey);
}
target.m_Rect.anchoredPosition = localPos;
target.m_Rect.sizeDelta = size;
}
}
}
void SavePanelSettings()
{
if (m_SavePosition)
{
foreach (RectResizer target in m_Targets)
{
PlayerPrefs.SetFloat(target.m_Rect.name + XPosKey, target.m_Rect.anchoredPosition.x);
PlayerPrefs.SetFloat(target.m_Rect.name + YPosKey, target.m_Rect.anchoredPosition.y);
PlayerPrefs.SetFloat(target.m_Rect.name + WidthKey, target.m_Rect.sizeDelta.x);
PlayerPrefs.SetFloat(target.m_Rect.name + HeightKey, target.m_Rect.sizeDelta.y);
PlayerPrefs.SetString(LastUsedResKey, StringifyResolution());
}
}
}
string StringifyResolution()
{
return string.Format("{0}x{1}", Screen.width, Screen.height);
}
void OnDestroy()
{
SavePanelSettings();
}
#endregion
#region IPointerEnterHandler implementation
void IPointerEnterHandler.OnPointerEnter (PointerEventData eventData)
{
if (m_MouseCursor != null)
{
Cursor.SetCursor(m_MouseCursor, new Vector2(m_MouseCursor.width / 2, m_MouseCursor.height / 2), CursorMode.Auto);
}
}
#endregion
#region IPointerExitHandler implementation
void IPointerExitHandler.OnPointerExit (PointerEventData eventData)
{
if (m_MouseCursor != null)
{
Cursor.SetCursor(null, Vector2.zero, CursorMode.Auto);
}
}
#endregion
#region IBeginDragHandler implementation
void IBeginDragHandler.OnBeginDrag (PointerEventData eventData)
{
//throw new System.NotImplementedException ();
}
#endregion
bool CanDragHorizontal(PointerEventData eventData)
{
/*return (eventData.delta.x < 0 && eventData.position.x > m_NormalizedDragBounds.xMin)
|| (eventData.delta.x > 0 && eventData.position.x < m_NormalizedDragBounds.xMax);*/
Rect bounds = m_NormalizedDragBounds;
bounds.x *= Screen.width;
bounds.y *= Screen.height;
bounds.width *= Screen.width;
bounds.height *= Screen.height;
return eventData.position.x >= bounds.xMin && eventData.position.x <= bounds.xMax;
}
bool CanDragVertical(PointerEventData eventData)
{
Rect bounds = m_NormalizedDragBounds;
bounds.x *= Screen.width;
bounds.y *= Screen.height;
bounds.width *= Screen.width;
bounds.height *= Screen.height;
return eventData.position.y >= bounds.yMin && eventData.position.y <= bounds.yMax;
}
#region IDragHandler implementation
void IDragHandler.OnDrag (PointerEventData eventData)
{
Vector3 posDelta = Vector3.zero;
Vector2 sizeDelta = Vector2.zero;
foreach (RectResizer target in m_Targets)
{
posDelta = target.m_Rect.anchoredPosition;
sizeDelta = target.m_Rect.sizeDelta;
if (target.m_PositionDisplacement)
{
if (target.m_HorizontalMovement && CanDragHorizontal(eventData))
{
posDelta.x += eventData.delta.x;
sizeDelta.x -= eventData.delta.x;
}
if (target.m_VerticalMovement && CanDragVertical(eventData))
{
posDelta.y += eventData.delta.y;
sizeDelta.y -= eventData.delta.y;
}
}
else
{
if (target.m_HorizontalMovement && CanDragHorizontal(eventData))
{
sizeDelta.x += eventData.delta.x;
}
if (target.m_VerticalMovement && CanDragVertical(eventData))
{
sizeDelta.y -= eventData.delta.y;
}
}
target.m_Rect.anchoredPosition = posDelta;
target.m_Rect.sizeDelta = sizeDelta;
}
}
#endregion
#region IEndDragHandler implementation
void IEndDragHandler.OnEndDrag (PointerEventData eventData)
{
//throw new System.NotImplementedException ();
}
#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.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyDate
{
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 Models;
/// <summary>
/// Date operations.
/// </summary>
public partial class Date : IServiceOperations<AutoRestDateTestService>, IDate
{
/// <summary>
/// Initializes a new instance of the Date class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Date(AutoRestDateTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestDateTestService
/// </summary>
public AutoRestDateTestService Client { get; private set; }
/// <summary>
/// Get null date value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetNull", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "date/null").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, new DateJsonConverter());
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get invalid date value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetInvalidDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetInvalidDate", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "date/invaliddate").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, new DateJsonConverter());
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get overflow date value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetOverflowDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetOverflowDate", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "date/overflowdate").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, new DateJsonConverter());
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get underflow date value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetUnderflowDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetUnderflowDate", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "date/underflowdate").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, new DateJsonConverter());
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put max date value 9999-12-31
/// </summary>
/// <param name='dateBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutMaxDateWithHttpMessagesAsync(DateTime? dateBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (dateBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "dateBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("dateBody", dateBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutMaxDate", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "date/max").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(dateBody, new DateJsonConverter());
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get max date value 9999-12-31
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetMaxDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetMaxDate", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "date/max").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, new DateJsonConverter());
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put min date value 0000-01-01
/// </summary>
/// <param name='dateBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutMinDateWithHttpMessagesAsync(DateTime? dateBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (dateBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "dateBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("dateBody", dateBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutMinDate", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "date/min").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(dateBody, new DateJsonConverter());
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get min date value 0000-01-01
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<DateTime?>> GetMinDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetMinDate", tracingParameters);
}
// Construct URL
var baseUrl = this.Client.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "date/min").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
if (httpRequest.Headers.Contains(header.Key))
{
httpRequest.Headers.Remove(header.Key);
}
httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<DateTime?>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<DateTime?>(responseContent, new DateJsonConverter());
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.XPath;
using dexih.functions.Exceptions;
using dexih.transforms;
namespace dexih.functions.external
{
public class Currency
{
private const string KeyAttribute =
"Register for an API key at: [currencylayer.com](https://currencylayer.com/product).";
public class CurrencyDetails
{
public DateTime TimeStamp { get; set; }
public DateTime Date { get; set; }
public string Source { get; set; }
public Dictionary<string, double> Rates = new Dictionary<string, double>();
public double USDRate(string to)
{
if (to == "USD")
{
return 1;
}
else
{
if (string.IsNullOrEmpty(to))
{
throw new FunctionException($"The \"TO\" currency code was empty or null.");
}
if (!Rates.TryGetValue(to, out var rate))
{
throw new FunctionException($"The exchange rate for {to} is not available.");
}
if (Math.Abs(rate) < 0.0000001)
{
throw new ArgumentOutOfRangeException($"The rate for {to} is equal to 0.");
}
return rate;
}
}
// get the from/to usd rates and divide these to get the from/to rate.
public double Rate(string from, string to)
{
var rate1 = USDRate(from);
var rate2 = USDRate(to);
return rate2 / rate1;
}
}
public class CurrencyRate
{
public string Currency { get; set; }
public double ToRate { get; set; }
public double FromRate { get; set; }
}
public class CountryCurrencyEntity
{
public string Country { get; set; }
public string CurrencyName { get; set; }
public string CurrencyCode { get; set; }
public int CurrencyNumber { get; set; }
}
public class CurrencyEntity
{
public string CurrencyName { get; set; }
public string CurrencyCode { get; set; }
public int CurrencyNumber { get; set; }
}
private CurrencyDetails _liveCurrency;
private Dictionary<string, CurrencyDetails> _currencyHistory;
private double _baseRate;
private Dictionary<string, double>.Enumerator _ratesEnumerator;
private bool _isFirst = true;
private async Task<(string url, string statusCode, bool isSuccess, Stream response)> GetWebServiceResponse(string url, CancellationToken cancellationToken)
{
var uri = new Uri(url);
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(uri.GetLeftPart(UriPartial.Authority));
client.DefaultRequestHeaders.Accept.Clear();
var response = await client.GetAsync(uri.PathAndQuery, cancellationToken);
return (uri.ToString(), response.StatusCode.ToString(), response.IsSuccessStatusCode, await response.Content.ReadAsStreamAsync());
}
}
private async Task LoadLiveRates(string key, CancellationToken cancellationToken)
{
_liveCurrency = await GetRates($"http://apilayer.net/api/live?access_key={key}", cancellationToken);
}
private async Task<CurrencyDetails> GetRates(string url, CancellationToken cancellationToken)
{
var response = await GetWebServiceResponse(url, cancellationToken);
if (!response.isSuccess)
{
throw new FunctionException(
$"The currency data not loaded due to failure to contact apilayer.net server. Status code: {response.statusCode}.");
}
var reader = new StreamReader(response.response);
var jsonString = await reader.ReadToEndAsync();
JsonDocument jsonDocument;
try
{
jsonDocument = JsonDocument.Parse(jsonString);
if (jsonDocument == null)
{
throw new FileHandlerException(
"The currency data not available, json parsing returned nothing.");
}
}
catch (Exception ex)
{
throw new FileHandlerException(
$"The currency data not available, error returned parsing json data: {ex.Message}", ex);
}
var success = jsonDocument.RootElement.GetProperty("success").GetBoolean();
if (!success)
{
if (jsonDocument.RootElement.TryGetProperty("error", out var error))
{
var errorMessage = error.GetProperty("info").GetString();
throw new FunctionException($"The currency data not loaded, error message: {errorMessage}.");
}
else
{
throw new FunctionException($"The currency data not loaded due to an unknown error.");
}
}
var rates = new CurrencyDetails();
rates.TimeStamp = jsonDocument.RootElement.GetProperty("timestamp").GetInt64().UnixTimeStampToDate();
rates.Source = jsonDocument.RootElement.GetProperty("source").GetString();
if (jsonDocument.RootElement.TryGetProperty("quotes", out var quotes))
{
foreach (var quote in quotes.EnumerateObject())
{
var sourceTo = quote.Name; // should contain string like USDAUD
var toCurrency = sourceTo.Substring(3, 3);
var rate = quote.Value.GetDouble();
rates.Rates.Add(toCurrency, rate);
}
}
return rates;
}
private async Task<CurrencyDetails> GetHistoricalRates(string key, DateTime dateTime, CancellationToken cancellationToken)
{
if (_isFirst)
{
_isFirst = false;
_currencyHistory = new Dictionary<string, CurrencyDetails>();
}
var date = dateTime.ToString("yyyy-MM-dd");
if (_currencyHistory.TryGetValue(date, out var currencyDetails))
{
return currencyDetails;
}
var url = $"http://apilayer.net/api/historical?access_key={key}&date={date}";
var rates = await GetRates(url, cancellationToken);
_currencyHistory.Add(date, rates);
return rates;
}
[TransformFunction(FunctionType = EFunctionType.Map, Category = "Currency", Name = "Live Exchange Rate",
Description = "Get the current exchange rate for the from/to currency.")]
public async Task<double> CurrencyRateLive(
[TransformFunctionParameter(Description = KeyAttribute)] string key,
string from,
string to,
CancellationToken cancellationToken)
{
if (from == to) return 1;
// load the rates on the first call
if (_isFirst)
{
_isFirst = false;
await LoadLiveRates(key, cancellationToken);
}
if (_liveCurrency == null)
{
throw new FunctionException($"The currency data not loaded.");
}
return _liveCurrency.Rate(from, to);
}
[TransformFunction(FunctionType = EFunctionType.Map, Category = "Currency", Name = "Live Rate Convert",
Description = "Converts the value based on the current exchange rate for the from/to currency.")]
public async Task<double> CurrencyConvertLive(
[TransformFunctionParameter(Description = KeyAttribute)] string key,
double value,
string from,
string to,
CancellationToken cancellationToken)
{
if (from == to) return value;
// load the rates on the first call
if (_isFirst)
{
_isFirst = false;
await LoadLiveRates(key, cancellationToken);
}
if (_liveCurrency == null)
{
throw new FunctionException($"The currency data not loaded.");
}
return _liveCurrency.Rate(from, to) * value;
}
[TransformFunction(FunctionType = EFunctionType.Rows, Category = "Currency", Name = "Live Exchange Rates",
Description = "Gets the live exchange rates for a specified currency (if from is null USD is used).")]
public async Task<CurrencyRate> CurrenciesLive(
[TransformFunctionParameter(Description = KeyAttribute)] string key,
string from,
CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(from)) from = "USD";
// load the rates on the first call
if (_isFirst)
{
_isFirst = false;
await LoadLiveRates(key, cancellationToken);
_baseRate = _liveCurrency.USDRate(from);
_ratesEnumerator = _liveCurrency.Rates.GetEnumerator();
}
if (_liveCurrency == null)
{
throw new FunctionException($"The currency data not loaded.");
}
if (_ratesEnumerator.MoveNext())
{
var currency = new CurrencyRate()
{
Currency = _ratesEnumerator.Current.Key,
ToRate = _ratesEnumerator.Current.Value / _baseRate,
FromRate = _baseRate / _ratesEnumerator.Current.Value
};
return currency;
}
else
{
_ratesEnumerator.Dispose();
return null;
}
}
[TransformFunction(FunctionType = EFunctionType.Map, Category = "Currency", Name = "Historical Exchange Rate",
Description = "Get the exchange rate at the specified date for the from/to currency.")]
public async Task<double> CurrencyRateHistorical(
[TransformFunctionParameter(Description = KeyAttribute)] string key,
DateTime date,
string from,
string to,
CancellationToken cancellationToken)
{
if (from == to) return 1;
var rates = await GetHistoricalRates(key, date, cancellationToken);
return rates.Rate(from, to);
}
[TransformFunction(FunctionType = EFunctionType.Map, Category = "Currency", Name = "Historical Rate Convert",
Description = "Converts the value based on the current exchange rate for the from/to currency.")]
public async Task<double> CurrencyConvertHistorical(
[TransformFunctionParameter(Description = KeyAttribute)] string key,
DateTime date,
double value,
string from,
string to,
CancellationToken cancellationToken)
{
if (from == to) return value;
var rates = await GetHistoricalRates(key, date, cancellationToken);
return rates.Rate(from, to) * value;
}
[TransformFunction(FunctionType = EFunctionType.Rows, Category = "Currency", Name = "Historical Exchange Rates",
Description = "Gets the live exchange rates for a specified currency (if from is null USD is used).")]
public async Task<CurrencyRate> CurrenciesHistorical(
[TransformFunctionParameter(Description = KeyAttribute)] string key,
DateTime date,
string from,
CancellationToken cancellationToken)
{
if (string.IsNullOrEmpty(from)) from = "USD";
// load the rates on the first call
if (_isFirst)
{
var rates = await GetHistoricalRates(key, date, cancellationToken);
_baseRate = rates.USDRate(from);
_ratesEnumerator = rates.Rates.GetEnumerator();
}
if (_ratesEnumerator.MoveNext())
{
var currency = new CurrencyRate()
{
Currency = _ratesEnumerator.Current.Key,
ToRate = _ratesEnumerator.Current.Value / _baseRate,
FromRate = _baseRate / _ratesEnumerator.Current.Value
};
return currency;
}
else
{
_ratesEnumerator.Dispose();
return null;
}
}
private XPathNodeIterator _cachedCurrencyCodes;
private HashSet<string> _usedCurrencyCodes;
private async Task<bool> LoadCurrencyCode(CancellationToken cancellationToken)
{
var uri = new Uri("https://www.currency-iso.org/dam/downloads/lists/list_one.xml");
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(uri.GetLeftPart(UriPartial.Authority));
client.DefaultRequestHeaders.Accept.Clear();
var response = await client.GetAsync(uri.PathAndQuery, cancellationToken);
if (response.IsSuccessStatusCode)
{
try
{
var xPathDocument = new XPathDocument(await response.Content.ReadAsStreamAsync());
var xPathNavigator = xPathDocument.CreateNavigator();
if (xPathNavigator == null)
{
throw new FileHandlerException($"Failed to parse the response xml value.");
}
_cachedCurrencyCodes = xPathNavigator.Select("//CcyTbl/*");
return true;
}
catch (Exception ex)
{
throw new FileHandlerException($"Failed to parse the response xml value. {ex.Message}", ex);
}
}
else
{
return false;
}
}
}
[TransformFunction(FunctionType = EFunctionType.Rows, Category = "Currency", Name = "Currency name and codes.",
Description = "Distinct list of currency, fund and precious metal codes. Data is standard ISO 4217 [currency-iso.org](https://www.currency-iso.org/en/home/tables/table-a1.html).")]
public async Task<CurrencyEntity> CurrencyCodes(CancellationToken cancellationToken)
{
if (_cachedCurrencyCodes == null)
{
if (!await LoadCurrencyCode(cancellationToken))
{
return null;
}
_usedCurrencyCodes = new HashSet<string>();
}
if (_cachedCurrencyCodes == null) return null;
while (_cachedCurrencyCodes.MoveNext())
{
var node = _cachedCurrencyCodes.Current;
var currencyCode = node.SelectSingleNode("Ccy")?.Value;
if (_usedCurrencyCodes.Contains(currencyCode)) continue;
_usedCurrencyCodes.Add(currencyCode);
var currencyEntity = new CurrencyEntity()
{
CurrencyNumber = node.SelectSingleNode("CcyNbr")?.ValueAsInt ?? 0,
CurrencyCode = currencyCode,
CurrencyName = node.SelectSingleNode("CcyNm")?.Value,
};
return currencyEntity;
}
return null;
}
[TransformFunction(FunctionType = EFunctionType.Rows, Category = "Currency", Name = "Country to currency name and codes",
Description = "List of currency, fund and precious metal codes by country (currency codes are not unique in this list). Data is standard ISO 4217 from [currency-iso.org](https://www.currency-iso.org/en/home/tables/table-a1.html).")]
public async Task<CountryCurrencyEntity> CountryCurrencyCodes(CancellationToken cancellationToken)
{
if (_cachedCurrencyCodes == null)
{
if (!await LoadCurrencyCode(cancellationToken))
{
return null;
}
}
if (_cachedCurrencyCodes == null) return null;
if(!_cachedCurrencyCodes.MoveNext()) return null;
var node = _cachedCurrencyCodes.Current;
var currencyEntity = new CountryCurrencyEntity()
{
Country = node.SelectSingleNode("CtryNm")?.Value,
CurrencyNumber = node.SelectSingleNode("CcyNbr")?.ValueAsInt ?? 0,
CurrencyCode = node.SelectSingleNode("Ccy")?.Value,
CurrencyName = node.SelectSingleNode("CcyNm")?.Value,
};
return currencyEntity;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml;
namespace SerializationTestTypes
{
[DataContract]
public struct VT
{
[DataMember]
public int b;
public VT(int v)
{
b = v;
}
}
public struct NotSer
{
public int a;
}
[DataContract]
public enum MyEnum1 : byte
{
[EnumMember]
red,
[EnumMember]
blue,
[EnumMember]
black
}
[Flags]
public enum Seasons1 : byte
{
None = 0,
Summer = 1,
Autumn = 2,
Winter = 4,
Spring = 8,
All = Summer | Autumn | Winter | Spring,
}
[Flags]
public enum Seasons2 : sbyte
{
None = 0,
Summer = 1,
Autumn = 2,
Winter = 4,
Spring = 8,
All = Summer | Autumn | Winter | Spring,
}
public struct MyStruct
{
public int value;
public string globName;
public MyStruct(bool init)
{
value = 10;
globName = "\uFEA5\uFEA3\uFEA8\uFEAA\uFEA3\uFEBB\uFEC2\uFEC3";
}
}
[DataContract]
public class EnumStructContainer
{
[DataMember]
public object p1 = new VT(10);
[DataMember]
public object p2 = new NotSer();
[DataMember]
public object[] enumArrayData = new object[] { MyEnum1.red, MyEnum1.black, MyEnum1.blue, Seasons1.Autumn, Seasons2.Spring };
[DataMember]
public object p3 = new MyStruct();
}
[DataContract]
public class Person
{
public Person(string variation)
{
Age = 6;
Name = "smith";
}
public Person()
{
}
[DataMember]
public int Age;
[DataMember]
public string Name;
}
[DataContract]
public class CharClass
{
public CharClass()
{
c = default(char);
c1 = char.MaxValue;
c2 = char.MinValue;
c3 = 'c';
}
[DataMember]
public char c;
[DataMember]
public char c1;
[DataMember]
public char c2;
[DataMember]
public char c3;
}
[DataContract]
[KnownType(typeof(MyEnum1))]
[KnownType(typeof(PublicDCStruct))]
public class AllTypes
{
public AllTypes()
{
a = false;
b = byte.MaxValue;
c = byte.MinValue;
e = decimal.MaxValue;
f = decimal.MinusOne;
g = decimal.MinValue;
h = decimal.One;
i = decimal.Zero;
j = default(decimal);
k = default(double);
l = double.Epsilon;
m = double.MaxValue;
n = double.MinValue;
o = double.NaN;
p = double.NegativeInfinity;
q = double.PositiveInfinity;
r = default(float);
s = float.Epsilon;
t = float.MinValue;
u = float.MaxValue;
v = float.NaN;
w = float.NegativeInfinity;
x = float.PositiveInfinity;
y = default(int);
z = int.MaxValue;
z1 = int.MinValue;
z2 = default(long);
z3 = long.MaxValue;
z4 = long.MinValue;
z5 = new object();
z6 = default(sbyte);
z7 = sbyte.MaxValue;
z8 = sbyte.MinValue;
z9 = default(short);
z91 = short.MaxValue;
z92 = short.MinValue;
z93 = "abc";
z94 = default(ushort);
z95 = ushort.MaxValue;
z96 = ushort.MinValue;
z97 = default(uint);
z98 = uint.MaxValue;
z99 = uint.MinValue;
z990 = default(ulong);
z991 = ulong.MaxValue;
z992 = ulong.MinValue;
}
[DataMember]
public bool a;
[DataMember]
public byte b;
[DataMember]
public byte c;
[DataMember]
public char d = char.MaxValue;
[DataMember]
public DateTime f5 = new DateTime();
[DataMember]
public Guid guidData = new Guid("5642b5d2-87c3-a724-2390-997062f3f7a2");
[DataMember]
public string strData;
[DataMember]
public decimal e;
[DataMember]
public decimal f;
[DataMember]
public decimal g;
[DataMember]
public decimal h;
[DataMember]
public decimal i;
[DataMember]
public decimal j;
[DataMember]
public double k;
[DataMember]
public double l;
[DataMember]
public double m;
[DataMember]
public double n;
[DataMember]
public double o;
[DataMember]
public double p;
[DataMember]
public double q;
[DataMember]
public float r;
[DataMember]
public float s;
[DataMember]
public float t;
[DataMember]
public float u;
[DataMember]
public float v;
[DataMember]
public float w;
[DataMember]
public float x;
[DataMember]
public int y;
[DataMember]
public int z;
[DataMember]
public int z1;
[DataMember]
public long z2;
[DataMember]
public long z3;
[DataMember]
public long z4;
[DataMember]
public object z5;
[DataMember]
public sbyte z6;
[DataMember]
public sbyte z7;
[DataMember]
public sbyte z8;
[DataMember]
public short z9;
[DataMember]
public short z91;
[DataMember]
public short z92;
[DataMember]
public string z93;
[DataMember]
public ushort z94;
[DataMember]
public ushort z95;
[DataMember]
public ushort z96;
[DataMember]
public uint z97;
[DataMember]
public uint z98;
[DataMember]
public uint z99;
[DataMember]
public ulong z990;
[DataMember]
public ulong z991;
[DataMember]
public ulong z992;
[DataMember]
[IgnoreMember]
public MyEnum1[] enumArrayData = new MyEnum1[] { MyEnum1.red };
[DataMember]
[IgnoreMember]
public XmlQualifiedName xmlQualifiedName = new XmlQualifiedName("WCF", "http://www.microsoft.com");
[DataMember]
[IgnoreMember]
public ValueType timeSpan = TimeSpan.MaxValue;
[DataMember]
[IgnoreMember]
public object obj = new object();
[DataMember]
[IgnoreMember]
public Uri uri = new Uri("http://www.microsoft.com");
[DataMember]
[IgnoreMember]
public Enum enumBase1 = MyEnum1.red;
[DataMember]
[IgnoreMember]
public Array array1 = new object[] { new object(), new object(), new object() };
[DataMember]
[IgnoreMember]
public ValueType valType = new PublicDCStruct(true);
[DataMember]
[IgnoreMember]
public Nullable<DateTimeOffset> nDTO = DateTimeOffset.MaxValue;
[DataMember]
[IgnoreMember]
public List<DateTimeOffset> lDTO = new List<DateTimeOffset>();
}
[DataContract]
[KnownType(typeof(MyEnum1))]
[KnownType(typeof(PublicDCStruct))]
public class AllTypes2
{
public AllTypes2()
{
a = false;
b = byte.MaxValue;
c = byte.MinValue;
e = decimal.MaxValue;
f = decimal.MinusOne;
g = decimal.MinValue;
h = decimal.One;
i = decimal.Zero;
j = default(decimal);
k = default(double);
l = double.Epsilon;
m = double.MaxValue;
n = double.MinValue;
o = double.NaN;
p = double.NegativeInfinity;
q = double.PositiveInfinity;
r = default(float);
s = float.Epsilon;
t = float.MinValue;
u = float.MaxValue;
v = float.NaN;
w = float.NegativeInfinity;
x = float.PositiveInfinity;
y = default(int);
z = int.MaxValue;
z1 = int.MinValue;
z2 = default(long);
z3 = long.MaxValue;
z4 = long.MinValue;
z5 = new object();
z6 = default(sbyte);
z7 = sbyte.MaxValue;
z8 = sbyte.MinValue;
z9 = default(short);
z91 = short.MaxValue;
z92 = short.MinValue;
z93 = "abc";
z94 = default(ushort);
z95 = ushort.MaxValue;
z96 = ushort.MinValue;
z97 = default(uint);
z98 = uint.MaxValue;
z99 = uint.MinValue;
z990 = default(ulong);
z991 = ulong.MaxValue;
z992 = ulong.MinValue;
}
[DataMember]
public bool a;
[DataMember]
public byte b;
[DataMember]
public byte c;
[DataMember]
public char d = char.MaxValue;
[DataMember]
public DateTime f5 = new DateTime();
[DataMember]
public Guid guidData = new Guid("cac76333-577f-7e1f-0389-789b0d97f395");
[DataMember]
public string strData;
[DataMember]
public decimal e;
[DataMember]
public decimal f;
[DataMember]
public decimal g;
[DataMember]
public decimal h;
[DataMember]
public decimal i;
[DataMember]
public decimal j;
[DataMember]
public double k;
[DataMember]
public double l;
[DataMember]
public double m;
[DataMember]
public double n;
[DataMember]
public double o;
[DataMember]
public double p;
[DataMember]
public double q;
[DataMember]
public float r;
[DataMember]
public float s;
[DataMember]
public float t;
[DataMember]
public float u;
[DataMember]
public float v;
[DataMember]
public float w;
[DataMember]
public float x;
[DataMember]
public int y;
[DataMember]
public int z;
[DataMember]
public int z1;
[DataMember]
public long z2;
[DataMember]
public long z3;
[DataMember]
public long z4;
[DataMember]
public object z5;
[DataMember]
public sbyte z6;
[DataMember]
public sbyte z7;
[DataMember]
public sbyte z8;
[DataMember]
public short z9;
[DataMember]
public short z91;
[DataMember]
public short z92;
[DataMember]
public string z93;
[DataMember]
public ushort z94;
[DataMember]
public ushort z95;
[DataMember]
public ushort z96;
[DataMember]
public uint z97;
[DataMember]
public uint z98;
[DataMember]
public uint z99;
[DataMember]
public ulong z990;
[DataMember]
public ulong z991;
[DataMember]
public ulong z992;
[DataMember]
[IgnoreMember]
public MyEnum1[] enumArrayData = new MyEnum1[] { MyEnum1.red };
[DataMember]
[IgnoreMember]
public XmlQualifiedName xmlQualifiedName = new XmlQualifiedName("WCF", "http://www.microsoft.com");
[DataMember]
[IgnoreMember]
public TimeSpan timeSpan = TimeSpan.MaxValue;
[DataMember]
[IgnoreMember]
public object obj = new object();
[DataMember]
[IgnoreMember]
public Uri uri = new Uri("http://www.microsoft.com");
[DataMember]
[IgnoreMember]
public Enum enumBase1 = MyEnum1.red;
[DataMember]
[IgnoreMember]
public Array array1 = new object[] { new object(), new object(), new object() };
[DataMember]
[IgnoreMember]
public ValueType valType = new PublicDCStruct(true);
[DataMember]
[IgnoreMember]
public Nullable<DateTimeOffset> nDTO = DateTimeOffset.MaxValue;
}
[DataContract]
public class DictContainer
{
[DataMember]
public Dictionary<byte[], byte[]> dictionaryData = new Dictionary<byte[], byte[]>();
public DictContainer()
{
dictionaryData.Add(new Guid("ec1f7b4b-c2d1-4c6e-95b6-060a111b0afd").ToByteArray(), new Guid("9831dc90-ca4c-4db2-9335-58a1025ecf29").ToByteArray());
dictionaryData.Add(new Guid("5e689847-1a10-4f72-aaae-19b247cd0878").ToByteArray(), new Guid("e7af8691-43d5-49e7-8775-1b0126bd943c").ToByteArray());
dictionaryData.Add(new Guid("711168dd-4a00-4de5-9f3e-38ddfbda0144").ToByteArray(), new Guid("2685b4af-09b6-4a56-81db-95231a3d0276").ToByteArray());
}
}
[DataContract]
public class ListContainer
{
[DataMember]
public List<string> listData = new List<string>();
public ListContainer()
{
listData.Add("TestData");
}
}
[DataContract]
[KnownType(typeof(string))]
public class ArrayContainer
{
[DataMember]
public ArrayList listData = new ArrayList();
public ArrayContainer(bool init)
{
listData.Add("TestData");
listData.Add("Test");
listData.Add(new Guid("c0a7310f-f369-481e-a990-39b121eae513"));
}
}
[DataContract]
[KnownType(typeof(MyPrivateEnum1[]))]
public class EnumContainer1
{
[DataMember]
public object myPrivateEnum1 = new MyPrivateEnum1[] { MyPrivateEnum1.red };
}
[DataContract]
[KnownType(typeof(MyPrivateEnum2[]))]
public class EnumContainer2
{
[DataMember]
public object myPrivateEnum2 = new MyPrivateEnum2[] { MyPrivateEnum2.red };
}
[DataContract]
[KnownType(typeof(MyPrivateEnum3[]))]
public class EnumContainer3
{
[DataMember]
public object myPrivateEnum3 = new MyPrivateEnum3[] { MyPrivateEnum3.red };
}
[DataContract]
public class WithStatic
{
public WithStatic()
{
sstr = "static string";
str = "instance string";
}
[DataMember]
public static string sstr;
[DataMember]
public string str;
}
[DataContract]
public class PrivateCstor
{
private PrivateCstor()
{
c = 22;
a = 10;
b = "string b";
c = 11;
}
public PrivateCstor(int i)
{
c = i;
}
private PrivateCstor(StreamingContext sc)
{
c = 33;
}
[DataMember]
public int a;
[DataMember]
public string b;
[DataMember]
public int c;
}
[DataContract]
public class DerivedFromPriC : PrivateCstor
{
public DerivedFromPriC() : base(int.MaxValue) { }
public DerivedFromPriC(int d)
: base(d)
{
this.d = d;
}
[DataMember]
public int d;
}
[DataContract]
public class EmptyDC
{
public EmptyDC()
{
a = 10;
}
[DataMember]
public int a;
public int A
{
set { a = value; }
get { return a; }
}
}
[DataContract(Name = "Enum")]
public enum MyEnum
{
[EnumMember]
red,
[EnumMember]
blue,
[EnumMember]
black
}
[DataContract(Name = "Enum1")]
internal enum MyPrivateEnum1
{
[EnumMember]
red,
[EnumMember]
blue,
[EnumMember]
black
}
internal enum MyPrivateEnum2
{
[EnumMember]
red,
[EnumMember]
blue,
[EnumMember]
black
}
internal enum MyPrivateEnum3
{
red,
blue,
black
}
internal interface SomeProperties
{
int A { set; get; }
string B { set; get; }
}
[DataContract]
public class Base : SomeProperties
{
private int _a;
private string _b;
[DataMember]
public virtual int A
{
set { _a = value; }
get { return _a; }
}
[DataMember]
public virtual string B
{
set { _b = value; }
get { return _b; }
}
}
[DataContract]
public class Derived : Base
{
private int _a;
private string _b;
[DataMember]
override public int A
{
set { _a = value; }
get { return _a; }
}
[DataMember]
override public string B
{
set { _b = value; }
get { return _b; }
}
}
[DataContract]
public enum MyEnum2 : sbyte
{
[EnumMember]
red,
[EnumMember]
blue,
[EnumMember]
black
}
[DataContract]
public enum MyEnum3 : short
{
[EnumMember]
red,
[EnumMember]
blue,
[EnumMember]
black
}
[DataContract]
public enum MyEnum4 : ushort
{
[EnumMember]
red,
[EnumMember]
blue,
[EnumMember]
black
}
[DataContract]
public enum MyEnum7 : long
{
[EnumMember]
red,
[EnumMember]
blue,
[EnumMember]
black
}
[DataContract]
public enum MyEnum8 : ulong
{
[EnumMember]
red,
[EnumMember]
blue,
[EnumMember]
black
}
public class SeasonsEnumContainer
{
[IgnoreMember]
public Seasons1 member1 = Seasons1.Autumn;
[IgnoreMember]
public Seasons2 member2 = Seasons2.Spring;
[IgnoreMember]
public Seasons3 member3 = Seasons3.Winter;
}
[Flags]
public enum Seasons3 : short
{
None = 0,
Summer = 1,
Autumn = 2,
Winter = 4,
Spring = 8,
All = Summer | Autumn | Winter | Spring,
}
[DataContract]
public class list
{
[DataMember]
public int value;
[DataMember]
public list next;
}
[DataContract]
public class Arrays
{
public Arrays()
{
a1 = new int[] { };
a2 = new int[] { 1 };
a3 = new int[] { 1, 2, 3, 4 };
a4 = new int[10000];
}
[DataMember]
public int[] a1;
[DataMember]
public int[] a2;
[DataMember]
public int[] a3;
[DataMember]
public int[] a4;
}
[DataContract]
public class Array3
{
[DataMember]
public int[][] a1 = { new int[] { 1 }, new int[] { } };
}
[DataContract]
public class Properties
{
private int _a = 5;
[DataMember]
public int A
{
set { _a = value; }
get { return _a; }
}
}
[DataContract]
public class HaveNS
{
[DataMember]
public NotSer ns;
}
[DataContract]
public class OutClass
{
[DataContract]
public class NestedClass
{
[DataMember]
public int a = 10;
}
[DataMember]
public NestedClass nc = new NestedClass();
}
[DataContract]
public class Temp
{
[DataMember]
public int a = 10;
}
[DataContract]
public class Array22
{
[DataMember]
public int[] p = new int[] { 1 };
}
[DataContract]
[KnownType(typeof(VT))]
public class BoxedPrim
{
[DataMember]
public object p = new bool();
[DataMember]
public object p2 = new VT(10);
}
}
| |
//
// SocketBase.cs
//
using System ;
using System.Collections ;
using System.Collections.Generic ;
using System.IO ;
using System.Text ;
using System.Text.RegularExpressions ;
using System.Xml ;
using System.Xml.Xsl ;
using System.Xml.XPath ;
using System.Xml.Schema ;
using System.Diagnostics ;
using System.Reflection ;
using System.Threading ;
using System.Net ;
using SNS=System.Net.Sockets ;
using alby.core.threadpool ;
namespace alby.core.sockets
{
public class SocketBase
{
//
//
//
protected SNS.Socket _socket = null ;
//
//
//
public SNS.Socket RawSocket
{
get
{
return _socket ;
}
set
{
_socket = value ;
}
}
//
//
//
protected byte[] _receiveBuffer = new byte[ SocketConstants.SOCKET_MAX_TRANSFER_BYTES ] ;
//
//
//
public byte[] ReceiveBuffer
{
get
{
return _receiveBuffer ;
}
}
//
//
//
protected long _statsBytesSent = 0 ;
protected long _statsBytesReceived = 0 ;
//
//
//
public void ResetStats()
{
_statsBytesSent = 0 ;
_statsBytesReceived = 0 ;
}
//
//
//
public long BytesSent
{
get
{
return _statsBytesSent ;
}
}
//
//
//
public long BytesReceived
{
get
{
return _statsBytesReceived ;
}
}
//
//
//
public SocketBase()
{
}
//
//
//
public string ReceiveString()
{
int bytes = this.ReceiveBytes() ;
if ( bytes == 0 ) return "" ;
return Encoding.UTF8.GetString( _receiveBuffer, 0, bytes ) ;
}
//
//
//
public int ReceiveBytes()
{
Array.Clear( _receiveBuffer, 0, _receiveBuffer.Length ) ;
if ( _socket == null )
throw new SocketException( "Socket is null." ) ;
_socket.Poll( -1, SNS.SelectMode.SelectRead ) ; // wait until we can read
// read the 4 byte header that tells us how many bytes we will get
byte[] readHeader = new byte[4];
_socket.Receive( readHeader, 0, 4, SNS.SocketFlags.None ) ;
int bytesToRead = BitConverter.ToInt32( readHeader, 0 ) ;
//Helper.WriteLine( "+++bytesToRead==" + bytesToRead ) ;
// read the bytes in a loop
int readBlockSize = (int) _socket.GetSocketOption( SNS.SocketOptionLevel.Socket, SNS.SocketOptionName.ReceiveBuffer ) ;
//Helper.WriteLine( "+++readBlockSize==" + readBlockSize ) ;
int bytesReadSoFar = 0 ;
while ( true )
{
int bytesLeftToRead = bytesToRead - bytesReadSoFar ;
if ( bytesLeftToRead <= 0 ) break ; // finished receiving
_socket.Poll( -1, SNS.SelectMode.SelectRead ) ; // wait until we can read
// do the read
int bytesToReadThisTime = Math.Min( readBlockSize, bytesLeftToRead ) ;
if ( bytesToReadThisTime + bytesReadSoFar > SocketConstants.SOCKET_MAX_TRANSFER_BYTES )
throw new SocketException( "You are trying to read " + bytesToRead + " bytes. Dont read more than " + SocketConstants.SOCKET_MAX_TRANSFER_BYTES + " bytes." ) ;
int bytesReadThisTime = _socket.Receive( _receiveBuffer, bytesReadSoFar, bytesToReadThisTime, SNS.SocketFlags.None ) ;
//Helper.WriteLine( "+++bytesReadThisTime==" + bytesReadThisTime ) ;
bytesReadSoFar += bytesReadThisTime ;
}
_statsBytesReceived += bytesReadSoFar ; // update stats
//Helper.WriteLine( "+++finished reading" ) ;
return bytesReadSoFar ;
}
//
//
//
public void Send( byte[] buffer, int bytesToSend )
{
if ( bytesToSend > SocketConstants.SOCKET_MAX_TRANSFER_BYTES )
throw new SocketException( "You are trying to send " + bytesToSend + " bytes. Dont send more than " + SocketConstants.SOCKET_MAX_TRANSFER_BYTES + " bytes." ) ;
if ( _socket == null )
throw new SocketException( "Socket is null." ) ;
_socket.Poll( -1, SNS.SelectMode.SelectWrite ) ; // wait until we can write
// send the 4 byte header
//Helper.WriteLine( "---bytesToSend==" + bytesToSend ) ;
byte[] sendHeader = BitConverter.GetBytes( bytesToSend ) ; // first send the number of bytes that we will be sending
_socket.Send( sendHeader, 4, 0 ) ;
// send the bytes in a loop
int sendBlockSize = (int) _socket.GetSocketOption( SNS.SocketOptionLevel.Socket, SNS.SocketOptionName.SendBuffer ) ;
//Helper.WriteLine( "---SendBlockSize==" + sendBlockSize ) ;
int bytesSentSoFar = 0 ;
while ( true )
{
int bytesLeftToSend = bytesToSend - bytesSentSoFar ;
if ( bytesLeftToSend <= 0 ) break ; // finished sending
_socket.Poll( -1, SNS.SelectMode.SelectWrite ) ; // wait until we can write
// do the write
int bytesToSendThisTime = Math.Min( sendBlockSize, bytesLeftToSend ) ;
int bytesSentThisTime = _socket.Send( buffer, bytesSentSoFar, bytesToSendThisTime, SNS.SocketFlags.None ) ;
//Helper.WriteLine( "---bytesSentThisTime==" + bytesSentThisTime ) ;
bytesSentSoFar += bytesSentThisTime ;
}
_statsBytesSent += bytesSentSoFar ; // update stats
//Helper.WriteLine( "_statsBytesSent: " + _statsBytesSent ) ;
//Helper.WriteLine( "---finished sending" ) ;
}
//
//
//
public void Send( string str )
{
byte[] buffer = Encoding.UTF8.GetBytes( str ) ; // UTF8
this.Send( buffer ) ;
}
//
//
//
public void Send( byte[] buffer )
{
this.Send( buffer, buffer.Length ) ;
}
//
//
//
protected string _separator = "___" + new string( '\x269B', 10 ) + "___" ; // the nuclear symbol, 10 of them
public string DictionarySeparator
{
get
{
return _separator ;
}
set
{
_separator = value ;
}
}
//
//
//
public void Send( Dictionary<string,string> dic )
{
string str = this.SerialiseDictionary( dic, _separator ) ;
this.Send( str ) ;
}
//
//
//
public Dictionary<string,string> ReceiveDictionary()
{
string str = this.ReceiveString() ;
return this.DeserialiseDictionary( str, _separator ) ;
}
//
// add key value pairs
//
protected string SerialiseDictionary( Dictionary<string,string> dic, string separator )
{
StringBuilder bob = new StringBuilder() ;
foreach( string key in dic.Keys )
{
string value = dic[ key ] ;
bob.Append( key ) ;
bob.Append( separator ) ;
bob.Append( value ) ;
bob.Append( separator ) ;
}
//Helper.WriteLine( "SerialiseDictionary\n" + bob.ToString() ) ;
return bob.ToString() ;
}
//
//
//
protected Dictionary<string,string> DeserialiseDictionary( string str, string separator )
{
Dictionary<string,string> dic = new Dictionary<string,string>() ;
string key = null ;
string value = null ;
string[] items = Regex.Split( str, separator ) ;
foreach ( string item in items )
{
if ( key == null )
key = item ;
else
{
value = item ;
dic.Add( key, value ) ;
key = null ;
value = null ;
}
}
return dic ;
}
} // end class
}
| |
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 ApiTute.Areas.HelpPage.ModelDescriptions;
using ApiTute.Areas.HelpPage.Models;
namespace ApiTute.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);
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="EntityReference.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
namespace System.Data.Objects.DataClasses
{
using System.Collections.Generic;
using System.Data;
using System.Data.Common.Utils;
using System.Data.Metadata.Edm;
using System.Data.Objects.Internal;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
/// <summary>
/// Models a relationship end with multiplicity 1.
/// </summary>
[DataContract]
[Serializable]
public abstract class EntityReference : RelatedEnd
{
// ------
// Fields
// ------
// The following fields are serialized. Adding or removing a serialized field is considered
// a breaking change. This includes changing the field type or field name of existing
// serialized fields. If you need to make this kind of change, it may be possible, but it
// will require some custom serialization/deserialization code.
// The following field is valid only for detached EntityReferences, see EntityKey property for more details.
private EntityKey _detachedEntityKey = null;
// The following field is used to cache the FK value to the principal for FK relationships.
// It is okay to not serialize this field because it is only used when the entity is tracked.
// For a detached entity it can always be null and cause no problems.
[NonSerialized]
private EntityKey _cachedForeignKey;
// ------------
// Constructors
// ------------
/// <summary>
/// The default constructor is required for some serialization scenarios. It should not be used to
/// create new EntityReferences. Use the GetRelatedReference or GetRelatedEnd methods on the RelationshipManager
/// class instead.
/// </summary>
internal EntityReference()
{
}
internal EntityReference(IEntityWrapper wrappedOwner, RelationshipNavigation navigation, IRelationshipFixer relationshipFixer)
: base(wrappedOwner, navigation, relationshipFixer)
{
}
/// <summary>
/// Returns the EntityKey of the target entity associated with this EntityReference.
///
/// Is non-null in the following scenarios:
/// (a) Entities are tracked by a context and an Unchanged or Added client-side relationships exists for this EntityReference's owner with the
/// same RelationshipName and source role. This relationship could have been created explicitly by the user (e.g. by setting
/// the EntityReference.Value, setting this property directly, or by calling EntityCollection.Add) or automatically through span queries.
/// (b) If the EntityKey was non-null before detaching an entity from the context, it will still be non-null after detaching, until any operation
/// occurs that would set it to null, as described below.
/// (c) Entities are detached and the EntityKey is explicitly set to non-null by the user.
/// (d) Entity graph was created using a NoTracking query with full span
///
/// Is null in the following scenarios:
/// (a) Entities are tracked by a context but there is no Unchanged or Added client-side relationship for this EntityReference's owner with the
/// same RelationshipName and source role.
/// (b) Entities are tracked by a context and a relationship exists, but the target entity has a temporary key (i.e. it is Added) or the key
/// is one of the special keys
/// (c) Entities are detached and the relationship was explicitly created by the user.
/// </summary>
[DataMember]
public EntityKey EntityKey
{
// This is the only scenario where it is valid to have a null Owner, so don't check it
get
{
if (this.ObjectContext != null && !UsingNoTracking)
{
Debug.Assert(this.WrappedOwner.Entity != null, "Unexpected null Owner on EntityReference attached to a context");
EntityKey attachedKey = null;
// If this EntityReference contains an entity, look up the key on that object
if (CachedValue.Entity != null)
{
// While processing an attach the owner may have a context while the target does not. This means
// that the target may gave an entity but not yet have an attached entity key.
attachedKey = CachedValue.EntityKey;
if (attachedKey != null && !IsValidEntityKeyType(attachedKey))
{
// don't return temporary or special keys from this property
attachedKey = null;
}
}
else
{
if (IsForeignKey)
{
// For dependent ends, return the value of the cached foreign key if it is not conceptually null
if (IsDependentEndOfReferentialConstraint(false) && _cachedForeignKey != null)
{
if (!ForeignKeyFactory.IsConceptualNullKey(_cachedForeignKey))
{
attachedKey = _cachedForeignKey;
}
}
else
{
// Principal ends or ends that haven't been fixed up yet (i.e during Add/Attach) should use the DetachedEntityKey value
// that contains the last known value that was set
attachedKey = DetachedEntityKey;
}
}
else
{
// There could still be an Added or Unchanged relationship with a stub entry
EntityKey ownerKey = WrappedOwner.EntityKey;
foreach (RelationshipEntry relationshipEntry in this.ObjectContext.ObjectStateManager.FindRelationshipsByKey(ownerKey))
{
// We only care about the relationships that match the AssociationSet and source role for the owner of this EntityReference
if (relationshipEntry.State != EntityState.Deleted &&
relationshipEntry.IsSameAssociationSetAndRole((AssociationSet)RelationshipSet, (AssociationEndMember)this.FromEndProperty, ownerKey))
{
Debug.Assert(attachedKey == null, "Found more than one non-Deleted relationship for the same AssociationSet and source role");
attachedKey = relationshipEntry.RelationshipWrapper.GetOtherEntityKey(ownerKey);
// key should never be temporary or special since it came from a key entry
}
}
}
}
Debug.Assert(attachedKey == null || IsValidEntityKeyType(attachedKey),
"Unexpected temporary or special key");
return attachedKey;
}
else
{
return DetachedEntityKey;
}
}
set
{
SetEntityKey(value, forceFixup: false);
}
}
internal void SetEntityKey(EntityKey value, bool forceFixup)
{
if (value != null && value == EntityKey && (ReferenceValue.Entity != null || (ReferenceValue.Entity == null && !forceFixup)))
{
// "no-op" -- this is not really no-op in the attached case, because at a minimum we have to do a key lookup,
// worst case we have to review all relationships for the owner entity
// However, if we don't do this, we can get into a scenario where we are setting the key to the same thing it's already set to
// and this could have side effects, especially with RI constraints and cascade delete. We don't want to delete something
// and then add it back, if that deleting could have additional unexpected effects. Don't bother doing this check if value is
// null, because EntityKey could be null even if there are Added/Unchanged relationships, if the target entity has a temporary key.
// In that case, we still need to delete that existing relationship, so it's not a no-op
return;
}
if (this.ObjectContext != null && !UsingNoTracking)
{
Debug.Assert(this.WrappedOwner.Entity != null, "Unexpected null Owner on EntityReference attached to a context");
// null is a valid value for the EntityKey, but temporary and special keys are not
// devnote: Can't check this on detached references because this property could be set to a temp key during deserialization,
// if the key hasn't finished deserializing yet.
if (value != null && !IsValidEntityKeyType(value))
{
throw EntityUtil.CannotSetSpecialKeys();
}
if (value == null)
{
if (AttemptToNullFKsOnRefOrKeySetToNull())
{
DetachedEntityKey = null;
}
else
{
ReferenceValue = EntityWrapperFactory.NullWrapper;
}
}
else
{
// Verify that the key has the right EntitySet for this RelationshipSet
EntitySet targetEntitySet = value.GetEntitySet(ObjectContext.MetadataWorkspace);
CheckRelationEntitySet(targetEntitySet);
value.ValidateEntityKey(ObjectContext.MetadataWorkspace, targetEntitySet, true /*isArgumentException */, "value");
ObjectStateManager manager = this.ObjectContext.ObjectStateManager;
// If we already have an entry with this key, we just need to create a relationship with it
bool addNewRelationship = false;
// If we don't already have any matching entries for this key, we'll have to create a new entry
bool addKeyEntry = false;
EntityEntry targetEntry = manager.FindEntityEntry(value);
if (targetEntry != null)
{
// If it's not a key entry, just use the entity to set this reference's Value
if (!targetEntry.IsKeyEntry)
{
// Delegate to the Value property to clear any existing relationship
// and to add the new one. This will fire the appropriate events and
// ensure that the related ends are connected.
// It has to be a TEntity since we already verified that the EntitySet is correct above
this.ReferenceValue = targetEntry.WrappedEntity;
}
else
{
// if the existing entry is a key entry, we just need to
// add a new relationship between the source entity and that key
addNewRelationship = true;
}
}
else
{
// no entry exists, so we'll need to add a key along with the relationship
addKeyEntry = !IsForeignKey;
addNewRelationship = true;
}
if (addNewRelationship)
{
EntityKey ownerKey = ValidateOwnerWithRIConstraints(targetEntry == null ? null : targetEntry.WrappedEntity, value, checkBothEnds: true);
// Verify that the owner is in a valid state for adding a relationship
ValidateStateForAdd(this.WrappedOwner);
if (addKeyEntry)
{
manager.AddKeyEntry(value, targetEntitySet);
}
// First, clear any existing relationships
manager.TransactionManager.EntityBeingReparented = WrappedOwner.Entity;
try
{
ClearCollectionOrRef(null, null, /*doCascadeDelete*/ false);
}
finally
{
manager.TransactionManager.EntityBeingReparented = null;
}
// Then add the new one
if (IsForeignKey)
{
DetachedEntityKey = value;
// Update the FK values in this entity
if (IsDependentEndOfReferentialConstraint(false))
{
UpdateForeignKeyValues(WrappedOwner, value);
}
}
else
{
RelationshipWrapper wrapper = new RelationshipWrapper((AssociationSet)RelationshipSet, RelationshipNavigation.From, ownerKey, RelationshipNavigation.To, value);
// Add the relationship in the unchanged state if
EntityState relationshipState = EntityState.Added;
// If this is an unchanged/modified dependent end of a relationship and we are allowing the EntityKey to be set
// create the relationship in the Unchanged state because the state must "match" the dependent end state
if (!ownerKey.IsTemporary && IsDependentEndOfReferentialConstraint(false))
{
relationshipState = EntityState.Unchanged;
}
manager.AddNewRelation(wrapper, relationshipState);
}
}
}
}
else
{
// Just set the field for detached object -- during Attach/Add we will make sure this value
// is not in conflict if the EntityReference contains a real entity. We cannot always determine the
// EntityKey for any real entity in the detached state, so we don't bother to do it here.
DetachedEntityKey = value;
}
}
/// <summary>
/// This method is called when either the EntityKey or the Value property is set to null when it is
/// already null. For an FK association of a tracked entity the method will attempt to null FKs
/// thereby deleting the relationship. This may result in conceptual nulls being set.
/// </summary>
internal bool AttemptToNullFKsOnRefOrKeySetToNull()
{
if (ReferenceValue.Entity == null &&
WrappedOwner.Entity != null &&
WrappedOwner.Context != null &&
!UsingNoTracking &&
IsForeignKey)
{
// For identifying relationships, we throw, since we cannot set primary key values to null, unless
// the entity is in the Added state.
if (WrappedOwner.ObjectStateEntry.State != EntityState.Added &&
IsDependentEndOfReferentialConstraint(checkIdentifying: true))
{
throw EntityUtil.CannotChangeReferentialConstraintProperty();
}
// For unloaded FK relationships in the context we attempt to null FK values here, which will
// delete the relationship.
RemoveFromLocalCache(EntityWrapperFactory.NullWrapper, resetIsLoaded: true, preserveForeignKey: false);
return true;
}
return false;
}
internal EntityKey AttachedEntityKey
{
get
{
Debug.Assert(this.ObjectContext != null && !UsingNoTracking, "Should only need to access AttachedEntityKey property on attached EntityReferences");
return this.EntityKey;
}
}
internal EntityKey DetachedEntityKey
{
get
{
return _detachedEntityKey;
}
set
{
_detachedEntityKey = value;
}
}
internal EntityKey CachedForeignKey
{
get
{
return EntityKey ?? _cachedForeignKey;
}
}
internal void SetCachedForeignKey(EntityKey newForeignKey, EntityEntry source)
{
if (this.ObjectContext != null && this.ObjectContext.ObjectStateManager != null && // are we attached?
source != null && // do we have an entry?
_cachedForeignKey != null && !ForeignKeyFactory.IsConceptualNullKey(_cachedForeignKey) // do we have an fk?
&& _cachedForeignKey != newForeignKey) // is the FK different from the one that we already have?
{
this.ObjectContext.ObjectStateManager.RemoveEntryFromForeignKeyIndex(_cachedForeignKey, source);
}
_cachedForeignKey = newForeignKey;
}
internal IEnumerable<EntityKey> GetAllKeyValues()
{
if (EntityKey != null)
{
yield return EntityKey;
}
if (_cachedForeignKey != null)
{
yield return _cachedForeignKey;
}
if (_detachedEntityKey != null)
{
yield return _detachedEntityKey;
}
}
internal abstract IEntityWrapper CachedValue
{
get;
}
internal abstract IEntityWrapper ReferenceValue
{
get;
set;
}
internal EntityKey ValidateOwnerWithRIConstraints(IEntityWrapper targetEntity, EntityKey targetEntityKey, bool checkBothEnds)
{
EntityKey ownerKey = WrappedOwner.EntityKey;
// Check if Referential Constraints are violated
if ((object)ownerKey != null &&
!ownerKey.IsTemporary &&
IsDependentEndOfReferentialConstraint(checkIdentifying: true))
{
Debug.Assert(CachedForeignKey != null || EntityKey == null, "CachedForeignKey should not be null if EntityKey is not null.");
ValidateSettingRIConstraints(targetEntity,
targetEntityKey == null,
(this.CachedForeignKey != null && this.CachedForeignKey != targetEntityKey));
}
else if (checkBothEnds && targetEntity != null && targetEntity.Entity != null)
{
EntityReference otherEnd = GetOtherEndOfRelationship(targetEntity) as EntityReference;
if (otherEnd != null)
{
otherEnd.ValidateOwnerWithRIConstraints(WrappedOwner, ownerKey, checkBothEnds: false);
}
}
return ownerKey;
}
internal void ValidateSettingRIConstraints(IEntityWrapper targetEntity, bool settingToNull, bool changingForeignKeyValue)
{
bool isNoTracking = targetEntity != null && targetEntity.MergeOption == MergeOption.NoTracking;
if (settingToNull || // setting the principle to null
changingForeignKeyValue || // existing key does not match incoming key
(targetEntity != null &&
!isNoTracking &&
(targetEntity.ObjectStateEntry == null || // setting to a detached principle
(EntityKey == null && targetEntity.ObjectStateEntry.State == EntityState.Deleted || // setting to a deleted principle
(CachedForeignKey == null && targetEntity.ObjectStateEntry.State == EntityState.Added))))) // setting to an added principle
{
throw EntityUtil.CannotChangeReferentialConstraintProperty();
}
}
/// <summary>
/// EntityReferences can only deferred load if they are empty
/// </summary>
internal override bool CanDeferredLoad
{
get
{
return IsEmpty();
}
}
/// <summary>
/// Takes key values from the given principal entity and transfers them to the foreign key properties
/// of the dependant entry. This method requires a context, but does not require that either
/// entity is in the context. This allows it to work in NoTracking cases where we have the context
/// but we're not tracked by that context.
/// </summary>
/// <param name="dependentEntity">The entity into which foreign key values will be written</param>
/// <param name="principalEntity">The entity from which key values will be obtained</param>
/// <param name="changedFKs">If non-null, then keeps track of FKs that have already been set such that an exception can be thrown if we find conflicting values</param>
/// <param name="forceChange">If true, then the property setter is called even if FK values already match,
/// which causes the FK properties to be marked as modified.</param>
internal void UpdateForeignKeyValues(IEntityWrapper dependentEntity, IEntityWrapper principalEntity, Dictionary<int, object> changedFKs, bool forceChange)
{
Debug.Assert(dependentEntity.Entity != null, "dependentEntity.Entity == null");
Debug.Assert(principalEntity.Entity != null, "principalEntity.Entity == null");
Debug.Assert(this.IsForeignKey, "cannot update foreign key values if the relationship is not a FK");
ReferentialConstraint constraint = ((AssociationType)this.RelationMetadata).ReferentialConstraints[0];
Debug.Assert(constraint != null, "null constraint");
bool isUnchangedDependent = (object)WrappedOwner.EntityKey != null &&
!WrappedOwner.EntityKey.IsTemporary &&
IsDependentEndOfReferentialConstraint(checkIdentifying: true);
ObjectStateManager stateManager = ObjectContext.ObjectStateManager;
stateManager.TransactionManager.BeginForeignKeyUpdate(this);
try
{
EntitySet principalEntitySet = ((AssociationSet)RelationshipSet).AssociationSetEnds[ToEndMember.Name].EntitySet;
StateManagerTypeMetadata principalTypeMetadata = stateManager.GetOrAddStateManagerTypeMetadata(principalEntity.IdentityType, principalEntitySet);
EntitySet dependentEntitySet = ((AssociationSet)RelationshipSet).AssociationSetEnds[FromEndProperty.Name].EntitySet;
StateManagerTypeMetadata dependentTypeMetadata = stateManager.GetOrAddStateManagerTypeMetadata(dependentEntity.IdentityType, dependentEntitySet);
var principalProps = constraint.FromProperties;
int numValues = principalProps.Count;
string[] keyNames = null;
object[] values = null;
if (numValues > 1)
{
keyNames = principalEntitySet.ElementType.KeyMemberNames;
values = new object[numValues];
}
for (int i = 0; i < numValues; i++)
{
int principalOrdinal = principalTypeMetadata.GetOrdinalforOLayerMemberName(principalProps[i].Name);
object value = principalTypeMetadata.Member(principalOrdinal).GetValue(principalEntity.Entity);
int dependentOrdinal = dependentTypeMetadata.GetOrdinalforOLayerMemberName(constraint.ToProperties[i].Name);
bool valueChanging = !ByValueEqualityComparer.Default.Equals(dependentTypeMetadata.Member(dependentOrdinal).GetValue(dependentEntity.Entity), value);
if (forceChange || valueChanging)
{
if (isUnchangedDependent)
{
ValidateSettingRIConstraints(principalEntity, settingToNull: value == null, changingForeignKeyValue: valueChanging);
}
// If we're tracking FK values that have already been set, then compare the value we are about to set
// to the value we previously set for this ordinal, if such a value exists. If they don't match then
// it means that we got conflicting FK values from two different PKs and we should throw.
if (changedFKs != null)
{
object previouslySetValue;
if (changedFKs.TryGetValue(dependentOrdinal, out previouslySetValue))
{
if (!ByValueEqualityComparer.Default.Equals(previouslySetValue, value))
{
throw new InvalidOperationException(System.Data.Entity.Strings.Update_ReferentialConstraintIntegrityViolation);
}
}
else
{
changedFKs[dependentOrdinal] = value;
}
}
dependentEntity.SetCurrentValue(
dependentEntity.ObjectStateEntry,
dependentTypeMetadata.Member(dependentOrdinal),
-1,
dependentEntity.Entity,
value);
}
if (numValues > 1)
{
int keyIndex = Array.IndexOf(keyNames, principalProps[i].Name);
Debug.Assert(keyIndex >= 0 && keyIndex < numValues, "Could not find constraint prop name in entity set key names");
values[keyIndex] = value;
}
else
{
SetCachedForeignKey(new EntityKey(principalEntitySet, value), dependentEntity.ObjectStateEntry);
}
}
if (numValues > 1)
{
SetCachedForeignKey(new EntityKey(principalEntitySet, values), dependentEntity.ObjectStateEntry);
}
if (WrappedOwner.ObjectStateEntry != null)
{
stateManager.ForgetEntryWithConceptualNull(WrappedOwner.ObjectStateEntry, resetAllKeys: false);
}
}
finally
{
stateManager.TransactionManager.EndForeignKeyUpdate();
}
}
/// <summary>
/// Takes key values from the given principal key and transfers them to the foreign key properties
/// of the dependant entry. This method requires a context, but does not require that either
/// entity or key is in the context. This allows it to work in NoTracking cases where we have the context
/// but we're not tracked by that context.
/// </summary>
/// <param name="dependentEntity">The entity into which foreign key values will be written</param>
/// <param name="principalEntity">The key from which key values will be obtained</param>
internal void UpdateForeignKeyValues(IEntityWrapper dependentEntity, EntityKey principalKey)
{
Debug.Assert(dependentEntity.Entity != null, "dependentEntity.Entity == null");
Debug.Assert(principalKey != null, "principalKey == null");
Debug.Assert(!principalKey.IsTemporary, "Cannot update from a temp key");
Debug.Assert(this.IsForeignKey, "cannot update foreign key values if the relationship is not a FK");
ReferentialConstraint constraint = ((AssociationType)this.RelationMetadata).ReferentialConstraints[0];
Debug.Assert(constraint != null, "null constraint");
ObjectStateManager stateManager = ObjectContext.ObjectStateManager;
stateManager.TransactionManager.BeginForeignKeyUpdate(this);
try
{
EntitySet dependentEntitySet = ((AssociationSet)RelationshipSet).AssociationSetEnds[FromEndProperty.Name].EntitySet;
StateManagerTypeMetadata dependentTypeMetadata = stateManager.GetOrAddStateManagerTypeMetadata(dependentEntity.IdentityType, dependentEntitySet);
for (int i = 0; i < constraint.FromProperties.Count; i++)
{
object value = principalKey.FindValueByName(constraint.FromProperties[i].Name);
int dependentOrdinal = dependentTypeMetadata.GetOrdinalforOLayerMemberName(constraint.ToProperties[i].Name);
object currentValue = dependentTypeMetadata.Member(dependentOrdinal).GetValue(dependentEntity.Entity);
if (!ByValueEqualityComparer.Default.Equals(currentValue, value))
{
dependentEntity.SetCurrentValue(
dependentEntity.ObjectStateEntry,
dependentTypeMetadata.Member(dependentOrdinal),
-1,
dependentEntity.Entity,
value);
}
}
SetCachedForeignKey(principalKey, dependentEntity.ObjectStateEntry);
if (WrappedOwner.ObjectStateEntry != null)
{
stateManager.ForgetEntryWithConceptualNull(WrappedOwner.ObjectStateEntry, resetAllKeys: false);
}
}
finally
{
stateManager.TransactionManager.EndForeignKeyUpdate();
}
}
internal object GetDependentEndOfReferentialConstraint(object relatedValue)
{
return IsDependentEndOfReferentialConstraint(checkIdentifying: false) ?
WrappedOwner.Entity :
relatedValue;
}
internal bool NavigationPropertyIsNullOrMissing()
{
Debug.Assert(RelationshipNavigation != null, "null RelationshipNavigation");
return !TargetAccessor.HasProperty || WrappedOwner.GetNavigationPropertyValue(this) == null;
}
/// <summary>
/// Attempts to null all FKs associated with the dependent end of this relationship on this entity.
/// This may result in setting conceptual nulls if the FK is not nullable.
/// </summary>
internal void NullAllForeignKeys()
{
Debug.Assert(ObjectContext != null, "Nulling FKs only works when attached.");
Debug.Assert(IsForeignKey, "Cannot null FKs for independent associations.");
ObjectStateManager stateManager = ObjectContext.ObjectStateManager;
EntityEntry entry = WrappedOwner.ObjectStateEntry;
TransactionManager transManager = stateManager.TransactionManager;
if (!transManager.IsGraphUpdate && !transManager.IsAttachTracking && !transManager.IsRelatedEndAdd)
{
ReferentialConstraint constraint = ((AssociationType)RelationMetadata).ReferentialConstraints.Single();
if (TargetRoleName == constraint.FromRole.Name) // Only do this on the dependent end
{
if (transManager.IsDetaching)
{
// If the principal is being detached, then the dependent must be added back to the
// dangling keys index.
// Perf note: The dependent currently gets added when it is being detached and is then
// removed again later in the process. The code could be optimized to prevent this.
Debug.Assert(entry != null, "State entry must exist while detaching.");
EntityKey foreignKey = ForeignKeyFactory.CreateKeyFromForeignKeyValues(entry, this);
if (foreignKey != null)
{
stateManager.AddEntryContainingForeignKeyToIndex(foreignKey, entry);
}
}
else if (!ReferenceEquals(stateManager.EntityInvokingFKSetter, WrappedOwner.Entity) && !transManager.IsForeignKeyUpdate)
{
transManager.BeginForeignKeyUpdate(this);
try
{
bool unableToNull = true;
bool canSetModifiedProps = entry != null && (entry.State == EntityState.Modified || entry.State == EntityState.Unchanged);
EntitySet dependentEntitySet = ((AssociationSet)RelationshipSet).AssociationSetEnds[FromEndProperty.Name].EntitySet;
StateManagerTypeMetadata dependentTypeMetadata = stateManager.GetOrAddStateManagerTypeMetadata(WrappedOwner.IdentityType, dependentEntitySet);
for (int i = 0; i < constraint.FromProperties.Count; i++)
{
string propertyName = constraint.ToProperties[i].Name;
int dependentOrdinal = dependentTypeMetadata.GetOrdinalforOLayerMemberName(propertyName);
StateManagerMemberMetadata member = dependentTypeMetadata.Member(dependentOrdinal);
// This is a check for nullability in o-space. However, o-space nullability is not the
// same as nullability of the underlying type. In particular, one difference is that when
// attribute-based mapping is used then a property can be marked as not nullable in o-space
// even when the underlying CLR type is nullable. For such a case, we treat the property
// as if it were not nullable (since that's what we have shipped) even though we could
// technically set it to null.
if (member.ClrMetadata.Nullable)
{
// Only set the value to null if it is not already null.
if (member.GetValue(WrappedOwner.Entity) != null)
{
WrappedOwner.SetCurrentValue(
WrappedOwner.ObjectStateEntry,
dependentTypeMetadata.Member(dependentOrdinal),
-1,
WrappedOwner.Entity,
null);
}
else
{
// Given that the current value is null, this next check confirms that the original
// value is also null. If it isn't, then we must make sure that the entity is marked
// as modified.
// This case can happen because fixup in the entity can set the FK to null while processing
// a RelatedEnd operation. This will be detected by DetectChanges, but when performing
// RelatedEnd operations the user is not required to call DetectChanges.
if (canSetModifiedProps && WrappedOwner.ObjectStateEntry.OriginalValues.GetValue(dependentOrdinal) != null)
{
entry.SetModifiedProperty(propertyName);
}
}
unableToNull = false;
}
else if (canSetModifiedProps)
{
entry.SetModifiedProperty(propertyName);
}
}
if (unableToNull)
{
// We were unable to null out the FK because all FK properties were non-nullable.
// We need to keep track of this state so that we treat the FK as null even though
// we were not able to null it. This prevents the FK from being used for fixup and
// also causes an exception to be thrown if an attempt is made to commit in this state.
//We should only set a conceptual null if the entity is tracked
if (entry != null)
{
//The CachedForeignKey may be null if we are putting
//back a Conceptual Null as part of roll back
EntityKey realKey = CachedForeignKey;
if (realKey == null)
{
realKey = ForeignKeyFactory.CreateKeyFromForeignKeyValues(entry, this);
}
// Note that the realKey can still be null here for a situation where the key is marked not nullable
// in o-space and yet the underlying type is nullable and the entity has been added or attached with a null
// value for the property. This will cause SaveChanges to throw unless the entity is marked
// as deleted before SaveChanges is called, in which case we don't want to set a conceptual
// null here as the call might very well succeed in the database since, unless the FK is
// a concurrency token, the value we have for it is not used at all for the delete.
if (realKey != null)
{
SetCachedForeignKey(ForeignKeyFactory.CreateConceptualNullKey(realKey), entry);
stateManager.RememberEntryWithConceptualNull(entry);
}
}
}
else
{
SetCachedForeignKey(null, entry);
}
}
finally
{
transManager.EndForeignKeyUpdate();
}
}
}
}
}
}
}
| |
// 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.AcceptanceTestsBodyComplex
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Inheritance operations.
/// </summary>
public partial class Inheritance : IServiceOperations<AutoRestComplexTestService>, IInheritance
{
/// <summary>
/// Initializes a new instance of the Inheritance class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Inheritance(AutoRestComplexTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestComplexTestService
/// </summary>
public AutoRestComplexTestService Client { get; private set; }
/// <summary>
/// Get complex types that extend others
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Siamese>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// 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, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (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;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Siamese>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Siamese>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that extend others
/// </summary>
/// <param name='complexBody'>
/// Please put a siamese with id=2, name="Siameee", color=green, breed=persion,
/// which hates 2 dogs, the 1st one named "Potato" with id=1 and food="tomato",
/// and the 2nd one named "Tomato" with id=-1 and food="french fries".
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Siamese complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
#if UNITY_WINRT && !UNITY_EDITOR
#define USE_WINRT
#endif
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using HUX.Utility;
using System.Reflection;
using HUX;
using UnityEngine.VR;
using HUX.Focus;
/// <summary>
/// InputShellMap is responsible for reading input from input sources and feeding it into InputShell.
/// It performs the switching logic so that a particular input source can be "activated" for use and
/// take precedence over
///
/// A brief overview of the flow of input:
/// Input APIs -> InputSourceBase -> InputShellMap -> InputShell -> HUX
///
/// </summary>
public class InputShellMap : Singleton<InputShellMap>
{
// Store a reference to the InputShell instance for convenient access
InputShell inputShell;
// InputSources gathers all the input sources
public InputSources inputSources = new InputSources();
// Helper class to handle deciding when to switch between the types of input
public InputSwitchLogic inputSwitchLogic = new InputSwitchLogic();
// Input states: Handle scaling for sources -> sematics
// Hands
public Vector2ControlState stateHandZoom = new Vector2ControlState();
// Mouse
public Vector2ControlState stateMouseWheelZoom = new Vector2ControlState(new Vector2(0, 1f / 40f));
// 6dof
public Vector2ControlState stateSixDOFZoom = new Vector2ControlState();
// controller
public Vector2ControlState stateLeftJoyScroll = new Vector2ControlState(new Vector2(-0.1f, -0.1f));
public Vector2ControlState stateLeftJoyTranslate = new Vector2ControlState(new Vector2(1f, 1f));
public Vector2ControlState stateTrigZoom = new Vector2ControlState(new Vector2(1f, 0.01f));
public Vector2ControlState stateRightJoyRotate = new Vector2ControlState(new Vector2(0.75f, 0.75f));
public Vector2ControlState statePadTranslate = new Vector2ControlState();
public Vector2ControlState statePadCardinal = new Vector2ControlState();
public Vector2ControlState stateLeftJoyCardinal = new Vector2ControlState();
// Targeting scroll gesture
public Vector2ControlState stateTargetScroll = new Vector2ControlState(false);
#region Debug controls
// If true, the gamepad will be used to control a world cursor
[DebugTunable]
public bool GamepadCursor = false;
#endregion
/// <summary>
/// Awake and init components
/// </summary>
protected override void Awake()
{
base.Awake();
inputSources.Init(gameObject);
inputSwitchLogic.Init(inputSources);
// I don't like hooking everything up with just events. There could be too many situations where
// a chain of subscribers is called all from one entry point, and the order of execution isn't very
// clear. A polling method would reduce these situations. The only downside is that it's somewhat
// convenient having events, especially if the input source is updating faster than the polling rate.
// Input sources can provide events if they don't aggregate their data. InputShell can provide events
// since it's convenient to use at the app level. A downside with using polling is that dependencies
// between sources can also get complicated and make update order unclear...
}
/// <summary>
/// Additional init, ensures that InputShell has instance allocated
/// </summary>
void Start()
{
inputShell = InputShell.Instance;
// Shell control states don't need to generate events
inputShell.ZoomVector.GenerateButtonEvents = false;
inputShell.ScrollVector.GenerateButtonEvents = false;
}
/// <summary>
/// MonoBehavior update. Updates the InputSources and InputSwitchLogic components,
/// updates all input states, and then applies the input to the shell. Finally,
/// updates InputShell.
/// </summary>
void Update()
{
// Apply debug tunes
inputSources.gamepad.IsEnabled = !GamepadCursor;
inputSources.worldCursorGamepad.IsEnabled = GamepadCursor;
// Update all InputSources (manually, so we can control update order)
inputSources.Update();
// Update the input switching logic
inputSwitchLogic.Update();
// Update input states
UpdateStates();
// Now apply to the shell and dev input states
ApplyInputToShell();
ApplyInputToDev();
// Update shell input, synchronously. This will allow InputShell to do any necessary logic before reporting input events
inputShell._Update();
}
/// <summary>
/// Maps input from sources and states to the shell input interface
/// </summary>
void ApplyInputToShell()
{
InputShell shell = inputShell;
// Update select button
bool selectButton = inputSwitchLogic.GetCurrentSelectPressed();
shell.SelectButton.ApplyState(selectButton);
// Update menu button
bool menuButton = inputSwitchLogic.GetAnyMenuPressed();
shell.MenuButton.ApplyState(menuButton);
// Update the scroll vector
shell.ScrollVector.AddState(inputSources.touch6D.touchState);
if (inputSources.gamepad.IsActiveTargetingSource() && !inputSources.gamepad.JoystickDragging)
{
shell.ScrollVector.AddState(stateLeftJoyScroll);
}
shell.ScrollVector.AddState(stateTargetScroll);
shell.ScrollVector.FinalizeState();
// Update the zoom vector
shell.ZoomVector.AddState(stateHandZoom);
shell.ZoomVector.AddState(stateSixDOFZoom);
shell.ZoomVector.AddState(inputSources.editor.dragControl);
shell.ZoomVector.AddState(stateMouseWheelZoom);
shell.ZoomVector.AddState(stateTrigZoom);
shell.ZoomVector.FinalizeState();
// Update the cardinal input vector
shell.CardinalVector.AddState(stateLeftJoyCardinal);
shell.CardinalVector.AddState(statePadCardinal);
shell.CardinalVector.FinalizeState();
// Update targeting ray
shell.TargetOrigin = inputSwitchLogic.GetTargetOrigin();
shell.TargetOrientation = inputSwitchLogic.GetTargetOrientation();
shell.TargetingReady = inputSwitchLogic.GetTargetingReady();
}
/// <summary>
/// Maps input from sources and states to the dev input interface
/// </summary>
void ApplyInputToDev()
{
InputDev dev = InputDev.Instance;
#if UNITY_EDITOR
// Update virtual cam input
dev.VirtualCamMovementToggle.ApplyState(inputSources.gamepad.xButtonPressed);
if (dev.VirtualCamMovementToggle.pressed)
{
dev.VirtualCamTranslate.AddState(false, inputSources.gamepad.leftJoyVector);
}
dev.VirtualCamTranslate.AddState(false, GetDevCameraVector(true));
dev.VirtualCamTranslate.FinalizeState();
if (dev.VirtualCamMovementToggle.pressed)
{
dev.VirtualCamVertAndRoll.AddState(false, new Vector2(-inputSources.gamepad.trigVector.x + inputSources.gamepad.trigVector.y, 0));
}
dev.VirtualCamVertAndRoll.AddState(false, GetDevCameraVector(false));
dev.VirtualCamVertAndRoll.FinalizeState();
dev.VirtualCamRotate.AddState(stateRightJoyRotate);
dev.VirtualCamRotate.FinalizeState();
#endif
}
Vector2 GetDevCameraVector(bool translate)
{
Vector2 vec = Vector2.zero;
if (translate)
{
vec.x += (InputSourceKeyboard.GetKey(KeyCode.A) ? -1f : 0) + (InputSourceKeyboard.GetKey(KeyCode.D) ? 1f : 0);
vec.y += (InputSourceKeyboard.GetKey(KeyCode.S) ? -1f : 0) + (InputSourceKeyboard.GetKey(KeyCode.W) ? 1f : 0);
}
else
{
vec.x += (InputSourceKeyboard.GetKey(KeyCode.E) ? 1f : 0) + (InputSourceKeyboard.GetKey(KeyCode.Q) ? -1f : 0);
}
return vec;
}
/// <summary>
/// Updates all control states. See InputControlState.cs.
/// </summary>
void UpdateStates()
{
// Hand zoom gesture
stateHandZoom.ApplyState(inputSources.hands.dragControl);
// Mouse wheel zoom
stateMouseWheelZoom.AddState(false, new Vector2(0, inputSources.editor.mouseSource.ScrollWheelDelta));
stateMouseWheelZoom.AddState(false, new Vector2(0, inputSources.worldCursorMouse.mouseSource.ScrollWheelDelta));
stateMouseWheelZoom.FinalizeState();
// SixDOF zoom gesture
stateSixDOFZoom.ApplyDelta(false, new Vector2(0, inputSources.touch6D.dragControl.delta.y));
// Controller input maps to scrolling, zooming, and freecam input
stateLeftJoyScroll.ApplyDelta(false, inputSources.gamepad.leftJoyVector);
stateLeftJoyTranslate.ApplyDelta(false, inputSources.gamepad.leftJoyVector);
stateTrigZoom.ApplyDelta(false, new Vector2(0, -inputSources.gamepad.trigVector.x + inputSources.gamepad.trigVector.y));
stateRightJoyRotate.ApplyDelta(false, inputSources.gamepad.rightJoyVector);
statePadTranslate.ApplyDelta(false, inputSources.gamepad.padVector);
statePadCardinal.ApplyDelta(false, inputSources.gamepad.padVector);
// Joystick cardinal state
Vector2 joyPos = Vector2.zero;
if (inputSources.gamepadCardinal.IsActiveTargetingSource())
{
float mag = 0.7f;
if (inputSources.gamepad.leftJoyVector.sqrMagnitude > mag * mag)
{
joyPos = inputSources.gamepad.leftJoyVector;
// Quantize
joyPos.x = (float)Mathf.RoundToInt(5f * joyPos.x) / 5f;
joyPos.y = (float)Mathf.RoundToInt(5f * joyPos.y) / 5f;
}
}
stateLeftJoyCardinal.ApplyDelta(false, joyPos);
// Update drag gesture
InputSourceBase curSource = inputSwitchLogic.CurrentTargetingSource as InputSourceBase;
if (curSource != null && curSource.IsManipulating())
{
stateTargetScroll.ApplyPos(true, curSource.GetManipulationPlaneProjection());
//Debug.Log("scroll state delta: " + stateTargetScroll.delta);
}
else
{
stateTargetScroll.ApplyPos(false, Vector2.zero);
//Debug.Log("scroll (done) state delta: " + stateTargetScroll.delta);
}
}
/// <summary>
/// Returns true if a hold gesture can be completed. Hold gestures cannot be completed if the user
/// is currently interacting with something.
/// </summary>
public bool CanCompleteHoldGesture()
{
return !InputShell.Instance.IsAnyManipulating();
}
}
/// <summary>
/// InputSwitchLogic holds a list of all targeting input sources and provides very simple logic for
/// activating and switching between inputs, and getting input from the current input.
/// InputSwitchLogic is instantiated and used by InputShellMap.
/// </summary>
[System.Serializable]
public class InputSwitchLogic
{
// Hold pointer to InputSources for convenient access
InputSources inputSources;
// The current targetin source
public ITargetingInputSource CurrentTargetingSource;
// List of all input sources which implement ITargetingInputSource
public List<ITargetingInputSource> TargetingSources = new List<ITargetingInputSource>();
// The same list, but InputSourceBase pointers
public List<InputSourceBase> TargetingSourceBases = new List<InputSourceBase>();
// Print to debug log when sources are activated or deactivated
public bool debugPrint = false;
/// <summary>
/// Initialization. Stores all input sources from InputSources which implement ITargetingInputSource
/// </summary>
/// <param name="_inputSources"></param>
public void Init(InputSources _inputSources)
{
inputSources = _inputSources;
foreach (InputSourceBase source in inputSources.sources)
{
//if( source.GetType().IsAssignableFrom(typeof(ITargetingInputSource)))
if (source is ITargetingInputSource)
{
TargetingSources.Add(source as ITargetingInputSource);
TargetingSourceBases.Add(source);
}
}
if (debugPrint)
{
Debug.Log("TargetingSources: " + TargetingSources.Count);
}
CurrentTargetingSource = inputSources.hands;
}
/// <summary>
/// Returns true if the current input source has select pressed.
/// </summary>
public bool GetCurrentSelectPressed()
{
if (CurrentTargetingSource != null)
{
return CurrentTargetingSource.IsSelectPressed();
}
return false;
}
/// <summary>
/// Returns true if any enabled input source has menu pressed
/// </summary>
public bool GetAnyMenuPressed()
{
foreach (InputSourceBase source in inputSources.sources)
{
if (source.IsEnabled)
{
ITargetingInputSource targetSource = source as ITargetingInputSource;
if (targetSource != null && targetSource.IsMenuPressed())
{
return true;
}
}
}
return false;
}
/// <summary>
/// Returns true if the specified source is the active targeting source
/// </summary>
public bool IsTargetingSourceActive(InputSourceBase source)
{
return CurrentTargetingSource == source as ITargetingInputSource;
}
/// <summary>
/// Returns the origin of the current targeting source
/// </summary>
public Vector3 GetTargetOrigin()
{
if (CurrentTargetingSource != null)
{
return CurrentTargetingSource.GetTargetOrigin();
}
return Veil.Instance.HeadTransform.position;
}
/// <summary>
/// Returns the rotation of the current targeting source
/// </summary>
public Quaternion GetTargetOrientation()
{
if (CurrentTargetingSource != null)
{
return CurrentTargetingSource.GetTargetRotation();
}
return Veil.Instance.HeadTransform.rotation;
}
/// <summary>
/// Returns true if the current targeting source is in the 'ready' state
/// </summary>
public bool GetTargetingReady()
{
if (CurrentTargetingSource != null)
{
return CurrentTargetingSource.IsReady();
}
return false;
}
/// <summary>
/// Gets the focuser tied to the current active input source.
/// </summary>
/// <returns></returns>
public AFocuser GetFocuserForCurrentTargetingSource()
{
AFocuser focuser = null;
if (FocusManager.Instance != null)
{
for (int index = 0; index < FocusManager.Instance.Focusers.Length; index++)
{
InputSourceFocuser sourceFocuser = FocusManager.Instance.Focusers[index] as InputSourceFocuser;
if (sourceFocuser != null && sourceFocuser.TargetingInputSource == CurrentTargetingSource)
{
focuser = FocusManager.Instance.Focusers[index];
break;
}
}
//If we haven't found a specific focuser use the gaze.
if (focuser == null)
{
focuser = FocusManager.Instance.GazeFocuser;
}
}
return focuser;
}
/// <summary>
/// Checks all enabled input sources and activates a new source if requested
/// </summary>
public void Update()
{
for (int i = 0; i < TargetingSources.Count; ++i)
{
ITargetingInputSource targetSource = TargetingSources[i];
if (TargetingSourceBases[i].IsEnabled)
{
if (targetSource != CurrentTargetingSource && targetSource.ShouldActivate())
{
ActivateTargetingSource(targetSource);
break;
}
}
}
}
/// <summary>
/// Deactivates the current source and activateds the new source
/// </summary>
public void ActivateTargetingSource(ITargetingInputSource targetSource)
{
if (CurrentTargetingSource != null && CurrentTargetingSource != targetSource)
{
CurrentTargetingSource.OnActivate(false);
}
CurrentTargetingSource = targetSource;
if (CurrentTargetingSource != null)
{
if (debugPrint)
{
Debug.Log("Activating source " + CurrentTargetingSource);
}
CurrentTargetingSource.OnActivate(true);
}
}
}
| |
/* ====================================================================
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 TestCases.HSSF.UserModel
{
using System;
using System.IO;
using System.Collections;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Record;
using NPOI.Util;
using NPOI.HSSF.Util;
using TestCases.HSSF;
using NUnit.Framework;
using NPOI.SS.UserModel;
using System.Drawing;
/**
* @author Brian Sanders (bsanders at risklabs dot com)
*/
[TestFixture]
public class TestHSSFPalette
{
private PaletteRecord palette;
private HSSFPalette hssfPalette;
[SetUp]
public void SetUp()
{
palette = new PaletteRecord();
hssfPalette = new HSSFPalette(palette);
}
/**
* Verifies that a custom palette can be Created, saved, and reloaded
*/
[Test]
public void TestCustomPalette()
{
//reading sample xls
HSSFWorkbook book = HSSFTestDataSamples.OpenSampleWorkbook("Simple.xls");
//creating custom palette
HSSFPalette palette = book.GetCustomPalette();
palette.SetColorAtIndex((short)0x12, (byte)101, (byte)230, (byte)100);
palette.SetColorAtIndex((short)0x3b, (byte)0, (byte)255, (byte)52);
//writing to disk; reading in and verifying palette
string tmppath = TempFile.GetTempFilePath("TestCustomPalette", ".xls");
FileStream fos = new FileStream(tmppath, FileMode.OpenOrCreate);
book.Write(fos);
fos.Close();
FileStream fis = new FileStream(tmppath, FileMode.Open,FileAccess.Read);
book = new HSSFWorkbook(fis);
fis.Close();
palette = book.GetCustomPalette();
HSSFColor color = palette.GetColor(HSSFColor.Coral.Index); //unmodified
Assert.IsNotNull(color, "Unexpected null in custom palette (unmodified index)");
byte[] expectedRGB = HSSFColor.Coral.Triplet;
byte[] actualRGB = color.RGB;
String msg = "Expected palette position to remain unmodified";
Assert.AreEqual(expectedRGB[0], actualRGB[0], msg);
Assert.AreEqual(expectedRGB[1], actualRGB[1], msg);
Assert.AreEqual(expectedRGB[2], actualRGB[2], msg);
color = palette.GetColor((short)0x12);
Assert.IsNotNull(color, "Unexpected null in custom palette (modified)");
actualRGB = color.RGB;
msg = "Expected palette modification to be preserved across save";
Assert.AreEqual((short)101, actualRGB[0], msg);
Assert.AreEqual((short)230, actualRGB[1], msg);
Assert.AreEqual((short)100, actualRGB[2], msg);
}
/**
* Uses the palette from cell stylings
*/
[Test]
public void TestPaletteFromCellColours()
{
HSSFWorkbook book = HSSFTestDataSamples.OpenSampleWorkbook("SimpleWithColours.xls");
HSSFPalette p = book.GetCustomPalette();
ICell cellA = book.GetSheetAt(0).GetRow(0).GetCell(0);
ICell cellB = book.GetSheetAt(0).GetRow(1).GetCell(0);
ICell cellC = book.GetSheetAt(0).GetRow(2).GetCell(0);
ICell cellD = book.GetSheetAt(0).GetRow(3).GetCell(0);
ICell cellE = book.GetSheetAt(0).GetRow(4).GetCell(0);
// Plain
Assert.AreEqual("I'm plain", cellA.StringCellValue);
Assert.AreEqual(64, cellA.CellStyle.FillForegroundColor);
Assert.AreEqual(64, cellA.CellStyle.FillBackgroundColor);
Assert.AreEqual(HSSFColor.COLOR_NORMAL, cellA.CellStyle.GetFont(book).Color);
Assert.AreEqual(0, (short)cellA.CellStyle.FillPattern);
Assert.AreEqual("0:0:0", p.GetColor((short)64).GetHexString());
Assert.AreEqual(null, p.GetColor((short)32767));
// Red
Assert.AreEqual("I'm red", cellB.StringCellValue);
Assert.AreEqual(64, cellB.CellStyle.FillForegroundColor);
Assert.AreEqual(64, cellB.CellStyle.FillBackgroundColor);
Assert.AreEqual(10, cellB.CellStyle.GetFont(book).Color);
Assert.AreEqual(0, (short)cellB.CellStyle.FillPattern);
Assert.AreEqual("0:0:0", p.GetColor((short)64).GetHexString());
Assert.AreEqual("FFFF:0:0", p.GetColor((short)10).GetHexString());
// Red + green bg
Assert.AreEqual("I'm red with a green bg", cellC.StringCellValue);
Assert.AreEqual(11, cellC.CellStyle.FillForegroundColor);
Assert.AreEqual(64, cellC.CellStyle.FillBackgroundColor);
Assert.AreEqual(10, cellC.CellStyle.GetFont(book).Color);
Assert.AreEqual(1, (short)cellC.CellStyle.FillPattern);
Assert.AreEqual("0:FFFF:0", p.GetColor((short)11).GetHexString());
Assert.AreEqual("FFFF:0:0", p.GetColor((short)10).GetHexString());
// Pink with yellow
Assert.AreEqual("I'm pink with a yellow pattern (none)", cellD.StringCellValue);
Assert.AreEqual(13, cellD.CellStyle.FillForegroundColor);
Assert.AreEqual(64, cellD.CellStyle.FillBackgroundColor);
Assert.AreEqual(14, cellD.CellStyle.GetFont(book).Color);
Assert.AreEqual(0, (short)cellD.CellStyle.FillPattern);
Assert.AreEqual("FFFF:FFFF:0", p.GetColor((short)13).GetHexString());
Assert.AreEqual("FFFF:0:FFFF", p.GetColor((short)14).GetHexString());
// Pink with yellow - full
Assert.AreEqual("I'm pink with a yellow pattern (full)", cellE.StringCellValue);
Assert.AreEqual(13, cellE.CellStyle.FillForegroundColor);
Assert.AreEqual(64, cellE.CellStyle.FillBackgroundColor);
Assert.AreEqual(14, cellE.CellStyle.GetFont(book).Color);
Assert.AreEqual(0, (short)cellE.CellStyle.FillPattern);
Assert.AreEqual("FFFF:FFFF:0", p.GetColor((short)13).GetHexString());
Assert.AreEqual("FFFF:0:FFFF", p.GetColor((short)14).GetHexString());
}
[Test]
public void TestFindSimilar()
{
HSSFWorkbook book = new HSSFWorkbook();
HSSFPalette p = book.GetCustomPalette();
// Add a few edge colours in
p.SetColorAtIndex((short)8, unchecked((byte)-1), (byte)0, (byte)0);
p.SetColorAtIndex((short)9, (byte)0, unchecked((byte)-1), (byte)0);
p.SetColorAtIndex((short)10, (byte)0, (byte)0, unchecked((byte)-1));
// And some near a few of them
p.SetColorAtIndex((short)11, unchecked((byte)-1), (byte)2, (byte)2);
p.SetColorAtIndex((short)12, unchecked((byte)-2), (byte)2, (byte)10);
p.SetColorAtIndex((short)13, unchecked((byte)-4), (byte)0, (byte)0);
p.SetColorAtIndex((short)14, unchecked((byte)-8), (byte)0, (byte)0);
Assert.AreEqual(
"FFFF:0:0", p.GetColor((short)8).GetHexString()
);
// Now Check we get the right stuff back
Assert.AreEqual(
p.GetColor((short)8).GetHexString(),
p.FindSimilarColor(unchecked((byte)-1), (byte)0, (byte)0).GetHexString()
);
Assert.AreEqual(
p.GetColor((short)8).GetHexString(),
p.FindSimilarColor(unchecked((byte)-2), (byte)0, (byte)0).GetHexString()
);
Assert.AreEqual(
p.GetColor((short)8).GetHexString(),
p.FindSimilarColor(unchecked((byte)-1), (byte)1, (byte)0).GetHexString()
);
Assert.AreEqual(
p.GetColor((short)11).GetHexString(),
p.FindSimilarColor(unchecked((byte)-1), (byte)2, (byte)1).GetHexString()
);
Assert.AreEqual(
p.GetColor((short)12).GetHexString(),
p.FindSimilarColor(unchecked((byte)-1), (byte)2, (byte)10).GetHexString()
);
book.Close();
}
/**
* Verifies that the generated gnumeric-format string values Match the
* hardcoded values in the HSSFColor default color palette
*/
private class ColorComparator1 : ColorComparator
{
public void Compare(HSSFColor expected, HSSFColor palette)
{
Assert.AreEqual(expected.GetHexString(), palette.GetHexString());
}
}
[Test]
public void TestGnumericStrings()
{
CompareToDefaults(new ColorComparator1());
}
/**
* Verifies that the palette handles invalid palette indexes
*/
private class ColorComparator2 : ColorComparator
{
public void Compare(HSSFColor expected, HSSFColor palette)
{
byte[] s1 = expected.RGB;
byte[] s2 = palette.RGB;
Assert.AreEqual(s1[0], s2[0]);
Assert.AreEqual(s1[1], s2[1]);
Assert.AreEqual(s1[2], s2[2]);
}
}
[Test]
public void TestBadIndexes()
{
//too small
hssfPalette.SetColorAtIndex((short)2, (byte)255, (byte)255, (byte)255);
//too large
hssfPalette.SetColorAtIndex((short)0x45, (byte)255, (byte)255, (byte)255);
//should still Match defaults;
CompareToDefaults(new ColorComparator2());
}
private void CompareToDefaults(ColorComparator c)
{
var colors = HSSFColor.GetIndexHash();
IEnumerator it = colors.Keys.GetEnumerator();
while (it.MoveNext())
{
int index = (int)it.Current;
HSSFColor expectedColor = (HSSFColor)colors[index];
HSSFColor paletteColor = hssfPalette.GetColor((short)index);
c.Compare(expectedColor, paletteColor);
}
}
[Test]
public void TestAddColor()
{
try
{
HSSFColor hssfColor = hssfPalette.AddColor((byte)10, (byte)10, (byte)10);
Assert.Fail();
}
catch (Exception)
{
// Failing because by default there are no colours left in the palette.
}
}
private interface ColorComparator
{
void Compare(HSSFColor expected, HSSFColor palette);
}
[Test]
public void Test48403()
{
HSSFWorkbook wb = new HSSFWorkbook();
Color color = Color.FromArgb(0, 0x6B, 0x6B); //decode("#006B6B");
HSSFPalette palette = wb.GetCustomPalette();
HSSFColor hssfColor = palette.FindColor(color.R, color.G, color.B);
Assert.IsNull(hssfColor);
palette.SetColorAtIndex(
(short)(PaletteRecord.STANDARD_PALETTE_SIZE - 1),
(byte)color.R, (byte)color.G,
(byte)color.B);
hssfColor = palette.GetColor((short)(PaletteRecord.STANDARD_PALETTE_SIZE - 1));
Assert.IsNotNull(hssfColor);
Assert.AreEqual(55, hssfColor.Indexed);
CollectionAssert.AreEqual(new short[] { 0, 107, 107 }, hssfColor.GetTriplet());
wb.Close();
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
//
// @module IOS Native Plugin for Unity3D
// @author Osipov Stanislav (Stan's Assets)
// @support stans.assets@gmail.com
//
////////////////////////////////////////////////////////////////////////////////
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class IOSInAppPurchaseManager : EventDispatcher {
public const string APPLE_VERIFICATION_SERVER = "https://buy.itunes.apple.com/verifyReceipt";
public const string SANDBOX_VERIFICATION_SERVER = "https://sandbox.itunes.apple.com/verifyReceipt";
public const string PRODUCT_BOUGHT = "product_bought";
public const string TRANSACTION_FAILED = "transaction_failed";
public const string RESTORE_TRANSACTION_FAILED = "restore_transaction_failed";
public const string RESTORE_TRANSACTION_COMPLETE = "restore_transaction_complete";
public const string VERIFICATION_RESPONSE = "verification_response";
public const string STORE_KIT_INITIALIZED = "store_kit_initialized";
public const string STORE_KIT_INITI_FAILED = "store_kit_init_failed";
private bool _IsStoreLoaded = false;
private bool _IsWaitingLoadResult = false;
private bool _IsInAppPurchasesEnabled = true;
private static int _nextId = 1;
private List<string> _productsIds = new List<string>();
private List<ProductTemplate> _products = new List<ProductTemplate>();
private Dictionary<int, IOSStoreProductView> _productsView = new Dictionary<int, IOSStoreProductView>();
private static IOSInAppPurchaseManager _instance;
private static string lastPurchasedProdcut;
//--------------------------------------
// INITIALIZE
//--------------------------------------
public static IOSInAppPurchaseManager instance {
get {
if(_instance == null) {
GameObject go = new GameObject("IOSInAppPurchaseManager");
DontDestroyOnLoad(go);
_instance = go.AddComponent<IOSInAppPurchaseManager>();
}
return _instance;
}
}
//--------------------------------------
// PUBLIC METHODS
//--------------------------------------
public void loadStore() {
if(_IsWaitingLoadResult || _IsStoreLoaded) {
return;
}
_IsWaitingLoadResult = true;
foreach(string pid in IOSNativeSettings.Instance.InAppProducts) {
addProductId(pid);
}
string ids = "";
int len = _productsIds.Count;
for(int i = 0; i < len; i++) {
if(i != 0) {
ids += ",";
}
ids += _productsIds[i];
}
IOSNativeMarketBridge.loadStore(ids);
}
public void buyProduct(string productId) {
if(!_IsStoreLoaded) {
Debug.LogWarning("buyProduct shouldn't be called before store kit initialized");
SendTransactionFailEvent(productId, "Store kit not yet initialized");
return;
} else {
if(!_IsInAppPurchasesEnabled) {
SendTransactionFailEvent(productId, "In App Purchases Disabled");
}
}
IOSNativeMarketBridge.buyProduct(productId);
}
public void addProductId(string productId) {
if(_productsIds.Contains(productId)) {
return;
}
_productsIds.Add(productId);
}
public ProductTemplate GetProductById(string id) {
foreach(ProductTemplate tpl in products) {
if(tpl.id.Equals(id)) {
return tpl;
}
}
return null;
}
public void restorePurchases() {
if(!_IsStoreLoaded || !_IsInAppPurchasesEnabled) {
dispatch(RESTORE_TRANSACTION_FAILED);
return;
}
IOSNativeMarketBridge.restorePurchases();
}
public void verifyLastPurchase(string url) {
IOSNativeMarketBridge.verifyLastPurchase (url);
}
public void RegisterProductView(IOSStoreProductView view) {
view.SetId(nextId);
_productsView.Add(view.id, view);
}
//--------------------------------------
// GET/SET
//--------------------------------------
public List<ProductTemplate> products {
get {
return _products;
}
}
public bool IsStoreLoaded {
get {
return _IsStoreLoaded;
}
}
public bool IsInAppPurchasesEnabled {
get {
return _IsInAppPurchasesEnabled;
}
}
public bool IsWaitingLoadResult {
get {
return _IsWaitingLoadResult;
}
}
public static int nextId {
get {
_nextId++;
return _nextId;
}
}
//--------------------------------------
// EVENTS
//--------------------------------------
private void onStoreKitStart(string data) {
int satus = System.Convert.ToInt32(data);
if(satus == 1) {
_IsInAppPurchasesEnabled = true;
} else {
_IsInAppPurchasesEnabled = false;
}
}
private void OnStoreKitInitFailed(string data) {
string[] storeData;
storeData = data.Split("|" [0]);
ISN_Error e = new ISN_Error();
e.code = System.Convert.ToInt32(storeData[0]);
e.description = storeData[1];
_IsStoreLoaded = false;
_IsWaitingLoadResult = false;
dispatch(STORE_KIT_INITI_FAILED, e);
}
public void onStoreDataReceived(string data) {
if(data.Equals(string.Empty)) {
Debug.Log("InAppPurchaseManager, no products avaiable: " + _products.Count.ToString());
dispatch (STORE_KIT_INITIALIZED);
return;
}
string[] storeData;
storeData = data.Split("|" [0]);
for(int i = 0; i < storeData.Length; i+=7) {
ProductTemplate tpl = new ProductTemplate();
tpl.id = storeData[i];
tpl.title = storeData[i + 1];
tpl.description = storeData[i + 2];
tpl.localizedPrice = storeData[i + 3];
tpl.price = storeData[i + 4];
tpl.currencyCode = storeData[i + 5];
tpl.currencySymbol = storeData[i + 6];
_products.Add(tpl);
}
Debug.Log("InAppPurchaseManager, tottal products loaded: " + _products.Count.ToString());
_IsStoreLoaded = true;
_IsWaitingLoadResult = false;
dispatch (STORE_KIT_INITIALIZED);
}
public void onProductBought(string array) {
string[] data;
data = array.Split("|" [0]);
IOSStoreKitResponse response = new IOSStoreKitResponse ();
response.productIdentifier = data [0];
response.receipt = data [1];
lastPurchasedProdcut = response.productIdentifier;
dispatch(PRODUCT_BOUGHT, response);
}
public void onTransactionFailed(string array) {
string[] data;
data = array.Split("|" [0]);
SendTransactionFailEvent(data [0], data [1]);
}
public void onVerificationResult(string array) {
string[] data;
data = array.Split("|" [0]);
IOSStoreKitVerificationResponse response = new IOSStoreKitVerificationResponse ();
response.status = System.Convert.ToInt32(data[0]);
response.originalJSON = data [1];
response.receipt = data [2];
response.productIdentifier = lastPurchasedProdcut;
dispatch (VERIFICATION_RESPONSE, response);
}
public void onRestoreTransactionFailed(string array) {
dispatch(RESTORE_TRANSACTION_FAILED);
}
public void onRestoreTransactionComplete(string array) {
dispatch(RESTORE_TRANSACTION_COMPLETE);
}
private void OnProductViewLoaded(string viewId) {
int id = System.Convert.ToInt32(viewId);
if(_productsView.ContainsKey(id)) {
_productsView[id].OnContentLoaded();
}
}
private void OnProductViewLoadedFailed(string viewId) {
int id = System.Convert.ToInt32(viewId);
if(_productsView.ContainsKey(id)) {
_productsView[id].OnContentLoadFailed();
}
}
private void OnProductViewDismissed(string viewId) {
int id = System.Convert.ToInt32(viewId);
if(_productsView.ContainsKey(id)) {
_productsView[id].OnProductViewDismissed();
}
}
//--------------------------------------
// PRIVATE METHODS
//--------------------------------------
private void SendTransactionFailEvent(string productIdentifier, string error) {
IOSStoreKitResponse response = new IOSStoreKitResponse ();
response.productIdentifier = productIdentifier;
response.error = error;
dispatch(TRANSACTION_FAILED, response);
}
//--------------------------------------
// DESTROY
//--------------------------------------
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using sc = System.Collections;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.AppEngine.V1
{
/// <summary>Settings for <see cref="FirewallClient"/> instances.</summary>
public sealed partial class FirewallSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="FirewallSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="FirewallSettings"/>.</returns>
public static FirewallSettings GetDefault() => new FirewallSettings();
/// <summary>Constructs a new <see cref="FirewallSettings"/> object with default settings.</summary>
public FirewallSettings()
{
}
private FirewallSettings(FirewallSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
ListIngressRulesSettings = existing.ListIngressRulesSettings;
BatchUpdateIngressRulesSettings = existing.BatchUpdateIngressRulesSettings;
CreateIngressRuleSettings = existing.CreateIngressRuleSettings;
GetIngressRuleSettings = existing.GetIngressRuleSettings;
UpdateIngressRuleSettings = existing.UpdateIngressRuleSettings;
DeleteIngressRuleSettings = existing.DeleteIngressRuleSettings;
OnCopy(existing);
}
partial void OnCopy(FirewallSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>FirewallClient.ListIngressRules</c> and <c>FirewallClient.ListIngressRulesAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings ListIngressRulesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>FirewallClient.BatchUpdateIngressRules</c> and <c>FirewallClient.BatchUpdateIngressRulesAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings BatchUpdateIngressRulesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>FirewallClient.CreateIngressRule</c> and <c>FirewallClient.CreateIngressRuleAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings CreateIngressRuleSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>FirewallClient.GetIngressRule</c> and <c>FirewallClient.GetIngressRuleAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetIngressRuleSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>FirewallClient.UpdateIngressRule</c> and <c>FirewallClient.UpdateIngressRuleAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateIngressRuleSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>FirewallClient.DeleteIngressRule</c> and <c>FirewallClient.DeleteIngressRuleAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings DeleteIngressRuleSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="FirewallSettings"/> object.</returns>
public FirewallSettings Clone() => new FirewallSettings(this);
}
/// <summary>
/// Builder class for <see cref="FirewallClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class FirewallClientBuilder : gaxgrpc::ClientBuilderBase<FirewallClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public FirewallSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public FirewallClientBuilder()
{
UseJwtAccessWithScopes = FirewallClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref FirewallClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FirewallClient> task);
/// <summary>Builds the resulting client.</summary>
public override FirewallClient Build()
{
FirewallClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<FirewallClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<FirewallClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private FirewallClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return FirewallClient.Create(callInvoker, Settings);
}
private async stt::Task<FirewallClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return FirewallClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => FirewallClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => FirewallClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => FirewallClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>Firewall client wrapper, for convenient use.</summary>
/// <remarks>
/// Firewall resources are used to define a collection of access control rules
/// for an Application. Each rule is defined with a position which specifies
/// the rule's order in the sequence of rules, an IP range to be matched against
/// requests, and an action to take upon matching requests.
///
/// Every request is evaluated against the Firewall rules in priority order.
/// Processesing stops at the first rule which matches the request's IP address.
/// A final rule always specifies an action that applies to all remaining
/// IP addresses. The default final rule for a newly-created application will be
/// set to "allow" if not otherwise specified by the user.
/// </remarks>
public abstract partial class FirewallClient
{
/// <summary>
/// The default endpoint for the Firewall service, which is a host of "appengine.googleapis.com" and a port of
/// 443.
/// </summary>
public static string DefaultEndpoint { get; } = "appengine.googleapis.com:443";
/// <summary>The default Firewall scopes.</summary>
/// <remarks>
/// The default Firewall scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/appengine.admin</description></item>
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/cloud-platform.read-only</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/appengine.admin",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="FirewallClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="FirewallClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="FirewallClient"/>.</returns>
public static stt::Task<FirewallClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new FirewallClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="FirewallClient"/> using the default credentials, endpoint and settings.
/// To specify custom credentials or other settings, use <see cref="FirewallClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="FirewallClient"/>.</returns>
public static FirewallClient Create() => new FirewallClientBuilder().Build();
/// <summary>
/// Creates a <see cref="FirewallClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="FirewallSettings"/>.</param>
/// <returns>The created <see cref="FirewallClient"/>.</returns>
internal static FirewallClient Create(grpccore::CallInvoker callInvoker, FirewallSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
Firewall.FirewallClient grpcClient = new Firewall.FirewallClient(callInvoker);
return new FirewallClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC Firewall client</summary>
public virtual Firewall.FirewallClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Lists the firewall rules of an application.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="FirewallRule"/> resources.</returns>
public virtual gax::PagedEnumerable<ListIngressRulesResponse, FirewallRule> ListIngressRules(ListIngressRulesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Lists the firewall rules of an application.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="FirewallRule"/> resources.</returns>
public virtual gax::PagedAsyncEnumerable<ListIngressRulesResponse, FirewallRule> ListIngressRulesAsync(ListIngressRulesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Replaces the entire firewall ruleset in one bulk operation. This overrides
/// and replaces the rules of an existing firewall with the new rules.
///
/// If the final rule does not match traffic with the '*' wildcard IP range,
/// then an "allow all" rule is explicitly added to the end of the list.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual BatchUpdateIngressRulesResponse BatchUpdateIngressRules(BatchUpdateIngressRulesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Replaces the entire firewall ruleset in one bulk operation. This overrides
/// and replaces the rules of an existing firewall with the new rules.
///
/// If the final rule does not match traffic with the '*' wildcard IP range,
/// then an "allow all" rule is explicitly added to the end of the list.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<BatchUpdateIngressRulesResponse> BatchUpdateIngressRulesAsync(BatchUpdateIngressRulesRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Replaces the entire firewall ruleset in one bulk operation. This overrides
/// and replaces the rules of an existing firewall with the new rules.
///
/// If the final rule does not match traffic with the '*' wildcard IP range,
/// then an "allow all" rule is explicitly added to the end of the list.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<BatchUpdateIngressRulesResponse> BatchUpdateIngressRulesAsync(BatchUpdateIngressRulesRequest request, st::CancellationToken cancellationToken) =>
BatchUpdateIngressRulesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates a firewall rule for the application.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual FirewallRule CreateIngressRule(CreateIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a firewall rule for the application.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<FirewallRule> CreateIngressRuleAsync(CreateIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates a firewall rule for the application.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<FirewallRule> CreateIngressRuleAsync(CreateIngressRuleRequest request, st::CancellationToken cancellationToken) =>
CreateIngressRuleAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual FirewallRule GetIngressRule(GetIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<FirewallRule> GetIngressRuleAsync(GetIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<FirewallRule> GetIngressRuleAsync(GetIngressRuleRequest request, st::CancellationToken cancellationToken) =>
GetIngressRuleAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual FirewallRule UpdateIngressRule(UpdateIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<FirewallRule> UpdateIngressRuleAsync(UpdateIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<FirewallRule> UpdateIngressRuleAsync(UpdateIngressRuleRequest request, st::CancellationToken cancellationToken) =>
UpdateIngressRuleAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Deletes the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual void DeleteIngressRule(DeleteIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteIngressRuleAsync(DeleteIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Deletes the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task DeleteIngressRuleAsync(DeleteIngressRuleRequest request, st::CancellationToken cancellationToken) =>
DeleteIngressRuleAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>Firewall client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Firewall resources are used to define a collection of access control rules
/// for an Application. Each rule is defined with a position which specifies
/// the rule's order in the sequence of rules, an IP range to be matched against
/// requests, and an action to take upon matching requests.
///
/// Every request is evaluated against the Firewall rules in priority order.
/// Processesing stops at the first rule which matches the request's IP address.
/// A final rule always specifies an action that applies to all remaining
/// IP addresses. The default final rule for a newly-created application will be
/// set to "allow" if not otherwise specified by the user.
/// </remarks>
public sealed partial class FirewallClientImpl : FirewallClient
{
private readonly gaxgrpc::ApiCall<ListIngressRulesRequest, ListIngressRulesResponse> _callListIngressRules;
private readonly gaxgrpc::ApiCall<BatchUpdateIngressRulesRequest, BatchUpdateIngressRulesResponse> _callBatchUpdateIngressRules;
private readonly gaxgrpc::ApiCall<CreateIngressRuleRequest, FirewallRule> _callCreateIngressRule;
private readonly gaxgrpc::ApiCall<GetIngressRuleRequest, FirewallRule> _callGetIngressRule;
private readonly gaxgrpc::ApiCall<UpdateIngressRuleRequest, FirewallRule> _callUpdateIngressRule;
private readonly gaxgrpc::ApiCall<DeleteIngressRuleRequest, wkt::Empty> _callDeleteIngressRule;
/// <summary>
/// Constructs a client wrapper for the Firewall service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="FirewallSettings"/> used within this client.</param>
public FirewallClientImpl(Firewall.FirewallClient grpcClient, FirewallSettings settings)
{
GrpcClient = grpcClient;
FirewallSettings effectiveSettings = settings ?? FirewallSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callListIngressRules = clientHelper.BuildApiCall<ListIngressRulesRequest, ListIngressRulesResponse>(grpcClient.ListIngressRulesAsync, grpcClient.ListIngressRules, effectiveSettings.ListIngressRulesSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callListIngressRules);
Modify_ListIngressRulesApiCall(ref _callListIngressRules);
_callBatchUpdateIngressRules = clientHelper.BuildApiCall<BatchUpdateIngressRulesRequest, BatchUpdateIngressRulesResponse>(grpcClient.BatchUpdateIngressRulesAsync, grpcClient.BatchUpdateIngressRules, effectiveSettings.BatchUpdateIngressRulesSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callBatchUpdateIngressRules);
Modify_BatchUpdateIngressRulesApiCall(ref _callBatchUpdateIngressRules);
_callCreateIngressRule = clientHelper.BuildApiCall<CreateIngressRuleRequest, FirewallRule>(grpcClient.CreateIngressRuleAsync, grpcClient.CreateIngressRule, effectiveSettings.CreateIngressRuleSettings).WithGoogleRequestParam("parent", request => request.Parent);
Modify_ApiCall(ref _callCreateIngressRule);
Modify_CreateIngressRuleApiCall(ref _callCreateIngressRule);
_callGetIngressRule = clientHelper.BuildApiCall<GetIngressRuleRequest, FirewallRule>(grpcClient.GetIngressRuleAsync, grpcClient.GetIngressRule, effectiveSettings.GetIngressRuleSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetIngressRule);
Modify_GetIngressRuleApiCall(ref _callGetIngressRule);
_callUpdateIngressRule = clientHelper.BuildApiCall<UpdateIngressRuleRequest, FirewallRule>(grpcClient.UpdateIngressRuleAsync, grpcClient.UpdateIngressRule, effectiveSettings.UpdateIngressRuleSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callUpdateIngressRule);
Modify_UpdateIngressRuleApiCall(ref _callUpdateIngressRule);
_callDeleteIngressRule = clientHelper.BuildApiCall<DeleteIngressRuleRequest, wkt::Empty>(grpcClient.DeleteIngressRuleAsync, grpcClient.DeleteIngressRule, effectiveSettings.DeleteIngressRuleSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callDeleteIngressRule);
Modify_DeleteIngressRuleApiCall(ref _callDeleteIngressRule);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_ListIngressRulesApiCall(ref gaxgrpc::ApiCall<ListIngressRulesRequest, ListIngressRulesResponse> call);
partial void Modify_BatchUpdateIngressRulesApiCall(ref gaxgrpc::ApiCall<BatchUpdateIngressRulesRequest, BatchUpdateIngressRulesResponse> call);
partial void Modify_CreateIngressRuleApiCall(ref gaxgrpc::ApiCall<CreateIngressRuleRequest, FirewallRule> call);
partial void Modify_GetIngressRuleApiCall(ref gaxgrpc::ApiCall<GetIngressRuleRequest, FirewallRule> call);
partial void Modify_UpdateIngressRuleApiCall(ref gaxgrpc::ApiCall<UpdateIngressRuleRequest, FirewallRule> call);
partial void Modify_DeleteIngressRuleApiCall(ref gaxgrpc::ApiCall<DeleteIngressRuleRequest, wkt::Empty> call);
partial void OnConstruction(Firewall.FirewallClient grpcClient, FirewallSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC Firewall client</summary>
public override Firewall.FirewallClient GrpcClient { get; }
partial void Modify_ListIngressRulesRequest(ref ListIngressRulesRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_BatchUpdateIngressRulesRequest(ref BatchUpdateIngressRulesRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_CreateIngressRuleRequest(ref CreateIngressRuleRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetIngressRuleRequest(ref GetIngressRuleRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateIngressRuleRequest(ref UpdateIngressRuleRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_DeleteIngressRuleRequest(ref DeleteIngressRuleRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Lists the firewall rules of an application.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable sequence of <see cref="FirewallRule"/> resources.</returns>
public override gax::PagedEnumerable<ListIngressRulesResponse, FirewallRule> ListIngressRules(ListIngressRulesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListIngressRulesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedEnumerable<ListIngressRulesRequest, ListIngressRulesResponse, FirewallRule>(_callListIngressRules, request, callSettings);
}
/// <summary>
/// Lists the firewall rules of an application.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A pageable asynchronous sequence of <see cref="FirewallRule"/> resources.</returns>
public override gax::PagedAsyncEnumerable<ListIngressRulesResponse, FirewallRule> ListIngressRulesAsync(ListIngressRulesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_ListIngressRulesRequest(ref request, ref callSettings);
return new gaxgrpc::GrpcPagedAsyncEnumerable<ListIngressRulesRequest, ListIngressRulesResponse, FirewallRule>(_callListIngressRules, request, callSettings);
}
/// <summary>
/// Replaces the entire firewall ruleset in one bulk operation. This overrides
/// and replaces the rules of an existing firewall with the new rules.
///
/// If the final rule does not match traffic with the '*' wildcard IP range,
/// then an "allow all" rule is explicitly added to the end of the list.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override BatchUpdateIngressRulesResponse BatchUpdateIngressRules(BatchUpdateIngressRulesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_BatchUpdateIngressRulesRequest(ref request, ref callSettings);
return _callBatchUpdateIngressRules.Sync(request, callSettings);
}
/// <summary>
/// Replaces the entire firewall ruleset in one bulk operation. This overrides
/// and replaces the rules of an existing firewall with the new rules.
///
/// If the final rule does not match traffic with the '*' wildcard IP range,
/// then an "allow all" rule is explicitly added to the end of the list.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<BatchUpdateIngressRulesResponse> BatchUpdateIngressRulesAsync(BatchUpdateIngressRulesRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_BatchUpdateIngressRulesRequest(ref request, ref callSettings);
return _callBatchUpdateIngressRules.Async(request, callSettings);
}
/// <summary>
/// Creates a firewall rule for the application.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override FirewallRule CreateIngressRule(CreateIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateIngressRuleRequest(ref request, ref callSettings);
return _callCreateIngressRule.Sync(request, callSettings);
}
/// <summary>
/// Creates a firewall rule for the application.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<FirewallRule> CreateIngressRuleAsync(CreateIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_CreateIngressRuleRequest(ref request, ref callSettings);
return _callCreateIngressRule.Async(request, callSettings);
}
/// <summary>
/// Gets the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override FirewallRule GetIngressRule(GetIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetIngressRuleRequest(ref request, ref callSettings);
return _callGetIngressRule.Sync(request, callSettings);
}
/// <summary>
/// Gets the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<FirewallRule> GetIngressRuleAsync(GetIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetIngressRuleRequest(ref request, ref callSettings);
return _callGetIngressRule.Async(request, callSettings);
}
/// <summary>
/// Updates the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override FirewallRule UpdateIngressRule(UpdateIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateIngressRuleRequest(ref request, ref callSettings);
return _callUpdateIngressRule.Sync(request, callSettings);
}
/// <summary>
/// Updates the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<FirewallRule> UpdateIngressRuleAsync(UpdateIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateIngressRuleRequest(ref request, ref callSettings);
return _callUpdateIngressRule.Async(request, callSettings);
}
/// <summary>
/// Deletes the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override void DeleteIngressRule(DeleteIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteIngressRuleRequest(ref request, ref callSettings);
_callDeleteIngressRule.Sync(request, callSettings);
}
/// <summary>
/// Deletes the specified firewall rule.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task DeleteIngressRuleAsync(DeleteIngressRuleRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_DeleteIngressRuleRequest(ref request, ref callSettings);
return _callDeleteIngressRule.Async(request, callSettings);
}
}
public partial class ListIngressRulesRequest : gaxgrpc::IPageRequest
{
}
public partial class ListIngressRulesResponse : gaxgrpc::IPageResponse<FirewallRule>
{
/// <summary>Returns an enumerator that iterates through the resources in this response.</summary>
public scg::IEnumerator<FirewallRule> GetEnumerator() => IngressRules.GetEnumerator();
sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator();
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using Erwine.Leonard.T.GDIPlus.Palette.ColorCaches.Common;
namespace Erwine.Leonard.T.GDIPlus.Palette.Helpers
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public class ColorModelHelper
{
#region | Constants |
private const int X = 0;
private const int Y = 1;
private const int Z = 2;
private const float Epsilon = 1E-05f;
private const float OneThird = 1.0f / 3.0f;
private const float TwoThirds = 2.0f * OneThird;
public const Double HueFactor = 1.4117647058823529411764705882353;
private static readonly float[] XYZWhite = new[] { 95.05f, 100.00f, 108.90f };
#endregion
#region | -> RGB |
private static Int32 GetColorComponent(Single v1, Single v2, Single hue)
{
Single preresult;
if (hue < 0.0f) hue++;
if (hue > 1.0f) hue--;
if ((6.0f * hue) < 1.0f)
{
preresult = v1 + (((v2 - v1) * 6.0f) * hue);
}
else if ((2.0f * hue) < 1.0f)
{
preresult = v2;
}
else if ((3.0f * hue) < 2.0f)
{
preresult = v1 + (((v2 - v1) * (TwoThirds - hue)) * 6.0f);
}
else
{
preresult = v1;
}
return Convert.ToInt32(255.0f * preresult);
}
public static Color HSBtoRGB(Single hue, Single saturation, Single brightness)
{
// initializes the default black
Int32 red = 0;
Int32 green = 0;
Int32 blue = 0;
// only if there is some brightness; otherwise leave it pitch black
if (brightness > 0.0f)
{
// if there is no saturation; leave it gray based on the brightness only
if (Math.Abs(saturation - 0.0f) < Epsilon)
{
red = green = blue = Convert.ToInt32(255.0f * brightness);
}
else // the color is more complex
{
// converts HSL cylinder to one slice (its factors)
Single factorHue = hue / 360.0f;
Single factorA = brightness < 0.5f ? brightness * (1.0f + saturation) : (brightness + saturation) - (brightness * saturation);
Single factorB = (2.0f * brightness) - factorA;
// maps HSL slice to a RGB cube
red = GetColorComponent(factorB, factorA, factorHue + OneThird);
green = GetColorComponent(factorB, factorA, factorHue);
blue = GetColorComponent(factorB, factorA, factorHue - OneThird);
}
}
Int32 argb = 255 << 24 | red << 16 | green << 8 | blue;
return Color.FromArgb(argb);
}
#endregion
#region | RGB -> |
public static void RGBtoLab(Int32 red, Int32 green, Int32 blue, out Single l, out Single a, out Single b)
{
Single x, y, z;
RGBtoXYZ(red, green, blue, out x, out y, out z);
XYZtoLab(x, y, z, out l, out a, out b);
}
public static void RGBtoXYZ(Int32 red, Int32 green, Int32 blue, out Single x, out Single y, out Single z)
{
// normalize red, green, blue values
Double redFactor = red / 255.0;
Double greenFactor = green / 255.0;
Double blueFactor = blue / 255.0;
// convert to a sRGB form
Double sRed = (redFactor > 0.04045) ? Math.Pow((redFactor + 0.055) / (1 + 0.055), 2.2) : (redFactor / 12.92);
Double sGreen = (greenFactor > 0.04045) ? Math.Pow((greenFactor + 0.055) / (1 + 0.055), 2.2) : (greenFactor / 12.92);
Double sBlue = (blueFactor > 0.04045) ? Math.Pow((blueFactor + 0.055) / (1 + 0.055), 2.2) : (blueFactor / 12.92);
// converts
x = Convert.ToSingle(sRed * 0.4124 + sGreen * 0.3576 + sBlue * 0.1805);
y = Convert.ToSingle(sRed * 0.2126 + sGreen * 0.7152 + sBlue * 0.0722);
z = Convert.ToSingle(sRed * 0.0193 + sGreen * 0.1192 + sBlue * 0.9505);
}
#endregion
#region | XYZ -> |
private static Single GetXYZValue(Single value)
{
return value > 0.008856f ? (Single)Math.Pow(value, OneThird) : (7.787f * value + 16.0f / 116.0f);
}
public static void XYZtoLab(Single x, Single y, Single z, out Single l, out Single a, out Single b)
{
l = 116.0f * GetXYZValue(y / XYZWhite[Y]) - 16.0f;
a = 500.0f * (GetXYZValue(x / XYZWhite[X]) - GetXYZValue(y / XYZWhite[Y]));
b = 200.0f * (GetXYZValue(y / XYZWhite[Y]) - GetXYZValue(z / XYZWhite[Z]));
}
#endregion
#region | Methods |
public static Int64 GetColorEuclideanDistance(ColorModel colorModel, Color requestedColor, Color realColor)
{
Single componentA, componentB, componentC;
GetColorComponents(colorModel, requestedColor, realColor, out componentA, out componentB, out componentC);
return (Int64) (componentA * componentA + componentB * componentB + componentC * componentC);
}
public static Int32 GetEuclideanDistance(Color color, ColorModel colorModel, IList<Color> palette)
{
// initializes the best difference, set it for worst possible, it can only get better
Int64 leastDistance = Int64.MaxValue;
Int32 result = 0;
for (Int32 index = 0; index < palette.Count; index++)
{
Color targetColor = palette[index];
Int64 distance = GetColorEuclideanDistance(colorModel, color, targetColor);
// if a difference is zero, we're good because it won't get better
if (distance == 0)
{
result = index;
break;
}
// if a difference is the best so far, stores it as our best candidate
if (distance < leastDistance)
{
leastDistance = distance;
result = index;
}
}
return result;
}
public static Int32 GetComponentA(ColorModel colorModel, Color color)
{
Int32 result = 0;
switch (colorModel)
{
case ColorModel.RedGreenBlue:
result = color.R;
break;
case ColorModel.HueSaturationBrightness:
result = Convert.ToInt32(color.GetHue()/HueFactor);
break;
case ColorModel.LabColorSpace:
Single l, a, b;
RGBtoLab(color.R, color.G, color.B, out l, out a, out b);
result = Convert.ToInt32(l*255.0f);
break;
}
return result;
}
public static Int32 GetComponentB(ColorModel colorModel, Color color)
{
Int32 result = 0;
switch (colorModel)
{
case ColorModel.RedGreenBlue:
result = color.G;
break;
case ColorModel.HueSaturationBrightness:
result = Convert.ToInt32(color.GetSaturation()*255);
break;
case ColorModel.LabColorSpace:
Single l, a, b;
RGBtoLab(color.R, color.G, color.B, out l, out a, out b);
result = Convert.ToInt32(a*255.0f);
break;
}
return result;
}
public static Int32 GetComponentC(ColorModel colorModel, Color color)
{
Int32 result = 0;
switch (colorModel)
{
case ColorModel.RedGreenBlue:
result = color.B;
break;
case ColorModel.HueSaturationBrightness:
result = Convert.ToInt32(color.GetBrightness()*255);
break;
case ColorModel.LabColorSpace:
Single l, a, b;
RGBtoLab(color.R, color.G, color.B, out l, out a, out b);
result = Convert.ToInt32(b*255.0f);
break;
}
return result;
}
public static void GetColorComponents(ColorModel colorModel, Color color, out Single componentA, out Single componentB, out Single componentC)
{
componentA = 0.0f;
componentB = 0.0f;
componentC = 0.0f;
switch (colorModel)
{
case ColorModel.RedGreenBlue:
componentA = color.R;
componentB = color.G;
componentC = color.B;
break;
case ColorModel.HueSaturationBrightness:
componentA = color.GetHue();
componentB = color.GetSaturation();
componentC = color.GetBrightness();
break;
case ColorModel.LabColorSpace:
RGBtoLab(color.R, color.G, color.B, out componentA, out componentB, out componentC);
break;
case ColorModel.XYZ:
RGBtoXYZ(color.R, color.G, color.B, out componentA, out componentB, out componentC);
break;
}
}
public static void GetColorComponents(ColorModel colorModel, Color color, Color targetColor, out Single componentA, out Single componentB, out Single componentC)
{
componentA = 0.0f;
componentB = 0.0f;
componentC = 0.0f;
switch (colorModel)
{
case ColorModel.RedGreenBlue:
componentA = color.R - targetColor.R;
componentB = color.G - targetColor.G;
componentC = color.B - targetColor.B;
break;
case ColorModel.HueSaturationBrightness:
componentA = color.GetHue() - targetColor.GetHue();
componentB = color.GetSaturation() - targetColor.GetSaturation();
componentC = color.GetBrightness() - targetColor.GetBrightness();
break;
case ColorModel.LabColorSpace:
Single sourceL, sourceA, sourceB;
Single targetL, targetA, targetB;
RGBtoLab(color.R, color.G, color.B, out sourceL, out sourceA, out sourceB);
RGBtoLab(targetColor.R, targetColor.G, targetColor.B, out targetL, out targetA, out targetB);
componentA = sourceL - targetL;
componentB = sourceA - targetA;
componentC = sourceB - targetB;
break;
case ColorModel.XYZ:
Single sourceX, sourceY, sourceZ;
Single targetX, targetY, targetZ;
RGBtoXYZ(color.R, color.G, color.B, out sourceX, out sourceY, out sourceZ);
RGBtoXYZ(targetColor.R, targetColor.G, targetColor.B, out targetX, out targetY, out targetZ);
componentA = sourceX - targetX;
componentB = sourceY - targetY;
componentC = sourceZ - targetZ;
break;
}
}
#endregion
}
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Security;
using Nop.Core.Domain.Stores;
using Nop.Core.Domain.Topics;
using Nop.Services.Customers;
using Nop.Services.Events;
using Nop.Services.Stores;
namespace Nop.Services.Topics
{
/// <summary>
/// Topic service
/// </summary>
public partial class TopicService : ITopicService
{
#region Constants
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : store ID
/// {1} : ignore ACL?
/// </remarks>
private const string TOPICS_ALL_KEY = "Nop.topics.all-{0}-{1}";
/// <summary>
/// Key for caching
/// </summary>
/// <remarks>
/// {0} : topic ID
/// </remarks>
private const string TOPICS_BY_ID_KEY = "Nop.topics.id-{0}";
/// <summary>
/// Key pattern to clear cache
/// </summary>
private const string TOPICS_PATTERN_KEY = "Nop.topics.";
#endregion
#region Fields
private readonly IRepository<Topic> _topicRepository;
private readonly IRepository<StoreMapping> _storeMappingRepository;
private readonly IStoreMappingService _storeMappingService;
private readonly IWorkContext _workContext;
private readonly IRepository<AclRecord> _aclRepository;
private readonly CatalogSettings _catalogSettings;
private readonly IEventPublisher _eventPublisher;
private readonly ICacheManager _cacheManager;
#endregion
#region Ctor
public TopicService(IRepository<Topic> topicRepository,
IRepository<StoreMapping> storeMappingRepository,
IStoreMappingService storeMappingService,
IWorkContext workContext,
IRepository<AclRecord> aclRepository,
CatalogSettings catalogSettings,
IEventPublisher eventPublisher,
ICacheManager cacheManager)
{
this._topicRepository = topicRepository;
this._storeMappingRepository = storeMappingRepository;
this._storeMappingService = storeMappingService;
this._workContext = workContext;
this._aclRepository = aclRepository;
this._catalogSettings = catalogSettings;
this._eventPublisher = eventPublisher;
this._cacheManager = cacheManager;
}
#endregion
#region Methods
/// <summary>
/// Deletes a topic
/// </summary>
/// <param name="topic">Topic</param>
public virtual void DeleteTopic(Topic topic)
{
if (topic == null)
throw new ArgumentNullException("topic");
_topicRepository.Delete(topic);
//cache
_cacheManager.RemoveByPattern(TOPICS_PATTERN_KEY);
//event notification
_eventPublisher.EntityDeleted(topic);
}
/// <summary>
/// Gets a topic
/// </summary>
/// <param name="topicId">The topic identifier</param>
/// <returns>Topic</returns>
public virtual Topic GetTopicById(int topicId)
{
if (topicId == 0)
return null;
string key = string.Format(TOPICS_BY_ID_KEY, topicId);
return _cacheManager.Get(key, () => _topicRepository.GetById(topicId));
}
/// <summary>
/// Gets a topic
/// </summary>
/// <param name="systemName">The topic system name</param>
/// <param name="storeId">Store identifier; pass 0 to ignore filtering by store and load the first one</param>
/// <returns>Topic</returns>
public virtual Topic GetTopicBySystemName(string systemName, int storeId = 0)
{
if (String.IsNullOrEmpty(systemName))
return null;
var query = _topicRepository.Table;
query = query.Where(t => t.SystemName == systemName);
query = query.OrderBy(t => t.Id);
var topics = query.ToList();
if (storeId > 0)
{
topics = topics.Where(x => _storeMappingService.Authorize(x, storeId)).ToList();
}
return topics.FirstOrDefault();
}
/// <summary>
/// Gets all topics
/// </summary>
/// <param name="storeId">Store identifier; pass 0 to load all records</param>
/// <param name="ignorAcl">A value indicating whether to ignore ACL rules</param>
/// <returns>Topics</returns>
public virtual IList<Topic> GetAllTopics(int storeId, bool ignorAcl = false)
{
string key = string.Format(TOPICS_ALL_KEY, storeId, ignorAcl);
return _cacheManager.Get(key, () =>
{
var query = _topicRepository.Table;
query = query.OrderBy(t => t.DisplayOrder).ThenBy(t => t.SystemName);
if ((storeId > 0 && !_catalogSettings.IgnoreStoreLimitations) ||
(!ignorAcl && !_catalogSettings.IgnoreAcl))
{
if (!ignorAcl && !_catalogSettings.IgnoreAcl)
{
//ACL (access control list)
var allowedCustomerRolesIds = _workContext.CurrentCustomer.GetCustomerRoleIds();
query = from c in query
join acl in _aclRepository.Table
on new { c1 = c.Id, c2 = "Topic" } equals new { c1 = acl.EntityId, c2 = acl.EntityName } into c_acl
from acl in c_acl.DefaultIfEmpty()
where !c.SubjectToAcl || allowedCustomerRolesIds.Contains(acl.CustomerRoleId)
select c;
}
if (!_catalogSettings.IgnoreStoreLimitations && storeId > 0)
{
//Store mapping
query = from c in query
join sm in _storeMappingRepository.Table
on new { c1 = c.Id, c2 = "Topic" } equals new { c1 = sm.EntityId, c2 = sm.EntityName } into c_sm
from sm in c_sm.DefaultIfEmpty()
where !c.LimitedToStores || storeId == sm.StoreId
select c;
}
//only distinct topics (group by ID)
query = from t in query
group t by t.Id
into tGroup
orderby tGroup.Key
select tGroup.FirstOrDefault();
query = query.OrderBy(t => t.DisplayOrder).ThenBy(t => t.SystemName);
}
return query.ToList();
});
}
/// <summary>
/// Inserts a topic
/// </summary>
/// <param name="topic">Topic</param>
public virtual void InsertTopic(Topic topic)
{
if (topic == null)
throw new ArgumentNullException("topic");
_topicRepository.Insert(topic);
//cache
_cacheManager.RemoveByPattern(TOPICS_PATTERN_KEY);
//event notification
_eventPublisher.EntityInserted(topic);
}
/// <summary>
/// Updates the topic
/// </summary>
/// <param name="topic">Topic</param>
public virtual void UpdateTopic(Topic topic)
{
if (topic == null)
throw new ArgumentNullException("topic");
_topicRepository.Update(topic);
//cache
_cacheManager.RemoveByPattern(TOPICS_PATTERN_KEY);
//event notification
_eventPublisher.EntityUpdated(topic);
}
#endregion
}
}
| |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permanentlyissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.iOS.Xcode;
using Firebase.Editor;
namespace Firebase.Analytics.Editor {
internal class AndroidAnalyticsConfig : ScriptableObject {
// Should you want to manually configure this plugin settings and not
// generate an AndroidManifest.xml set this to false.
public bool autoConfigure;
// Should you wish to disable collection of the Advertising ID in your
// Android app set this to true
public bool disableAndroidADID;
// Should you wish to disable collection of Android Secure ID set this to
// true
public bool disableAndroidSSAID;
internal static readonly string temporaryDisableKey =
"firebase_analytics_collection_enabled";
internal static readonly string permanentlyDisableKey =
"firebase_analytics_collection_deactivated";
internal static readonly string personalAdsKey =
"google_analytics_default_allow_ad_personalization_signals";
internal static readonly string adidCollectionKey =
"google_analytics_adid_collection_enabled";
internal static readonly string ssaidCollectionKey =
"google_analytics_ssaid_collection_enabled";
}
internal class IOSAnalyticsConfig : ScriptableObject {
// Should you want to manually configure this plugin settings and not
// configure XCode project automatically set this to false.
public bool autoConfigure;
// Should you wish to disable collection of the Advertising ID in your iOS
// app set this to true
public bool permanentlyDisableAppleIDFA;
// Should you wish to disable collection of the Vendor ID in your iOS app
// set this to true
public bool permanentlyDisableAppleIDFV;
internal static readonly string temporaryDisableKey =
"FIREBASE_ANALYTICS_COLLECTION_ENABLED";
internal static readonly string permanentlyDisableKey =
"FIREBASE_ANALYTICS_COLLECTION_DEACTIVATED";
internal static readonly string personalAdsKey =
"GOOGLE_ANALYTICS_DEFAULT_ALLOW_AD_PERSONALIZATION_SIGNALS";
internal static readonly string idfvCollectionKey =
"GOOGLE_ANALYTICS_IDFV_COLLECTION_ENABLED";
}
/// <summary>
/// Unity asset that represents configuration required for Firebase Analytics
/// </summary>
[ConfigAsset("analytics")]
internal class AnalyticsConfig : ScriptableObject {
// Should you want to get end user consent before collectiong data you can
// set this value to true. If you want to re-enable call
// FirebaseAnalytics.SetAnalyticsCollectionEnabled(true);
public bool temporaryDisableCollection;
// Should you want to never enable analytics in this application, set this
// to true
public bool permanentlyDisableCollection;
// Should you want to indicate that a users analytics should not be used for
// personalized advertising set this to true. If you want to re-enable call
// FirebaseAnalytics.SetUserProperty("allow_personalized_ads", "true");
public bool temporaryDisablePersonalizedAdvert;
// Android configuration
public AndroidAnalyticsConfig android = new AndroidAnalyticsConfig();
// iOS configuration
public IOSAnalyticsConfig iOS = new IOSAnalyticsConfig();
/// <summary>
/// Setup config on first use in a Unity Editor Project
/// </summary>
public void Initialize() {
android.autoConfigure = true;
iOS.autoConfigure = true;
}
}
/// <summary>
/// Class handles all utility functions for config including rendering UI and
/// modifing build projects.
/// </summary>
[InitializeOnLoad]
internal class AnalyticsConfigUtil {
/// <summary>
/// Gets called on first load and registers callbacks for UI and project
/// modification.
/// </summary>
static AnalyticsConfigUtil() {
// Common settings tab ui
ConfigWindow.RegisterTab<AnalyticsConfig>(
"Analytics", "fb_analytics",
delegate(AnalyticsConfig config) { OnGUI(config); });
ConfigWindow.RegisterSubTab<AnalyticsConfig>(
"Analytics", "Analytics - iOS",
delegate(AnalyticsConfig config) { OnGUIiOS(config); });
ConfigWindow.RegisterSubTab<AnalyticsConfig>(
"Analytics", "Analytics - Android",
delegate(AnalyticsConfig config) { OnGUIAndroid(config); });
AndroidManifestModifier.RegisterDelegate<AnalyticsConfig>(
delegate(AndroidManifestModifier info, AnalyticsConfig config) {
OnAndroidPreGen(info, config);
});
XcodeProjectModifier.RegisterDelegate<AnalyticsConfig>(
delegate(XcodeProjectModifier info, AnalyticsConfig config) {
OnXCodePostGen(info, config);
});
}
/// <summary>
/// Options to show on UI about the three states analytics can be configured
/// to run in.
/// </summary>
static readonly string[] options = new string[]{
Strings.OptionEnabled,
Strings.OptionTemporaryDisabled,
Strings.OptionPermanetlyDisabled,
};
/// <summary>
/// Callback to render common tab page
/// </summary>
/// <param name="config">Analytics config</param>
internal static void OnGUI(AnalyticsConfig config) {
string selected = Strings.OptionEnabled;
if (config.permanentlyDisableCollection == true) {
selected = Strings.OptionPermanetlyDisabled;
} else if (config.temporaryDisableCollection == true) {
selected = Strings.OptionTemporaryDisabled;
}
selected = FirebaseGUILayout.Popup(Strings.AnalyticsCollection, selected,
options);
if (selected == Strings.OptionTemporaryDisabled) {
config.permanentlyDisableCollection = false;
config.temporaryDisableCollection = true;
} else if (selected == Strings.OptionPermanetlyDisabled) {
config.permanentlyDisableCollection = true;
config.temporaryDisableCollection = false;
} else // (selected == Strings.OptionEnabled)
{
config.permanentlyDisableCollection = false;
config.temporaryDisableCollection = false;
}
SerializedObject so = new SerializedObject(config);
FirebaseGUILayout.PropertyField(so, "temporaryDisablePersonalizedAdvert",
Strings.DisablePersonalAds,
Strings.DisablePersonalAdsDescription);
so.ApplyModifiedProperties();
}
/// <summary>
/// Callback to render iOS sub tab page
/// </summary>
/// <param name="config">Messaging config</param>
internal static void OnGUIiOS(AnalyticsConfig config) {
SerializedObject so = new SerializedObject(config.iOS);
FirebaseGUILayout.PropertyField(so, "autoConfigure",
Strings.AutoConfigureIOS,
Strings.AutoConfigureIOSDescription);
FirebaseGUILayout.PropertyField(
so, "permanentlyDisableAppleIDFA",
Strings.PermanentlyDisableAppleIDFA,
Strings.PermanentlyDisableAppleIDFADescription);
FirebaseGUILayout.PropertyField(
so, "permanentlyDisableAppleIDFV",
Strings.PermanentlyDisableAppleIDFV,
Strings.PermanentlyDisableAppleIDFVDescription);
so.ApplyModifiedProperties();
}
/// <summary>
/// Callback to render Android sub tab page
/// </summary>
/// <param name="config">Messaging config</param>
internal static void OnGUIAndroid(AnalyticsConfig config) {
SerializedObject so = new SerializedObject(config.android);
FirebaseGUILayout.PropertyField(so, "autoConfigure",
Strings.AutoConfigureAndroid,
Strings.AutoConfigureAndroidDescription);
FirebaseGUILayout.PropertyField(
so, "disableAndroidADID", Strings.PermanentlyDisableAndroidADID,
Strings.PermanentlyDisableAndroidADIDDescription);
FirebaseGUILayout.PropertyField(
so, "disableAndroidSSAID", Strings.PermanentlyDisableAndroidSSAID,
Strings.PermanentlyDisableAndroidSSAIDDescription);
so.ApplyModifiedProperties();
}
/// <summary>
/// Callback to setup android manifest file
/// </summary>
/// <param name="info">Android manifest info</param>
/// <param name="config">Analytics config</param>
internal static void OnAndroidPreGen(AndroidManifestModifier info,
AnalyticsConfig config) {
if (config.android.autoConfigure == false) {
return;
}
info.SetMetaDataValue(AndroidAnalyticsConfig.temporaryDisableKey,
config.temporaryDisableCollection == false);
info.SetMetaDataValue(AndroidAnalyticsConfig.permanentlyDisableKey,
config.permanentlyDisableCollection == false);
info.SetMetaDataValue(AndroidAnalyticsConfig.personalAdsKey,
config.temporaryDisablePersonalizedAdvert == false);
info.SetMetaDataValue(AndroidAnalyticsConfig.adidCollectionKey,
config.android.disableAndroidADID == false);
info.SetMetaDataValue(AndroidAnalyticsConfig.ssaidCollectionKey,
config.android.disableAndroidSSAID == false);
}
/// <summary>
/// Callback to setup Xcode project settings
/// </summary>
/// <param name="info">Xcode project info</param>
/// <param name="config">Analytics config</param>
internal static void OnXCodePostGen(XcodeProjectModifier info,
AnalyticsConfig config) {
if (config.iOS.autoConfigure == false) {
return;
}
var projectInfo = (PlistElementDict)info.ProjectInfo;
projectInfo.SetBoolean(IOSAnalyticsConfig.temporaryDisableKey,
config.temporaryDisableCollection == false);
projectInfo.SetBoolean(IOSAnalyticsConfig.permanentlyDisableKey,
config.permanentlyDisableCollection);
projectInfo.SetBoolean(
IOSAnalyticsConfig.personalAdsKey,
config.temporaryDisablePersonalizedAdvert == false);
projectInfo.SetBoolean(
IOSAnalyticsConfig.idfvCollectionKey,
config.iOS.permanentlyDisableAppleIDFV == false);
if (config.iOS.permanentlyDisableAppleIDFA == true) {
((PBXProject)info.Project).RemoveFrameworkFromProject(info.TargetGUID,
"AdSupport.framework");
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/bigtable/admin/v2/bigtable_table_admin.proto
// Original file comments:
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#region Designer generated code
using System;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core;
namespace Google.Bigtable.Admin.V2 {
/// <summary>
/// Service for creating, configuring, and deleting Cloud Bigtable tables.
/// Provides access to the table schemas only, not the data stored within
/// the tables.
/// </summary>
public static class BigtableTableAdmin
{
static readonly string __ServiceName = "google.bigtable.admin.v2.BigtableTableAdmin";
static readonly Marshaller<global::Google.Bigtable.Admin.V2.CreateTableRequest> __Marshaller_CreateTableRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.CreateTableRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Bigtable.Admin.V2.Table> __Marshaller_Table = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.Table.Parser.ParseFrom);
static readonly Marshaller<global::Google.Bigtable.Admin.V2.ListTablesRequest> __Marshaller_ListTablesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.ListTablesRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Bigtable.Admin.V2.ListTablesResponse> __Marshaller_ListTablesResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.ListTablesResponse.Parser.ParseFrom);
static readonly Marshaller<global::Google.Bigtable.Admin.V2.GetTableRequest> __Marshaller_GetTableRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.GetTableRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Bigtable.Admin.V2.DeleteTableRequest> __Marshaller_DeleteTableRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.DeleteTableRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom);
static readonly Marshaller<global::Google.Bigtable.Admin.V2.ModifyColumnFamiliesRequest> __Marshaller_ModifyColumnFamiliesRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.ModifyColumnFamiliesRequest.Parser.ParseFrom);
static readonly Marshaller<global::Google.Bigtable.Admin.V2.DropRowRangeRequest> __Marshaller_DropRowRangeRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Bigtable.Admin.V2.DropRowRangeRequest.Parser.ParseFrom);
static readonly Method<global::Google.Bigtable.Admin.V2.CreateTableRequest, global::Google.Bigtable.Admin.V2.Table> __Method_CreateTable = new Method<global::Google.Bigtable.Admin.V2.CreateTableRequest, global::Google.Bigtable.Admin.V2.Table>(
MethodType.Unary,
__ServiceName,
"CreateTable",
__Marshaller_CreateTableRequest,
__Marshaller_Table);
static readonly Method<global::Google.Bigtable.Admin.V2.ListTablesRequest, global::Google.Bigtable.Admin.V2.ListTablesResponse> __Method_ListTables = new Method<global::Google.Bigtable.Admin.V2.ListTablesRequest, global::Google.Bigtable.Admin.V2.ListTablesResponse>(
MethodType.Unary,
__ServiceName,
"ListTables",
__Marshaller_ListTablesRequest,
__Marshaller_ListTablesResponse);
static readonly Method<global::Google.Bigtable.Admin.V2.GetTableRequest, global::Google.Bigtable.Admin.V2.Table> __Method_GetTable = new Method<global::Google.Bigtable.Admin.V2.GetTableRequest, global::Google.Bigtable.Admin.V2.Table>(
MethodType.Unary,
__ServiceName,
"GetTable",
__Marshaller_GetTableRequest,
__Marshaller_Table);
static readonly Method<global::Google.Bigtable.Admin.V2.DeleteTableRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteTable = new Method<global::Google.Bigtable.Admin.V2.DeleteTableRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
MethodType.Unary,
__ServiceName,
"DeleteTable",
__Marshaller_DeleteTableRequest,
__Marshaller_Empty);
static readonly Method<global::Google.Bigtable.Admin.V2.ModifyColumnFamiliesRequest, global::Google.Bigtable.Admin.V2.Table> __Method_ModifyColumnFamilies = new Method<global::Google.Bigtable.Admin.V2.ModifyColumnFamiliesRequest, global::Google.Bigtable.Admin.V2.Table>(
MethodType.Unary,
__ServiceName,
"ModifyColumnFamilies",
__Marshaller_ModifyColumnFamiliesRequest,
__Marshaller_Table);
static readonly Method<global::Google.Bigtable.Admin.V2.DropRowRangeRequest, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DropRowRange = new Method<global::Google.Bigtable.Admin.V2.DropRowRangeRequest, global::Google.Protobuf.WellKnownTypes.Empty>(
MethodType.Unary,
__ServiceName,
"DropRowRange",
__Marshaller_DropRowRangeRequest,
__Marshaller_Empty);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::Google.Bigtable.Admin.V2.BigtableTableAdminReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of BigtableTableAdmin</summary>
public abstract class BigtableTableAdminBase
{
/// <summary>
/// Creates a new table in the specified instance.
/// The table can be created with a full set of initial column families,
/// specified in the request.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Bigtable.Admin.V2.Table> CreateTable(global::Google.Bigtable.Admin.V2.CreateTableRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Lists all tables served from a specified instance.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Bigtable.Admin.V2.ListTablesResponse> ListTables(global::Google.Bigtable.Admin.V2.ListTablesRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Gets metadata information about the specified table.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Bigtable.Admin.V2.Table> GetTable(global::Google.Bigtable.Admin.V2.GetTableRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Permanently deletes a specified table and all of its data.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteTable(global::Google.Bigtable.Admin.V2.DeleteTableRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Atomically performs a series of column family modifications
/// on the specified table.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Bigtable.Admin.V2.Table> ModifyColumnFamilies(global::Google.Bigtable.Admin.V2.ModifyColumnFamiliesRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
/// <summary>
/// Permanently drop/delete a row range from a specified table. The request can
/// specify whether to delete all rows in a table, or only those that match a
/// particular prefix.
/// </summary>
public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DropRowRange(global::Google.Bigtable.Admin.V2.DropRowRangeRequest request, ServerCallContext context)
{
throw new RpcException(new Status(StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for BigtableTableAdmin</summary>
public class BigtableTableAdminClient : ClientBase<BigtableTableAdminClient>
{
/// <summary>Creates a new client for BigtableTableAdmin</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public BigtableTableAdminClient(Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for BigtableTableAdmin that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public BigtableTableAdminClient(CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected BigtableTableAdminClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected BigtableTableAdminClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
/// <summary>
/// Creates a new table in the specified instance.
/// The table can be created with a full set of initial column families,
/// specified in the request.
/// </summary>
public virtual global::Google.Bigtable.Admin.V2.Table CreateTable(global::Google.Bigtable.Admin.V2.CreateTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateTable(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates a new table in the specified instance.
/// The table can be created with a full set of initial column families,
/// specified in the request.
/// </summary>
public virtual global::Google.Bigtable.Admin.V2.Table CreateTable(global::Google.Bigtable.Admin.V2.CreateTableRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_CreateTable, null, options, request);
}
/// <summary>
/// Creates a new table in the specified instance.
/// The table can be created with a full set of initial column families,
/// specified in the request.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.Table> CreateTableAsync(global::Google.Bigtable.Admin.V2.CreateTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return CreateTableAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Creates a new table in the specified instance.
/// The table can be created with a full set of initial column families,
/// specified in the request.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.Table> CreateTableAsync(global::Google.Bigtable.Admin.V2.CreateTableRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_CreateTable, null, options, request);
}
/// <summary>
/// Lists all tables served from a specified instance.
/// </summary>
public virtual global::Google.Bigtable.Admin.V2.ListTablesResponse ListTables(global::Google.Bigtable.Admin.V2.ListTablesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListTables(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists all tables served from a specified instance.
/// </summary>
public virtual global::Google.Bigtable.Admin.V2.ListTablesResponse ListTables(global::Google.Bigtable.Admin.V2.ListTablesRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ListTables, null, options, request);
}
/// <summary>
/// Lists all tables served from a specified instance.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.ListTablesResponse> ListTablesAsync(global::Google.Bigtable.Admin.V2.ListTablesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ListTablesAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Lists all tables served from a specified instance.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.ListTablesResponse> ListTablesAsync(global::Google.Bigtable.Admin.V2.ListTablesRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ListTables, null, options, request);
}
/// <summary>
/// Gets metadata information about the specified table.
/// </summary>
public virtual global::Google.Bigtable.Admin.V2.Table GetTable(global::Google.Bigtable.Admin.V2.GetTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetTable(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets metadata information about the specified table.
/// </summary>
public virtual global::Google.Bigtable.Admin.V2.Table GetTable(global::Google.Bigtable.Admin.V2.GetTableRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_GetTable, null, options, request);
}
/// <summary>
/// Gets metadata information about the specified table.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.Table> GetTableAsync(global::Google.Bigtable.Admin.V2.GetTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return GetTableAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Gets metadata information about the specified table.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.Table> GetTableAsync(global::Google.Bigtable.Admin.V2.GetTableRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_GetTable, null, options, request);
}
/// <summary>
/// Permanently deletes a specified table and all of its data.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteTable(global::Google.Bigtable.Admin.V2.DeleteTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteTable(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Permanently deletes a specified table and all of its data.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteTable(global::Google.Bigtable.Admin.V2.DeleteTableRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_DeleteTable, null, options, request);
}
/// <summary>
/// Permanently deletes a specified table and all of its data.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteTableAsync(global::Google.Bigtable.Admin.V2.DeleteTableRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DeleteTableAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Permanently deletes a specified table and all of its data.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteTableAsync(global::Google.Bigtable.Admin.V2.DeleteTableRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_DeleteTable, null, options, request);
}
/// <summary>
/// Atomically performs a series of column family modifications
/// on the specified table.
/// </summary>
public virtual global::Google.Bigtable.Admin.V2.Table ModifyColumnFamilies(global::Google.Bigtable.Admin.V2.ModifyColumnFamiliesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ModifyColumnFamilies(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Atomically performs a series of column family modifications
/// on the specified table.
/// </summary>
public virtual global::Google.Bigtable.Admin.V2.Table ModifyColumnFamilies(global::Google.Bigtable.Admin.V2.ModifyColumnFamiliesRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_ModifyColumnFamilies, null, options, request);
}
/// <summary>
/// Atomically performs a series of column family modifications
/// on the specified table.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.Table> ModifyColumnFamiliesAsync(global::Google.Bigtable.Admin.V2.ModifyColumnFamiliesRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return ModifyColumnFamiliesAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Atomically performs a series of column family modifications
/// on the specified table.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Bigtable.Admin.V2.Table> ModifyColumnFamiliesAsync(global::Google.Bigtable.Admin.V2.ModifyColumnFamiliesRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_ModifyColumnFamilies, null, options, request);
}
/// <summary>
/// Permanently drop/delete a row range from a specified table. The request can
/// specify whether to delete all rows in a table, or only those that match a
/// particular prefix.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DropRowRange(global::Google.Bigtable.Admin.V2.DropRowRangeRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DropRowRange(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Permanently drop/delete a row range from a specified table. The request can
/// specify whether to delete all rows in a table, or only those that match a
/// particular prefix.
/// </summary>
public virtual global::Google.Protobuf.WellKnownTypes.Empty DropRowRange(global::Google.Bigtable.Admin.V2.DropRowRangeRequest request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_DropRowRange, null, options, request);
}
/// <summary>
/// Permanently drop/delete a row range from a specified table. The request can
/// specify whether to delete all rows in a table, or only those that match a
/// particular prefix.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DropRowRangeAsync(global::Google.Bigtable.Admin.V2.DropRowRangeRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken))
{
return DropRowRangeAsync(request, new CallOptions(headers, deadline, cancellationToken));
}
/// <summary>
/// Permanently drop/delete a row range from a specified table. The request can
/// specify whether to delete all rows in a table, or only those that match a
/// particular prefix.
/// </summary>
public virtual AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DropRowRangeAsync(global::Google.Bigtable.Admin.V2.DropRowRangeRequest request, CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_DropRowRange, null, options, request);
}
protected override BigtableTableAdminClient NewInstance(ClientBaseConfiguration configuration)
{
return new BigtableTableAdminClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
public static ServerServiceDefinition BindService(BigtableTableAdminBase serviceImpl)
{
return ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_CreateTable, serviceImpl.CreateTable)
.AddMethod(__Method_ListTables, serviceImpl.ListTables)
.AddMethod(__Method_GetTable, serviceImpl.GetTable)
.AddMethod(__Method_DeleteTable, serviceImpl.DeleteTable)
.AddMethod(__Method_ModifyColumnFamilies, serviceImpl.ModifyColumnFamilies)
.AddMethod(__Method_DropRowRange, serviceImpl.DropRowRange).Build();
}
}
}
#endregion
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Messaging;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Serialization;
using Orleans.Streams;
namespace Orleans
{
internal class OutsideRuntimeClient : IRuntimeClient, IDisposable
{
internal static bool TestOnlyThrowExceptionDuringInit { get; set; }
private readonly Logger logger;
private readonly Logger appLogger;
private readonly ClientConfiguration config;
private readonly ConcurrentDictionary<CorrelationId, CallbackData> callbacks;
private readonly ConcurrentDictionary<GuidId, LocalObjectData> localObjects;
private readonly ProxiedMessageCenter transport;
private bool listenForMessages;
private CancellationTokenSource listeningCts;
private bool firstMessageReceived;
private readonly ClientProviderRuntime clientProviderRuntime;
private readonly StatisticsProviderManager statisticsProviderManager;
internal ClientStatisticsManager ClientStatistics;
private GrainId clientId;
private readonly GrainId handshakeClientId;
private IGrainTypeResolver grainInterfaceMap;
private readonly ThreadTrackingStatistic incomingMessagesThreadTimeTracking;
private readonly Func<Message, bool> tryResendMessage;
private readonly Action<Message> unregisterCallback;
// initTimeout used to be AzureTableDefaultPolicies.TableCreationTimeout, which was 3 min
private static readonly TimeSpan initTimeout = TimeSpan.FromMinutes(1);
private static readonly TimeSpan resetTimeout = TimeSpan.FromMinutes(1);
private const string BARS = "----------";
private readonly GrainFactory grainFactory;
public IInternalGrainFactory InternalGrainFactory
{
get { return grainFactory; }
}
/// <summary>
/// Response timeout.
/// </summary>
private TimeSpan responseTimeout;
private static readonly Object staticLock = new Object();
private TypeMetadataCache typeCache;
private readonly AssemblyProcessor assemblyProcessor;
Logger IRuntimeClient.AppLogger
{
get { return appLogger; }
}
public ActivationAddress CurrentActivationAddress
{
get;
private set;
}
public SiloAddress CurrentSilo
{
get { return CurrentActivationAddress.Silo; }
}
public string Identity
{
get { return CurrentActivationAddress.ToString(); }
}
internal IList<Uri> Gateways
{
get
{
return transport.GatewayManager.ListProvider.GetGateways().GetResult();
}
}
public IStreamProviderManager CurrentStreamProviderManager { get; private set; }
public IStreamProviderRuntime CurrentStreamProviderRuntime
{
get { return clientProviderRuntime; }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "MessageCenter is IDisposable but cannot call Dispose yet as it lives past the end of this method call.")]
public OutsideRuntimeClient(ClientConfiguration cfg, bool secondary = false)
{
this.typeCache = new TypeMetadataCache();
this.assemblyProcessor = new AssemblyProcessor(this.typeCache);
this.grainFactory = new GrainFactory(this, this.typeCache);
if (cfg == null)
{
Console.WriteLine("An attempt to create an OutsideRuntimeClient with null ClientConfiguration object.");
throw new ArgumentException("OutsideRuntimeClient was attempted to be created with null ClientConfiguration object.", "cfg");
}
this.config = cfg;
if (!LogManager.IsInitialized) LogManager.Initialize(config);
StatisticsCollector.Initialize(config);
SerializationManager.Initialize(cfg.SerializationProviders, cfg.FallbackSerializationProvider);
this.assemblyProcessor.Initialize();
logger = LogManager.GetLogger("OutsideRuntimeClient", LoggerType.Runtime);
appLogger = LogManager.GetLogger("Application", LoggerType.Application);
BufferPool.InitGlobalBufferPool(config);
this.handshakeClientId = GrainId.NewClientId();
tryResendMessage = TryResendMessage;
unregisterCallback = msg => UnRegisterCallback(msg.Id);
try
{
LoadAdditionalAssemblies();
callbacks = new ConcurrentDictionary<CorrelationId, CallbackData>();
localObjects = new ConcurrentDictionary<GuidId, LocalObjectData>();
if (!secondary)
{
UnobservedExceptionsHandlerClass.SetUnobservedExceptionHandler(UnhandledException);
}
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload;
// Ensure SerializationManager static constructor is called before AssemblyLoad event is invoked
SerializationManager.GetDeserializer(typeof(String));
clientProviderRuntime = new ClientProviderRuntime(grainFactory, null);
statisticsProviderManager = new StatisticsProviderManager("Statistics", clientProviderRuntime);
var statsProviderName = statisticsProviderManager.LoadProvider(config.ProviderConfigurations)
.WaitForResultWithThrow(initTimeout);
if (statsProviderName != null)
{
config.StatisticsProviderName = statsProviderName;
}
responseTimeout = Debugger.IsAttached ? Constants.DEFAULT_RESPONSE_TIMEOUT : config.ResponseTimeout;
var localAddress = ClusterConfiguration.GetLocalIPAddress(config.PreferredFamily, config.NetInterface);
// Client init / sign-on message
logger.Info(ErrorCode.ClientInitializing, string.Format(
"{0} Initializing OutsideRuntimeClient on {1} at {2} Client Id = {3} {0}",
BARS, config.DNSHostName, localAddress, handshakeClientId));
string startMsg = string.Format("{0} Starting OutsideRuntimeClient with runtime Version='{1}' in AppDomain={2}",
BARS, RuntimeVersion.Current, PrintAppDomainDetails());
startMsg = string.Format("{0} Config= " + Environment.NewLine + " {1}", startMsg, config);
logger.Info(ErrorCode.ClientStarting, startMsg);
if (TestOnlyThrowExceptionDuringInit)
{
throw new InvalidOperationException("TestOnlyThrowExceptionDuringInit");
}
config.CheckGatewayProviderSettings();
var generation = -SiloAddress.AllocateNewGeneration(); // Client generations are negative
var gatewayListProvider = GatewayProviderFactory.CreateGatewayListProvider(config)
.WithTimeout(initTimeout).Result;
transport = new ProxiedMessageCenter(config, localAddress, generation, handshakeClientId, gatewayListProvider);
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking = new ThreadTrackingStatistic("ClientReceiver");
}
}
catch (Exception exc)
{
if (logger != null) logger.Error(ErrorCode.Runtime_Error_100319, "OutsideRuntimeClient constructor failed.", exc);
ConstructorReset();
throw;
}
}
private void StreamingInitialize()
{
var implicitSubscriberTable = transport.GetImplicitStreamSubscriberTable(grainFactory).Result;
clientProviderRuntime.StreamingInitialize(implicitSubscriberTable);
var streamProviderManager = new Streams.StreamProviderManager();
streamProviderManager
.LoadStreamProviders(
this.config.ProviderConfigurations,
clientProviderRuntime)
.Wait();
CurrentStreamProviderManager = streamProviderManager;
}
private void LoadAdditionalAssemblies()
{
#if !NETSTANDARD_TODO
var logger = LogManager.GetLogger("AssemblyLoader.Client", LoggerType.Runtime);
var directories =
new Dictionary<string, SearchOption>
{
{
Path.GetDirectoryName(typeof(OutsideRuntimeClient).GetTypeInfo().Assembly.Location),
SearchOption.AllDirectories
}
};
var excludeCriteria =
new AssemblyLoaderPathNameCriterion[]
{
AssemblyLoaderCriteria.ExcludeResourceAssemblies,
AssemblyLoaderCriteria.ExcludeSystemBinaries()
};
var loadProvidersCriteria =
new AssemblyLoaderReflectionCriterion[]
{
AssemblyLoaderCriteria.LoadTypesAssignableFrom(typeof(IProvider))
};
this.assemblyProcessor.Initialize();
AssemblyLoader.LoadAssemblies(directories, excludeCriteria, loadProvidersCriteria, logger);
#endif
}
private void UnhandledException(ISchedulingContext context, Exception exception)
{
logger.Error(ErrorCode.Runtime_Error_100007, String.Format("OutsideRuntimeClient caught an UnobservedException."), exception);
logger.Assert(ErrorCode.Runtime_Error_100008, context == null, "context should be not null only inside OrleansRuntime and not on the client.");
}
public void Start()
{
lock (staticLock)
{
if (RuntimeClient.Current != null)
throw new InvalidOperationException("Can only have one RuntimeClient per AppDomain");
RuntimeClient.Current = this;
}
StartInternal();
logger.Info(ErrorCode.ProxyClient_StartDone, "{0} Started OutsideRuntimeClient with Global Client ID: {1}", BARS, CurrentActivationAddress.ToString() + ", client GUID ID: " + handshakeClientId);
}
// used for testing to (carefully!) allow two clients in the same process
internal void StartInternal()
{
transport.Start();
LogManager.MyIPEndPoint = transport.MyAddress.Endpoint; // transport.MyAddress is only set after transport is Started.
CurrentActivationAddress = ActivationAddress.NewActivationAddress(transport.MyAddress, handshakeClientId);
ClientStatistics = new ClientStatisticsManager(config);
listeningCts = new CancellationTokenSource();
var ct = listeningCts.Token;
listenForMessages = true;
// Keeping this thread handling it very simple for now. Just queue task on thread pool.
Task.Factory.StartNew(() =>
{
try
{
RunClientMessagePump(ct);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Runtime_Error_100326, "RunClientMessagePump has thrown exception", exc);
}
}
);
grainInterfaceMap = transport.GetTypeCodeMap(grainFactory).Result;
ClientStatistics.Start(statisticsProviderManager, transport, clientId)
.WaitWithThrow(initTimeout);
StreamingInitialize();
}
private void RunClientMessagePump(CancellationToken ct)
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStartExecution();
}
while (listenForMessages)
{
var message = transport.WaitMessage(Message.Categories.Application, ct);
if (message == null) // if wait was cancelled
break;
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStartProcessing();
}
#endif
// when we receive the first message, we update the
// clientId for this client because it may have been modified to
// include the cluster name
if (!firstMessageReceived)
{
firstMessageReceived = true;
if (!handshakeClientId.Equals(message.TargetGrain))
{
clientId = message.TargetGrain;
transport.UpdateClientId(clientId);
CurrentActivationAddress = ActivationAddress.GetAddress(transport.MyAddress, clientId, CurrentActivationAddress.Activation);
}
else
{
clientId = handshakeClientId;
}
}
switch (message.Direction)
{
case Message.Directions.Response:
{
ReceiveResponse(message);
break;
}
case Message.Directions.OneWay:
case Message.Directions.Request:
{
this.DispatchToLocalObject(message);
break;
}
default:
logger.Error(ErrorCode.Runtime_Error_100327, String.Format("Message not supported: {0}.", message));
break;
}
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopProcessing();
incomingMessagesThreadTimeTracking.IncrementNumberOfProcessed();
}
#endif
}
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopExecution();
}
}
private void DispatchToLocalObject(Message message)
{
LocalObjectData objectData;
GuidId observerId = message.TargetObserverId;
if (observerId == null)
{
logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound_2,
String.Format("Did not find TargetObserverId header in the message = {0}. A request message to a client is expected to have an observerId.", message));
return;
}
if (localObjects.TryGetValue(observerId, out objectData))
this.InvokeLocalObjectAsync(objectData, message);
else
{
logger.Error(
ErrorCode.ProxyClient_OGC_TargetNotFound,
String.Format(
"Unexpected target grain in request: {0}. Message={1}",
message.TargetGrain,
message));
}
}
private void InvokeLocalObjectAsync(LocalObjectData objectData, Message message)
{
var obj = (IAddressable)objectData.LocalObject.Target;
if (obj == null)
{
//// Remove from the dictionary record for the garbage collected object? But now we won't be able to detect invalid dispatch IDs anymore.
logger.Warn(ErrorCode.Runtime_Error_100162,
String.Format("Object associated with Observer ID {0} has been garbage collected. Deleting object reference and unregistering it. Message = {1}", objectData.ObserverId, message));
LocalObjectData ignore;
// Try to remove. If it's not there, we don't care.
localObjects.TryRemove(objectData.ObserverId, out ignore);
return;
}
bool start;
lock (objectData.Messages)
{
objectData.Messages.Enqueue(message);
start = !objectData.Running;
objectData.Running = true;
}
if (logger.IsVerbose) logger.Verbose("InvokeLocalObjectAsync {0} start {1}", message, start);
if (start)
{
// we use Task.Run() to ensure that the message pump operates asynchronously
// with respect to the current thread. see
// http://channel9.msdn.com/Events/TechEd/Europe/2013/DEV-B317#fbid=aIWUq0ssW74
// at position 54:45.
//
// according to the information posted at:
// http://stackoverflow.com/questions/12245935/is-task-factory-startnew-guaranteed-to-use-another-thread-than-the-calling-thr
// this idiom is dependent upon the a TaskScheduler not implementing the
// override QueueTask as task inlining (as opposed to queueing). this seems
// implausible to the author, since none of the .NET schedulers do this and
// it is considered bad form (the OrleansTaskScheduler does not do this).
//
// if, for some reason this doesn't hold true, we can guarantee what we
// want by passing a placeholder continuation token into Task.StartNew()
// instead. i.e.:
//
// return Task.StartNew(() => ..., new CancellationToken());
Func<Task> asyncFunc =
async () =>
await this.LocalObjectMessagePumpAsync(objectData);
Task.Run(asyncFunc).Ignore();
}
}
private async Task LocalObjectMessagePumpAsync(LocalObjectData objectData)
{
while (true)
{
try
{
Message message;
lock (objectData.Messages)
{
if (objectData.Messages.Count == 0)
{
objectData.Running = false;
break;
}
message = objectData.Messages.Dequeue();
}
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Invoke))
continue;
RequestContext.Import(message.RequestContextData);
var request = (InvokeMethodRequest)message.BodyObject;
var targetOb = (IAddressable)objectData.LocalObject.Target;
object resultObject = null;
Exception caught = null;
try
{
// exceptions thrown within this scope are not considered to be thrown from user code
// and not from runtime code.
var resultPromise = objectData.Invoker.Invoke(targetOb, request);
if (resultPromise != null) // it will be null for one way messages
{
resultObject = await resultPromise;
}
}
catch (Exception exc)
{
// the exception needs to be reported in the log or propagated back to the caller.
caught = exc;
}
if (caught != null)
this.ReportException(message, caught);
else if (message.Direction != Message.Directions.OneWay)
await this.SendResponseAsync(message, resultObject);
}
catch (Exception)
{
// ignore, keep looping.
}
}
}
private static bool ExpireMessageIfExpired(Message message, MessagingStatisticsGroup.Phase phase)
{
if (message.IsExpired)
{
message.DropExpiredMessage(phase);
return true;
}
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private Task
SendResponseAsync(
Message message,
object resultObject)
{
if (ExpireMessageIfExpired(message, MessagingStatisticsGroup.Phase.Respond))
return TaskDone.Done;
object deepCopy = null;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = SerializationManager.DeepCopy(resultObject);
}
catch (Exception exc2)
{
SendResponse(message, Response.ExceptionResponse(exc2));
logger.Warn(
ErrorCode.ProxyClient_OGC_SendResponseFailed,
"Exception trying to send a response.", exc2);
return TaskDone.Done;
}
// the deep-copy succeeded.
SendResponse(message, new Response(deepCopy));
return TaskDone.Done;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void ReportException(Message message, Exception exception)
{
var request = (InvokeMethodRequest)message.BodyObject;
switch (message.Direction)
{
default:
throw new InvalidOperationException();
case Message.Directions.OneWay:
{
logger.Error(
ErrorCode.ProxyClient_OGC_UnhandledExceptionInOneWayInvoke,
String.Format(
"Exception during invocation of notification method {0}, interface {1}. Ignoring exception because this is a one way request.",
request.MethodId,
request.InterfaceId),
exception);
break;
}
case Message.Directions.Request:
{
Exception deepCopy = null;
try
{
// we're expected to notify the caller if the deep copy failed.
deepCopy = (Exception)SerializationManager.DeepCopy(exception);
}
catch (Exception ex2)
{
SendResponse(message, Response.ExceptionResponse(ex2));
logger.Warn(
ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed,
"Exception trying to send an exception response", ex2);
return;
}
// the deep-copy succeeded.
var response = Response.ExceptionResponse(deepCopy);
SendResponse(message, response);
break;
}
}
}
private void SendResponse(Message request, Response response)
{
var message = request.CreateResponseMessage();
message.BodyObject = response;
transport.SendMessage(message);
}
/// <summary>
/// For testing only.
/// </summary>
public void Disconnect()
{
transport.Disconnect();
}
/// <summary>
/// For testing only.
/// </summary>
public void Reconnect()
{
transport.Reconnect();
}
#region Implementation of IRuntimeClient
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "CallbackData is IDisposable but instances exist beyond lifetime of this method so cannot Dispose yet.")]
public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null)
{
var message = Message.CreateMessage(request, options);
SendRequestMessage(target, message, context, callback, debugContext, options, genericArguments);
}
private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null)
{
var targetGrainId = target.GrainId;
var oneWay = (options & InvokeMethodOptions.OneWay) != 0;
message.SendingGrain = CurrentActivationAddress.Grain;
message.SendingActivation = CurrentActivationAddress.Activation;
message.TargetGrain = targetGrainId;
if (!String.IsNullOrEmpty(genericArguments))
message.GenericGrainType = genericArguments;
if (targetGrainId.IsSystemTarget)
{
// If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo
message.TargetSilo = target.SystemTargetSilo;
if (target.SystemTargetSilo != null)
{
message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, target.SystemTargetSilo);
}
}
// Client sending messages to another client (observer). Yes, we support that.
if (target.IsObserverReference)
{
message.TargetObserverId = target.ObserverId;
}
if (debugContext != null)
{
message.DebugContext = debugContext;
}
if (message.IsExpirableMessage(config))
{
// don't set expiration for system target messages.
message.Expiration = DateTime.UtcNow + responseTimeout + Constants.MAXIMUM_CLOCK_SKEW;
}
if (!oneWay)
{
var callbackData = new CallbackData(
callback,
tryResendMessage,
context,
message,
unregisterCallback,
config);
callbacks.TryAdd(message.Id, callbackData);
callbackData.StartTimer(responseTimeout);
}
if (logger.IsVerbose2) logger.Verbose2("Send {0}", message);
transport.SendMessage(message);
}
private bool TryResendMessage(Message message)
{
if (!message.MayResend(config))
{
return false;
}
if (logger.IsVerbose) logger.Verbose("Resend {0}", message);
message.ResendCount = message.ResendCount + 1;
message.TargetHistory = message.GetTargetHistory();
if (!message.TargetGrain.IsSystemTarget)
{
message.TargetActivation = null;
message.TargetSilo = null;
message.ClearTargetAddress();
}
transport.SendMessage(message);
return true;
}
public void ReceiveResponse(Message response)
{
if (logger.IsVerbose2) logger.Verbose2("Received {0}", response);
// ignore duplicate requests
if (response.Result == Message.ResponseTypes.Rejection && response.RejectionType == Message.RejectionTypes.DuplicateRequest)
return;
CallbackData callbackData;
var found = callbacks.TryGetValue(response.Id, out callbackData);
if (found)
{
// We need to import the RequestContext here as well.
// Unfortunately, it is not enough, since CallContext.LogicalGetData will not flow "up" from task completion source into the resolved task.
// RequestContext.Import(response.RequestContextData);
callbackData.DoCallback(response);
}
else
{
logger.Warn(ErrorCode.Runtime_Error_100011, "No callback for response message: " + response);
}
}
private void UnRegisterCallback(CorrelationId id)
{
CallbackData ignore;
callbacks.TryRemove(id, out ignore);
}
public void Reset(bool cleanup)
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.Reset(): client Id " + clientId);
}
});
Utils.SafeExecute(() =>
{
if (clientProviderRuntime != null)
{
clientProviderRuntime.Reset(cleanup).WaitWithThrow(resetTimeout);
}
}, logger, "Client.clientProviderRuntime.Reset");
Utils.SafeExecute(() =>
{
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
incomingMessagesThreadTimeTracking.OnStopExecution();
}
}, logger, "Client.incomingMessagesThreadTimeTracking.OnStopExecution");
Utils.SafeExecute(() =>
{
if (transport != null)
{
transport.PrepareToStop();
}
}, logger, "Client.PrepareToStop-Transport");
listenForMessages = false;
Utils.SafeExecute(() =>
{
if (listeningCts != null)
{
listeningCts.Cancel();
}
}, logger, "Client.Stop-ListeningCTS");
Utils.SafeExecute(() =>
{
if (transport != null)
{
transport.Stop();
}
}, logger, "Client.Stop-Transport");
Utils.SafeExecute(() =>
{
if (ClientStatistics != null)
{
ClientStatistics.Stop();
}
}, logger, "Client.Stop-ClientStatistics");
ConstructorReset();
}
private void ConstructorReset()
{
Utils.SafeExecute(() =>
{
if (logger != null)
{
logger.Info("OutsideRuntimeClient.ConstructorReset(): client Id " + clientId);
}
});
try
{
UnobservedExceptionsHandlerClass.ResetUnobservedExceptionHandler();
}
catch (Exception) { }
try
{
AppDomain.CurrentDomain.DomainUnload -= CurrentDomain_DomainUnload;
}
catch (Exception) { }
try
{
if (clientProviderRuntime != null)
{
clientProviderRuntime.Reset().WaitWithThrow(resetTimeout);
}
}
catch (Exception) { }
try
{
LogManager.UnInitialize();
}
catch (Exception) { }
}
public void SetResponseTimeout(TimeSpan timeout)
{
responseTimeout = timeout;
}
public TimeSpan GetResponseTimeout()
{
return responseTimeout;
}
public Task<IGrainReminder> RegisterOrUpdateReminder(string reminderName, TimeSpan dueTime, TimeSpan period)
{
throw new InvalidOperationException("RegisterReminder can only be called from inside a grain");
}
public Task UnregisterReminder(IGrainReminder reminder)
{
throw new InvalidOperationException("UnregisterReminder can only be called from inside a grain");
}
public Task<IGrainReminder> GetReminder(string reminderName)
{
throw new InvalidOperationException("GetReminder can only be called from inside a grain");
}
public Task<List<IGrainReminder>> GetReminders()
{
throw new InvalidOperationException("GetReminders can only be called from inside a grain");
}
public async Task ExecAsync(Func<Task> asyncFunction, ISchedulingContext context, string activityName)
{
await Task.Run(asyncFunction); // No grain context on client - run on .NET thread pool
}
public GrainReference CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker)
{
if (obj is GrainReference)
throw new ArgumentException("Argument obj is already a grain reference.");
GrainReference gr = GrainReference.NewObserverGrainReference(clientId, GuidId.GetNewGuidId());
if (!localObjects.TryAdd(gr.ObserverId, new LocalObjectData(obj, gr.ObserverId, invoker)))
{
throw new ArgumentException(String.Format("Failed to add new observer {0} to localObjects collection.", gr), "gr");
}
return gr;
}
public void DeleteObjectReference(IAddressable obj)
{
if (!(obj is GrainReference))
throw new ArgumentException("Argument reference is not a grain reference.");
var reference = (GrainReference)obj;
LocalObjectData ignore;
if (!localObjects.TryRemove(reference.ObserverId, out ignore))
throw new ArgumentException("Reference is not associated with a local object.", "reference");
}
#endregion Implementation of IRuntimeClient
private void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
try
{
logger.Warn(ErrorCode.ProxyClient_AppDomain_Unload,
String.Format("Current AppDomain={0} is unloading.", PrintAppDomainDetails()));
LogManager.Flush();
}
catch (Exception)
{
// just ignore, make sure not to throw from here.
}
}
private string PrintAppDomainDetails()
{
#if NETSTANDARD_TODO
return "N/A";
#else
return string.Format("<AppDomain.Id={0}, AppDomain.FriendlyName={1}>", AppDomain.CurrentDomain.Id, AppDomain.CurrentDomain.FriendlyName);
#endif
}
private class LocalObjectData
{
internal WeakReference LocalObject { get; private set; }
internal IGrainMethodInvoker Invoker { get; private set; }
internal GuidId ObserverId { get; private set; }
internal Queue<Message> Messages { get; private set; }
internal bool Running { get; set; }
internal LocalObjectData(IAddressable obj, GuidId observerId, IGrainMethodInvoker invoker)
{
LocalObject = new WeakReference(obj);
ObserverId = observerId;
Invoker = invoker;
Messages = new Queue<Message>();
Running = false;
}
}
public void Dispose()
{
if (listeningCts != null)
{
listeningCts.Dispose();
listeningCts = null;
this.assemblyProcessor.Dispose();
}
transport.Dispose();
if (ClientStatistics != null)
{
ClientStatistics.Dispose();
ClientStatistics = null;
}
GC.SuppressFinalize(this);
}
public IGrainTypeResolver GrainTypeResolver
{
get { return grainInterfaceMap; }
}
public void BreakOutstandingMessagesToDeadSilo(SiloAddress deadSilo)
{
foreach (var callback in callbacks)
{
if (deadSilo.Equals(callback.Value.Message.TargetSilo))
{
callback.Value.OnTargetSiloFail();
}
}
}
}
}
| |
// Copyright (c) 2017 Jan Pluskal, Viliam Letavay
//
//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.
/**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
using System;
using System.Text;
using Thrift.Protocol;
namespace Netfox.SnooperMessenger.Protocol
{
#if !SILVERLIGHT
[Serializable]
#endif
public partial class MNMessagesSyncDeltaReadReceipt : TBase
{
private MNMessagesSyncThreadKey _ThreadKey;
private long _ActorFbId;
private long _ActionTimestampMs;
private long _WatermarkTimestampMs;
public MNMessagesSyncThreadKey ThreadKey
{
get
{
return _ThreadKey;
}
set
{
__isset.ThreadKey = true;
this._ThreadKey = value;
}
}
public long ActorFbId
{
get
{
return _ActorFbId;
}
set
{
__isset.ActorFbId = true;
this._ActorFbId = value;
}
}
public long ActionTimestampMs
{
get
{
return _ActionTimestampMs;
}
set
{
__isset.ActionTimestampMs = true;
this._ActionTimestampMs = value;
}
}
public long WatermarkTimestampMs
{
get
{
return _WatermarkTimestampMs;
}
set
{
__isset.WatermarkTimestampMs = true;
this._WatermarkTimestampMs = value;
}
}
public Isset __isset;
#if !SILVERLIGHT
[Serializable]
#endif
public struct Isset {
public bool ThreadKey;
public bool ActorFbId;
public bool ActionTimestampMs;
public bool WatermarkTimestampMs;
}
public MNMessagesSyncDeltaReadReceipt() {
}
public void Read (TProtocol iprot)
{
iprot.IncrementRecursionDepth();
try
{
TField field;
iprot.ReadStructBegin();
while (true)
{
field = iprot.ReadFieldBegin();
if (field.Type == TType.Stop) {
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.Struct) {
ThreadKey = new MNMessagesSyncThreadKey();
ThreadKey.Read(iprot);
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 2:
if (field.Type == TType.I64) {
ActorFbId = iprot.ReadI64();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 3:
if (field.Type == TType.I64) {
ActionTimestampMs = iprot.ReadI64();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 4:
if (field.Type == TType.I64) {
WatermarkTimestampMs = iprot.ReadI64();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
default:
TProtocolUtil.Skip(iprot, field.Type);
break;
}
iprot.ReadFieldEnd();
}
iprot.ReadStructEnd();
}
finally
{
iprot.DecrementRecursionDepth();
}
}
public void Write(TProtocol oprot) {
oprot.IncrementRecursionDepth();
try
{
TStruct struc = new TStruct("MNMessagesSyncDeltaReadReceipt");
oprot.WriteStructBegin(struc);
TField field = new TField();
if (ThreadKey != null && __isset.ThreadKey) {
field.Name = "ThreadKey";
field.Type = TType.Struct;
field.ID = 1;
oprot.WriteFieldBegin(field);
ThreadKey.Write(oprot);
oprot.WriteFieldEnd();
}
if (__isset.ActorFbId) {
field.Name = "ActorFbId";
field.Type = TType.I64;
field.ID = 2;
oprot.WriteFieldBegin(field);
oprot.WriteI64(ActorFbId);
oprot.WriteFieldEnd();
}
if (__isset.ActionTimestampMs) {
field.Name = "ActionTimestampMs";
field.Type = TType.I64;
field.ID = 3;
oprot.WriteFieldBegin(field);
oprot.WriteI64(ActionTimestampMs);
oprot.WriteFieldEnd();
}
if (__isset.WatermarkTimestampMs) {
field.Name = "WatermarkTimestampMs";
field.Type = TType.I64;
field.ID = 4;
oprot.WriteFieldBegin(field);
oprot.WriteI64(WatermarkTimestampMs);
oprot.WriteFieldEnd();
}
oprot.WriteFieldStop();
oprot.WriteStructEnd();
}
finally
{
oprot.DecrementRecursionDepth();
}
}
public override string ToString() {
StringBuilder __sb = new StringBuilder("MNMessagesSyncDeltaReadReceipt(");
bool __first = true;
if (ThreadKey != null && __isset.ThreadKey) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("ThreadKey: ");
__sb.Append(ThreadKey== null ? "<null>" : ThreadKey.ToString());
}
if (__isset.ActorFbId) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("ActorFbId: ");
__sb.Append(ActorFbId);
}
if (__isset.ActionTimestampMs) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("ActionTimestampMs: ");
__sb.Append(ActionTimestampMs);
}
if (__isset.WatermarkTimestampMs) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("WatermarkTimestampMs: ");
__sb.Append(WatermarkTimestampMs);
}
__sb.Append(")");
return __sb.ToString();
}
}
}
| |
namespace Boxed.AspNetCore
{
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
/// <summary>
/// <see cref="IServiceCollection"/> extension methods.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Executes the specified action if the specified <paramref name="condition"/> is <c>true</c> which can be
/// used to conditionally configure the MVC services.
/// </summary>
/// <param name="services">The services collection.</param>
/// <param name="condition">If set to <c>true</c> the action is executed.</param>
/// <param name="action">The action used to configure the MVC services.</param>
/// <returns>The same services collection.</returns>
public static IServiceCollection AddIf(
this IServiceCollection services,
bool condition,
Func<IServiceCollection, IServiceCollection> action)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (action == null)
{
throw new ArgumentNullException(nameof(action));
}
if (condition)
{
services = action(services);
}
return services;
}
/// <summary>
/// Executes the specified <paramref name="ifAction"/> if the specified <paramref name="condition"/> is
/// <c>true</c>, otherwise executes the <paramref name="elseAction"/>. This can be used to conditionally
/// configure the MVC services.
/// </summary>
/// <param name="services">The services collection.</param>
/// <param name="condition">If set to <c>true</c> the <paramref name="ifAction"/> is executed, otherwise the
/// <paramref name="elseAction"/> is executed.</param>
/// <param name="ifAction">The action used to configure the MVC services if the condition is <c>true</c>.</param>
/// <param name="elseAction">The action used to configure the MVC services if the condition is <c>false</c>.</param>
/// <returns>The same services collection.</returns>
public static IServiceCollection AddIfElse(
this IServiceCollection services,
bool condition,
Func<IServiceCollection, IServiceCollection> ifAction,
Func<IServiceCollection, IServiceCollection> elseAction)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (ifAction == null)
{
throw new ArgumentNullException(nameof(ifAction));
}
if (elseAction == null)
{
throw new ArgumentNullException(nameof(elseAction));
}
if (condition)
{
services = ifAction(services);
}
else
{
services = elseAction(services);
}
return services;
}
/// <summary>
/// Registers <see cref="IOptions{TOptions}"/> and <typeparamref name="TOptions"/> to the services container.
/// </summary>
/// <typeparam name="TOptions">The type of the options.</typeparam>
/// <param name="services">The services collection.</param>
/// <param name="configuration">The configuration.</param>
/// <returns>The same services collection.</returns>
public static IServiceCollection ConfigureSingleton<TOptions>(
this IServiceCollection services,
IConfiguration configuration)
where TOptions : class, new()
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
return services
.Configure<TOptions>(configuration)
.AddSingleton(x => x.GetRequiredService<IOptions<TOptions>>().Value);
}
/// <summary>
/// Registers <see cref="IOptions{TOptions}"/> and <typeparamref name="TOptions"/> to the services container.
/// Also runs data annotation validation.
/// </summary>
/// <typeparam name="TOptions">The type of the options.</typeparam>
/// <param name="services">The services collection.</param>
/// <param name="configuration">The configuration.</param>
/// <returns>The same services collection.</returns>
public static IServiceCollection ConfigureAndValidateSingleton<TOptions>(
this IServiceCollection services,
IConfiguration configuration)
where TOptions : class, new()
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
services
.AddOptions<TOptions>()
.Bind(configuration)
.ValidateDataAnnotations();
return services.AddSingleton(x => x.GetRequiredService<IOptions<TOptions>>().Value);
}
/// <summary>
/// Registers <see cref="IOptions{TOptions}"/> and <typeparamref name="TOptions"/> to the services container.
/// Also runs data annotation validation and custom validation using the default failure message.
/// </summary>
/// <typeparam name="TOptions">The type of the options.</typeparam>
/// <param name="services">The services collection.</param>
/// <param name="configuration">The configuration.</param>
/// <param name="validation">The validation function.</param>
/// <returns>The same services collection.</returns>
public static IServiceCollection ConfigureAndValidateSingleton<TOptions>(
this IServiceCollection services,
IConfiguration configuration,
Func<TOptions, bool> validation)
where TOptions : class, new()
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
if (validation == null)
{
throw new ArgumentNullException(nameof(validation));
}
services
.AddOptions<TOptions>()
.Bind(configuration)
.ValidateDataAnnotations()
.Validate(validation);
return services.AddSingleton(x => x.GetRequiredService<IOptions<TOptions>>().Value);
}
/// <summary>
/// Registers <see cref="IOptions{TOptions}"/> and <typeparamref name="TOptions"/> to the services container.
/// Also runs data annotation validation and custom validation.
/// </summary>
/// <typeparam name="TOptions">The type of the options.</typeparam>
/// <param name="services">The services collection.</param>
/// <param name="configuration">The configuration.</param>
/// <param name="validation">The validation function.</param>
/// <param name="failureMessage">The failure message to use when validation fails.</param>
/// <returns>The same services collection.</returns>
public static IServiceCollection ConfigureAndValidateSingleton<TOptions>(
this IServiceCollection services,
IConfiguration configuration,
Func<TOptions, bool> validation,
string failureMessage)
where TOptions : class, new()
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (configuration == null)
{
throw new ArgumentNullException(nameof(configuration));
}
if (validation == null)
{
throw new ArgumentNullException(nameof(validation));
}
if (failureMessage == null)
{
throw new ArgumentNullException(nameof(failureMessage));
}
services
.AddOptions<TOptions>()
.Bind(configuration)
.ValidateDataAnnotations()
.Validate(validation, failureMessage);
return services.AddSingleton(x => x.GetRequiredService<IOptions<TOptions>>().Value);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.DotNet.CodeFormatting.Rules
{
/// <summary>
/// Mark any fields that can provably be marked as readonly.
/// </summary>
[GlobalSemanticRule(GlobalSemanticRuleOrder.MarkReadonlyFieldsRule,
FormattingLevel = FormattingLevel.Agressive)]
internal sealed class MarkReadonlyFieldsRule : IGlobalSemanticFormattingRule
{
private readonly SemaphoreSlim _processUsagesLock = new SemaphoreSlim(1, 1);
private ConcurrentDictionary<IFieldSymbol, bool> _unwrittenWritableFields;
public bool SupportsLanguage(string languageName)
{
return languageName == LanguageNames.CSharp;
}
public async Task<Solution> ProcessAsync(
Document document,
SyntaxNode syntaxRoot,
CancellationToken cancellationToken)
{
if (_unwrittenWritableFields == null)
{
using (await SemaphoreLock.GetAsync(_processUsagesLock))
{
// A global analysis must be run before we can do any actual processing, because a field might
// be written in a different file than it is declared (even private ones may be split between
// partial classes).
// It's also quite expensive, which is why it's being done inside the lock, so
// that the entire solution is not processed for each input file individually
if (_unwrittenWritableFields == null)
{
List<Document> allDocuments =
document.Project.Solution.Projects.SelectMany(p => p.Documents).ToList();
HashSet<IFieldSymbol>[] fields = await Task.WhenAll(
allDocuments
.AsParallel()
.Select(
doc => WritableFieldScanner.Scan(doc, cancellationToken)));
var writableFields = new ConcurrentDictionary<IFieldSymbol, bool>(
fields.SelectMany(s => s).Select(f => new KeyValuePair<IFieldSymbol, bool>(f, true)));
await Task.WhenAll(
allDocuments.AsParallel()
.Select(
doc => WriteUsagesScanner.RemoveWrittenFields(
doc,
writableFields,
cancellationToken)));
_unwrittenWritableFields = writableFields;
}
}
}
if (_unwrittenWritableFields.Count == 0)
{
// If there are no unwritten writable fields, skip all the rewriting
return document.Project.Solution;
}
SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken);
var application = new ReadonlyRewriter(
_unwrittenWritableFields,
await document.GetSemanticModelAsync(cancellationToken));
return document.Project.Solution.WithDocumentSyntaxRoot(document.Id, application.Visit(root));
}
/// <summary>
/// This is the first walker, which looks for fields that are valid to transform to readonly.
/// It returns any private or internal fields that are not already marked readonly, and returns a hash set
/// of them. Internal fields are only considered if the "InternalsVisibleTo" is a reference to something
/// in the same solution, since it's possible to analyse the global usages of it. Otherwise there is an
/// assembly we don't have access to that can see that field, so we have to treat is as public.
/// </summary>
private sealed class WritableFieldScanner : CSharpSyntaxWalker
{
private static readonly HashSet<string> s_serializingFieldAttributes = new HashSet<string>
{
"System.ComponentModel.Composition.ImportAttribute",
"System.ComponentModel.Composition.ImportManyAttribute",
};
private readonly HashSet<IFieldSymbol> _fields = new HashSet<IFieldSymbol>();
private readonly ISymbol _internalsVisibleToAttribute;
private readonly SemanticModel _model;
private WritableFieldScanner(SemanticModel model)
{
_model = model;
_internalsVisibleToAttribute =
model.Compilation.GetTypeByMetadataName(
"System.Runtime.CompilerServices.InternalsVisibleToAttribute");
}
public static async Task<HashSet<IFieldSymbol>> Scan(
Document document,
CancellationToken cancellationToken)
{
var scanner = new WritableFieldScanner(
await document.GetSemanticModelAsync(cancellationToken));
scanner.Visit(await document.GetSyntaxRootAsync(cancellationToken));
return scanner._fields;
}
public override void VisitFieldDeclaration(FieldDeclarationSyntax node)
{
var fieldSymbol = (IFieldSymbol)_model.GetDeclaredSymbol(node.Declaration.Variables[0]);
if (fieldSymbol.IsReadOnly || fieldSymbol.IsConst || fieldSymbol.IsExtern)
{
return;
}
if (IsSymbolVisibleOutsideSolution(fieldSymbol, _internalsVisibleToAttribute))
{
return;
}
if (IsFieldSerializableByAttributes(fieldSymbol))
{
return;
}
_fields.Add(fieldSymbol);
}
private static bool IsSymbolVisibleOutsideSolution(ISymbol symbol, ISymbol internalsVisibleToAttribute)
{
Accessibility accessibility = symbol.DeclaredAccessibility;
if (accessibility == Accessibility.NotApplicable)
{
if (symbol.Kind == SymbolKind.Field)
{
accessibility = Accessibility.Private;
}
else
{
accessibility = Accessibility.Internal;
}
}
if (accessibility == Accessibility.Public || accessibility == Accessibility.Protected)
{
if (symbol.ContainingType != null)
{
// a public symbol in a non-visible class isn't visible
return IsSymbolVisibleOutsideSolution(symbol.ContainingType, internalsVisibleToAttribute);
}
// They are public, we are going to skip them.
return true;
}
if (accessibility > Accessibility.Private)
{
bool visibleOutsideSolution = IsVisibleOutsideSolution(
symbol,
internalsVisibleToAttribute);
if (visibleOutsideSolution)
{
if (symbol.ContainingType != null)
{
// a visible symbol in a non-visible class isn't visible
return IsSymbolVisibleOutsideSolution(
symbol.ContainingType,
internalsVisibleToAttribute);
}
return true;
}
}
return false;
}
private static bool IsVisibleOutsideSolution(
ISymbol field,
ISymbol internalsVisibleToAttribute)
{
IAssemblySymbol assembly = field.ContainingAssembly;
return assembly.GetAttributes().Any(a => Equals(a.AttributeClass, internalsVisibleToAttribute));
}
private bool IsFieldSerializableByAttributes(IFieldSymbol field)
{
if (field.GetAttributes()
.Any(attr => s_serializingFieldAttributes.Contains(NameHelper.GetFullName(attr.AttributeClass))))
{
return true;
}
return false;
}
}
/// <summary>
/// This is the second walker. It checks all code for instances where one of the writable fields (as
/// calculated by <see cref="WritableFieldScanner" />) is written to, and removes it from the set.
/// Once the scan is complete, the set will not contain any fields written in the specified document.
/// </summary>
private sealed class WriteUsagesScanner : CSharpSyntaxWalker
{
private readonly SemanticModel _semanticModel;
private readonly ConcurrentDictionary<IFieldSymbol, bool> _writableFields;
private WriteUsagesScanner(
SemanticModel semanticModel,
ConcurrentDictionary<IFieldSymbol, bool> writableFields)
{
_semanticModel = semanticModel;
_writableFields = writableFields;
}
public override void VisitArgument(ArgumentSyntax node)
{
base.VisitArgument(node);
if (!node.RefOrOutKeyword.IsKind(SyntaxKind.None))
{
CheckForFieldWrite(node.Expression);
}
}
public override void VisitAssignmentExpression(AssignmentExpressionSyntax node)
{
base.VisitAssignmentExpression(node);
CheckForFieldWrite(node.Left);
}
public override void VisitBinaryExpression(BinaryExpressionSyntax node)
{
base.VisitBinaryExpression(node);
switch (node.OperatorToken.Kind())
{
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
{
CheckForFieldWrite(node.Left);
break;
}
}
}
public override void VisitIndexerDeclaration(IndexerDeclarationSyntax node)
{
base.VisitIndexerDeclaration(node);
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.ExternKeyword)))
{
// This method body is unable to be analysed, so may contain writer instances
CheckForRefParametersForExternMethod(node.ParameterList.Parameters);
}
}
public override void VisitInvocationExpression(InvocationExpressionSyntax node)
{
base.VisitInvocationExpression(node);
// A call to myStruct.myField.myMethod() will change if "myField" is marked
// readonly, since myMethod might modify it. So those need to be counted as writes
if (node.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
var memberAccess = (MemberAccessExpressionSyntax)node.Expression;
ISymbol symbol = _semanticModel.GetSymbolInfo(memberAccess.Expression).Symbol;
if (symbol?.Kind == SymbolKind.Field)
{
var fieldSymbol = (IFieldSymbol)symbol;
if (fieldSymbol.Type.TypeKind == TypeKind.Struct)
{
if (!IsImmutablePrimitiveType(fieldSymbol.Type))
{
MarkWriteInstance(fieldSymbol);
}
}
}
}
}
public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
{
base.VisitMethodDeclaration(node);
if (node.Modifiers.Any(m => m.IsKind(SyntaxKind.ExternKeyword)))
{
// This method body is unable to be analysed, so may contain writer instances
CheckForRefParametersForExternMethod(node.ParameterList.Parameters);
}
}
private void CheckForRefParametersForExternMethod(IEnumerable<ParameterSyntax> parameters)
{
foreach (ParameterSyntax parameter in parameters)
{
ITypeSymbol parameterType = _semanticModel.GetTypeInfo(parameter.Type).Type;
if (parameterType == null)
{
continue;
}
bool canModify = true;
if (parameterType.TypeKind == TypeKind.Struct)
{
canModify = parameter.Modifiers.Any(m => m.IsKind(SyntaxKind.RefKeyword));
}
if (canModify)
{
// This parameter might be used to modify one of the fields, since the
// implmentation is hidden from this analysys. Assume all fields
// of the type are written to
foreach (IFieldSymbol field in parameterType.GetMembers().OfType<IFieldSymbol>())
{
MarkWriteInstance(field);
}
}
}
}
private void CheckForFieldWrite(ExpressionSyntax node)
{
var fieldSymbol = _semanticModel.GetSymbolInfo(node).Symbol as IFieldSymbol;
if (fieldSymbol != null)
{
if (IsInsideOwnConstructor(node, fieldSymbol.ContainingType, fieldSymbol.IsStatic))
{
return;
}
MarkWriteInstance(fieldSymbol);
}
}
private bool IsImmutablePrimitiveType(ITypeSymbol type)
{
// All of the "special type" structs exposed are all immutable,
// so it's safe to assume all methods on them are non-mutating, and
// therefore safe to call on a readonly field
return type.SpecialType != SpecialType.None && type.TypeKind == TypeKind.Struct;
}
private bool IsInsideOwnConstructor(SyntaxNode node, ITypeSymbol type, bool isStatic)
{
while (node != null)
{
switch (node.Kind())
{
case SyntaxKind.ConstructorDeclaration:
{
return _semanticModel.GetDeclaredSymbol(node).IsStatic == isStatic &&
IsInType(node.Parent, type);
}
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
return false;
}
node = node.Parent;
}
return false;
}
private bool IsInType(SyntaxNode node, ITypeSymbol containingType)
{
while (node != null)
{
if (node.IsKind(SyntaxKind.ClassDeclaration) || node.IsKind(SyntaxKind.StructDeclaration))
{
return Equals(containingType, _semanticModel.GetDeclaredSymbol(node));
}
node = node.Parent;
}
return false;
}
private void MarkWriteInstance(IFieldSymbol fieldSymbol)
{
bool ignored;
_writableFields.TryRemove(fieldSymbol, out ignored);
}
public static async Task RemoveWrittenFields(
Document document,
ConcurrentDictionary<IFieldSymbol, bool> writableFields,
CancellationToken cancellationToken)
{
var scanner = new WriteUsagesScanner(
await document.GetSemanticModelAsync(cancellationToken),
writableFields);
scanner.Visit(await document.GetSyntaxRootAsync(cancellationToken));
}
}
/// <summary>
/// This is the actually rewriter, and should be run third, using the data gathered from the other two
/// (<see cref="WritableFieldScanner" /> and <see cref="WriteUsagesScanner" />).
/// Any field in the set is both writeable, but not actually written to, which means the "readonly"
/// modifier should be applied to it.
/// </summary>
private sealed class ReadonlyRewriter : CSharpSyntaxRewriter
{
private readonly SemanticModel _model;
private readonly ConcurrentDictionary<IFieldSymbol, bool> _unwrittenFields;
public ReadonlyRewriter(ConcurrentDictionary<IFieldSymbol, bool> unwrittenFields, SemanticModel model)
{
_model = model;
_unwrittenFields = unwrittenFields;
}
public override SyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax node)
{
var fieldSymbol = (IFieldSymbol)_model.GetDeclaredSymbol(node.Declaration.Variables[0]);
bool ignored;
if (_unwrittenFields.TryRemove(fieldSymbol, out ignored))
{
return
node.WithModifiers(
node.Modifiers.Add(
SyntaxFactory.Token(
SyntaxFactory.TriviaList(),
SyntaxKind.ReadOnlyKeyword,
SyntaxFactory.TriviaList(
SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ")))));
}
return node;
}
}
}
}
| |
using System;
#if REAL_T_IS_DOUBLE
using real_t = System.Double;
#else
using real_t = System.Single;
#endif
namespace Godot
{
public static partial class Mathf
{
// Define constants with Decimal precision and cast down to double or float.
public const real_t Tau = (real_t) 6.2831853071795864769252867666M; // 6.2831855f and 6.28318530717959
public const real_t Pi = (real_t) 3.1415926535897932384626433833M; // 3.1415927f and 3.14159265358979
public const real_t Inf = real_t.PositiveInfinity;
public const real_t NaN = real_t.NaN;
private const real_t Deg2RadConst = (real_t) 0.0174532925199432957692369077M; // 0.0174532924f and 0.0174532925199433
private const real_t Rad2DegConst = (real_t) 57.295779513082320876798154814M; // 57.29578f and 57.2957795130823
public static real_t Abs(real_t s)
{
return Math.Abs(s);
}
public static int Abs(int s)
{
return Math.Abs(s);
}
public static real_t Acos(real_t s)
{
return (real_t)Math.Acos(s);
}
public static real_t Asin(real_t s)
{
return (real_t)Math.Asin(s);
}
public static real_t Atan(real_t s)
{
return (real_t)Math.Atan(s);
}
public static real_t Atan2(real_t x, real_t y)
{
return (real_t)Math.Atan2(x, y);
}
public static Vector2 Cartesian2Polar(real_t x, real_t y)
{
return new Vector2(Sqrt(x * x + y * y), Atan2(y, x));
}
public static real_t Ceil(real_t s)
{
return (real_t)Math.Ceiling(s);
}
public static int Clamp(int value, int min, int max)
{
return value < min ? min : value > max ? max : value;
}
public static real_t Clamp(real_t value, real_t min, real_t max)
{
return value < min ? min : value > max ? max : value;
}
public static real_t Cos(real_t s)
{
return (real_t)Math.Cos(s);
}
public static real_t Cosh(real_t s)
{
return (real_t)Math.Cosh(s);
}
public static int Decimals(real_t step)
{
return Decimals((decimal)step);
}
public static int Decimals(decimal step)
{
return BitConverter.GetBytes(decimal.GetBits(step)[3])[2];
}
public static real_t Deg2Rad(real_t deg)
{
return deg * Deg2RadConst;
}
public static real_t Ease(real_t s, real_t curve)
{
if (s < 0f)
{
s = 0f;
}
else if (s > 1.0f)
{
s = 1.0f;
}
if (curve > 0f)
{
if (curve < 1.0f)
{
return 1.0f - Pow(1.0f - s, 1.0f / curve);
}
return Pow(s, curve);
}
if (curve < 0f)
{
if (s < 0.5f)
{
return Pow(s * 2.0f, -curve) * 0.5f;
}
return (1.0f - Pow(1.0f - (s - 0.5f) * 2.0f, -curve)) * 0.5f + 0.5f;
}
return 0f;
}
public static real_t Exp(real_t s)
{
return (real_t)Math.Exp(s);
}
public static real_t Floor(real_t s)
{
return (real_t)Math.Floor(s);
}
public static real_t InverseLerp(real_t from, real_t to, real_t weight)
{
return (weight - from) / (to - from);
}
public static bool IsInf(real_t s)
{
return real_t.IsInfinity(s);
}
public static bool IsNaN(real_t s)
{
return real_t.IsNaN(s);
}
public static real_t Lerp(real_t from, real_t to, real_t weight)
{
return from + (to - from) * weight;
}
public static real_t Log(real_t s)
{
return (real_t)Math.Log(s);
}
public static int Max(int a, int b)
{
return a > b ? a : b;
}
public static real_t Max(real_t a, real_t b)
{
return a > b ? a : b;
}
public static int Min(int a, int b)
{
return a < b ? a : b;
}
public static real_t Min(real_t a, real_t b)
{
return a < b ? a : b;
}
public static int NearestPo2(int value)
{
value--;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
value |= value >> 16;
value++;
return value;
}
public static Vector2 Polar2Cartesian(real_t r, real_t th)
{
return new Vector2(r * Cos(th), r * Sin(th));
}
/// <summary>
/// Performs a canonical Modulus operation, where the output is on the range [0, b).
/// </summary>
public static real_t PosMod(real_t a, real_t b)
{
real_t c = a % b;
if ((c < 0 && b > 0) || (c > 0 && b < 0))
{
c += b;
}
return c;
}
/// <summary>
/// Performs a canonical Modulus operation, where the output is on the range [0, b).
/// </summary>
public static int PosMod(int a, int b)
{
int c = a % b;
if ((c < 0 && b > 0) || (c > 0 && b < 0))
{
c += b;
}
return c;
}
public static real_t Pow(real_t x, real_t y)
{
return (real_t)Math.Pow(x, y);
}
public static real_t Rad2Deg(real_t rad)
{
return rad * Rad2DegConst;
}
public static real_t Round(real_t s)
{
return (real_t)Math.Round(s);
}
public static int Sign(int s)
{
return s < 0 ? -1 : 1;
}
public static real_t Sign(real_t s)
{
return s < 0f ? -1f : 1f;
}
public static real_t Sin(real_t s)
{
return (real_t)Math.Sin(s);
}
public static real_t Sinh(real_t s)
{
return (real_t)Math.Sinh(s);
}
public static real_t Sqrt(real_t s)
{
return (real_t)Math.Sqrt(s);
}
public static real_t Stepify(real_t s, real_t step)
{
if (step != 0f)
{
s = Floor(s / step + 0.5f) * step;
}
return s;
}
public static real_t Tan(real_t s)
{
return (real_t)Math.Tan(s);
}
public static real_t Tanh(real_t s)
{
return (real_t)Math.Tanh(s);
}
public static int Wrap(int value, int min, int max)
{
int rng = max - min;
return min + ((value - min) % rng + rng) % rng;
}
public static real_t Wrap(real_t value, real_t min, real_t max)
{
real_t rng = max - min;
return min + ((value - min) % rng + rng) % rng;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
namespace Internal.Runtime
{
/// <summary>
/// Utility class for encoding GCDescs. GCDesc is a runtime structure used by the
/// garbage collector that describes the GC layout of a memory region.
/// </summary>
public struct GCDescEncoder
{
/// <summary>
/// Retrieves size of the GCDesc that describes the instance GC layout for the given type.
/// </summary>
public static int GetGCDescSize(TypeDesc type)
{
if (type.IsArray)
{
TypeDesc elementType = ((ArrayType)type).ElementType;
if (elementType.IsGCPointer)
{
// For efficiency this is special cased and encoded as one serie.
return 3 * type.Context.Target.PointerSize;
}
else if (elementType.IsDefType)
{
var defType = (DefType)elementType;
if (defType.ContainsGCPointers)
{
GCPointerMap pointerMap = GCPointerMap.FromInstanceLayout(defType);
if (pointerMap.IsAllGCPointers)
{
// For efficiency this is special cased and encoded as one serie.
return 3 * type.Context.Target.PointerSize;
}
else
{
int numSeries = pointerMap.NumSeries;
Debug.Assert(numSeries > 0);
return (numSeries + 2) * type.Context.Target.PointerSize;
}
}
}
}
else
{
var defType = (DefType)type;
if (defType.ContainsGCPointers)
{
int numSeries = GCPointerMap.FromInstanceLayout(defType).NumSeries;
Debug.Assert(numSeries > 0);
return (numSeries * 2 + 1) * type.Context.Target.PointerSize;
}
}
return 0;
}
public static void EncodeGCDesc<T>(ref T builder, TypeDesc type)
where T : struct, ITargetBinaryWriter
{
int initialBuilderPosition = builder.CountBytes;
if (type.IsArray)
{
TypeDesc elementType = ((ArrayType)type).ElementType;
// 2 means m_pEEType and _numComponents. Syncblock is sort of appended at the end of the object layout in this case.
int baseSize = 2 * builder.TargetPointerSize;
if (type.IsMdArray)
{
// Multi-dim arrays include upper and lower bounds for each rank
baseSize += 2 * sizeof(int) * ((ArrayType)type).Rank;
}
if (elementType.IsGCPointer)
{
EncodeAllGCPointersArrayGCDesc(ref builder, baseSize);
}
else if (elementType.IsDefType)
{
var elementDefType = (DefType)elementType;
if (elementDefType.ContainsGCPointers)
{
GCPointerMap pointerMap = GCPointerMap.FromInstanceLayout(elementDefType);
if (pointerMap.IsAllGCPointers)
{
EncodeAllGCPointersArrayGCDesc(ref builder, baseSize);
}
else
{
EncodeArrayGCDesc(ref builder, pointerMap, baseSize);
}
}
}
}
else
{
var defType = (DefType)type;
if (defType.ContainsGCPointers)
{
// Computing the layout for the boxed version if this is a value type.
int offs = defType.IsValueType ? builder.TargetPointerSize : 0;
// Include syncblock
int objectSize = defType.InstanceByteCount.AsInt + offs + builder.TargetPointerSize;
EncodeStandardGCDesc(ref builder, GCPointerMap.FromInstanceLayout(defType), objectSize, offs);
}
}
Debug.Assert(initialBuilderPosition + GetGCDescSize(type) == builder.CountBytes);
}
public static void EncodeStandardGCDesc<T>(ref T builder, GCPointerMap map, int size, int delta)
where T : struct, ITargetBinaryWriter
{
Debug.Assert(size >= map.Size);
int pointerSize = builder.TargetPointerSize;
int numSeries = 0;
for (int cellIndex = map.Size - 1; cellIndex >= 0; cellIndex--)
{
if (map[cellIndex])
{
numSeries++;
int seriesSize = pointerSize;
while (cellIndex > 0 && map[cellIndex - 1])
{
seriesSize += pointerSize;
cellIndex--;
}
builder.EmitNaturalInt(seriesSize - size);
builder.EmitNaturalInt(cellIndex * pointerSize + delta);
}
}
Debug.Assert(numSeries > 0);
builder.EmitNaturalInt(numSeries);
}
// Arrays of all GC references are encoded as special kind of GC desc for efficiency
private static void EncodeAllGCPointersArrayGCDesc<T>(ref T builder, int baseSize)
where T : struct, ITargetBinaryWriter
{
builder.EmitNaturalInt(-3 * builder.TargetPointerSize);
builder.EmitNaturalInt(baseSize);
// NumSeries
builder.EmitNaturalInt(1);
}
private static void EncodeArrayGCDesc<T>(ref T builder, GCPointerMap map, int baseSize)
where T : struct, ITargetBinaryWriter
{
// NOTE: This format cannot properly represent element types with sizes >= 64k bytes.
// We guard it with an assert, but it is the responsibility of the code using this
// to cap array component sizes. EEType only has a UInt16 field for component sizes too.
int numSeries = 0;
int leadingNonPointerCount = 0;
int pointerSize = builder.TargetPointerSize;
for (int cellIndex = 0; cellIndex < map.Size && !map[cellIndex]; cellIndex++)
{
leadingNonPointerCount++;
}
int nonPointerCount = leadingNonPointerCount;
for (int cellIndex = map.Size - 1; cellIndex >= leadingNonPointerCount; cellIndex--)
{
if (map[cellIndex])
{
numSeries++;
int pointerCount = 1;
while (cellIndex > leadingNonPointerCount && map[cellIndex - 1])
{
cellIndex--;
pointerCount++;
}
Debug.Assert(pointerCount < 64 * 1024);
builder.EmitHalfNaturalInt((short)pointerCount);
Debug.Assert(nonPointerCount * pointerSize < 64 * 1024);
builder.EmitHalfNaturalInt((short)(nonPointerCount * pointerSize));
nonPointerCount = 0;
}
else
{
nonPointerCount++;
}
}
Debug.Assert(numSeries > 0);
builder.EmitNaturalInt(baseSize + leadingNonPointerCount * pointerSize);
builder.EmitNaturalInt(-numSeries);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using Vevo;
using Vevo.Domain;
using Vevo.Domain.Products;
using Vevo.Domain.Shipping;
using Vevo.Domain.Stores;
using Vevo.Domain.Tax;
using Vevo.Shared.Utilities;
using Vevo.WebAppLib;
using Vevo.WebUI;
public partial class AdminAdvanced_Components_Products_ProductAttributes : AdminAdvancedBaseUserControl
{
#region Private
private const string _pathUploadProduct = "Images/Products/";
private const int MaxSmallProductImageWidth = 170;
private const string ProductDetailsSessionName = "AdminProductDetails";
private bool _isEditMode;
private bool _isEnterPrice = false;
private bool IsRestoreSession
{
get
{
return !MainContext.IsPostBack &&
ConvertUtilities.ToBoolean( MainContext.QueryString["Restore"] ) &&
Session[ProductDetailsSessionName] != null;
}
}
private string _pathUploadProductFile
{
get
{
return WebConfiguration.ProductDownloadPath + "/";
}
}
private string CurrentID
{
get
{
if (string.IsNullOrEmpty( MainContext.QueryString["ProductID"] ))
return "0";
else
return MainContext.QueryString["ProductID"];
}
}
private bool isCustomPrice
{
get
{
_isEnterPrice = uxUseCustomPriceCheck.Checked;
return _isEnterPrice;
}
}
private string FormatNumber( string number )
{
return String.Format( "{0:f2}", number );
}
private string CreateNonEmptyNumber( string number )
{
if (String.IsNullOrEmpty( number.Trim() ))
return "0";
else
return number;
}
private string[] OriginalOptionGroup
{
get { return (string[]) ViewState["OriginalOptionGroup"]; }
set { ViewState["OriginalOptionGroup"] = value; }
}
private double ConvertProductRatingForDatabase()
{
if (DataAccessContext.Configurations.GetIntValue( "StarRatingAmount" ) > 0)
{
return ConvertUtilities.ToDouble( uxProductRating.Text.Trim() ) /
DataAccessContext.Configurations.GetIntValue( "StarRatingAmount" );
}
else
return 0;
}
private void PopulateSpecificationItem( Product product )
{
foreach (ProductSpecification item in product.ProductSpecifications)
{
SpecificationItem specificationItem = DataAccessContext.SpecificationItemRepository.GetOne(
CurrentCulture, item.SpecificationItemID );
Panel rowPanel = (Panel) uxSpecificationItemTR.FindControl( "RowPanelSpecificationGroup" + specificationItem.SpecificationGroupID );
switch (specificationItem.Type)
{
case SpecificationItemControlType.Textbox:
TextBox text = (TextBox) rowPanel.FindControl( "SpecificationItem" + item.SpecificationItemID );
text.Text = item.Value;
break;
case SpecificationItemControlType.DropDownList:
DropDownList dropDown = (DropDownList) rowPanel.FindControl( "SpecificationItem" + item.SpecificationItemID );
dropDown.SelectedValue = item.Value;
break;
case SpecificationItemControlType.MultiSelect:
ListBox multiSelect = (ListBox) rowPanel.FindControl( "SpecificationItem" + item.SpecificationItemID );
foreach (ListItem listItem in multiSelect.Items)
{
if (listItem.Value == item.Value)
{
listItem.Selected = true;
break;
}
}
break;
default:
TextBox textDefault = (TextBox) rowPanel.FindControl( "SpecificationItem" + item.SpecificationItemID );
textDefault.Text = item.Value;
break;
}
}
}
private void PopulateShippingCost( Product product )
{
IList<ShippingOption> shippingList =
DataAccessContext.ShippingOptionRepository.GetShipping( StoreContext.Culture, BoolFilter.ShowFalse );
for (int i = 0; i < shippingList.Count; i++)
{
TextBox txt = (TextBox) uxShippingCostTR.FindControl( shippingList[i].ShippingID );
txt.Text = String.Format(
"{0:f2}",
product.GetOverriddenShippingCost( shippingList[i].ShippingID ) );
}
}
private void PopulateProductImage( string imageSecondary )
{
string mapUrl;
mapUrl = "../" + imageSecondary;
if (File.Exists( Server.MapPath( mapUrl ) ))
{
if (mapUrl != "")
{
Bitmap mypic;
mypic = new Bitmap( Server.MapPath( mapUrl ) );
if (mypic.Width < MaxSmallProductImageWidth)
uxProductImage.Width = mypic.Width;
else
uxProductImage.Width = MaxSmallProductImageWidth;
mypic.Dispose();
}
uxProductImage.Visible = true;
}
else
{
uxProductImage.Visible = false;
}
}
private void PopulateDefaultCheckboxVisible( string storeID )
{
if (storeID == "0")
{
uxPriceCheck.Visible = false;
uxUseDefaultPriceLabel.Visible = false;
uxRetailPriceCheck.Visible = false;
uxUseDefaultRetailLabel.Visible = false;
uxWholesaleCheck.Visible = false;
uxUseDefaultWholesaleLabel.Visible = false;
uxWholesale2Check.Visible = false;
uxUseDefaultWholesale2Label.Visible = false;
uxWholesale3Check.Visible = false;
uxUseDefaultWholesale3Label.Visible = false;
}
else
{
uxPriceCheck.Visible = true;
uxUseDefaultPriceLabel.Visible = true;
uxRetailPriceCheck.Visible = true;
uxUseDefaultRetailLabel.Visible = true;
uxWholesaleCheck.Visible = true;
uxUseDefaultWholesaleLabel.Visible = true;
uxWholesale2Check.Visible = true;
uxUseDefaultWholesale2Label.Visible = true;
uxWholesale3Check.Visible = true;
uxUseDefaultWholesale3Label.Visible = true;
}
}
private void PopulateProductPrices( Product product, string storeID )
{
ProductPrice defaultProductPrice = product.GetProductPrice( "0" );
ProductPrice productPrice = product.GetProductPrice( storeID );
PopulateDefaultCheckboxVisible( storeID );
uxPriceCheck.Checked = productPrice.UseDefaultPrice;
uxRetailPriceCheck.Checked = productPrice.UseDefaultRetailPrice;
uxWholesaleCheck.Checked = productPrice.UseDefaultWholeSalePrice;
uxWholesale2Check.Checked = productPrice.UseDefaultWholeSalePrice2;
uxWholesale3Check.Checked = productPrice.UseDefaultWholeSalePrice3;
if (uxPriceCheck.Checked && storeID != "0")
{
uxPriceText.Enabled = false;
uxPriceText.Text = String.Format( "{0:f2}", defaultProductPrice.Price );
}
else
{
uxPriceText.Enabled = true;
uxPriceText.Text = String.Format( "{0:f2}", productPrice.Price );
}
if (uxRetailPriceCheck.Checked && storeID != "0")
{
uxRetailPriceText.Enabled = false;
uxRetailPriceText.Text = String.Format( "{0:f2}", defaultProductPrice.RetailPrice );
}
else
{
uxRetailPriceText.Enabled = true;
uxRetailPriceText.Text = String.Format( "{0:f2}", productPrice.RetailPrice );
}
if (uxWholesaleCheck.Checked && storeID != "0")
{
uxWholesalePriceText.Enabled = false;
uxWholesalePriceText.Text = String.Format( "{0:f2}", defaultProductPrice.WholesalePrice );
}
else
{
uxWholesalePriceText.Enabled = true;
uxWholesalePriceText.Text = String.Format( "{0:f2}", productPrice.WholesalePrice );
}
if (uxWholesale2Check.Checked && storeID != "0")
{
uxWholesalePrice2Text.Enabled = false;
uxWholesalePrice2Text.Text = String.Format( "{0:f2}", defaultProductPrice.WholesalePrice2 );
}
else
{
uxWholesalePrice2Text.Enabled = true;
uxWholesalePrice2Text.Text = String.Format( "{0:f2}", productPrice.WholesalePrice2 );
}
if (uxWholesale3Check.Checked && storeID != "0")
{
uxWholesalePrice3Text.Enabled = false;
uxWholesalePrice3Text.Text = String.Format( "{0:f2}", defaultProductPrice.WholesalePrice3 );
}
else
{
uxWholesalePrice3Text.Enabled = true;
uxWholesalePrice3Text.Text = String.Format( "{0:f2}", productPrice.WholesalePrice3 );
}
}
private void SetPrice( Product product, string storeID, string storeViewID, out decimal price, out bool useDefaultPrice )
{
ProductPrice productPrice = product.GetProductPrice( storeID );
price = VerifyPrice(
storeID,
storeViewID,
ConvertUtilities.ToDecimal( CreateNonEmptyNumber( uxPriceText.Text ) ),
product.GetProductPrice( "0" ).Price,
productPrice.Price,
productPrice.UseDefaultPrice,
uxPriceCheck.Checked,
out useDefaultPrice );
}
private void SetRetailPrice( Product product, string storeID, string storeViewID, out decimal retailPrice, out bool useDefaultRetailPrice )
{
ProductPrice productPrice = product.GetProductPrice( storeID );
retailPrice = VerifyPrice(
storeID,
storeViewID,
ConvertUtilities.ToDecimal( CreateNonEmptyNumber( uxRetailPriceText.Text ) ),
product.GetProductPrice( "0" ).RetailPrice,
productPrice.RetailPrice,
productPrice.UseDefaultRetailPrice,
uxRetailPriceCheck.Checked,
out useDefaultRetailPrice );
}
private void SetWholesalePrice( Product product, string storeID, string storeViewID, out decimal wholesalePrice, out bool useDefaultWholesalePrice )
{
ProductPrice productPrice = product.GetProductPrice( storeID );
wholesalePrice = VerifyPrice(
storeID,
storeViewID,
ConvertUtilities.ToDecimal( CreateNonEmptyNumber( uxWholesalePriceText.Text ) ),
product.GetProductPrice( "0" ).WholesalePrice,
productPrice.WholesalePrice,
productPrice.UseDefaultWholeSalePrice,
uxWholesaleCheck.Checked,
out useDefaultWholesalePrice );
}
private void SetWholesalePrice2( Product product, string storeID, string storeViewID, out decimal wholesalePrice2, out bool useDefaultWholesalePrice2 )
{
ProductPrice productPrice = product.GetProductPrice( storeID );
wholesalePrice2 = VerifyPrice(
storeID,
storeViewID,
ConvertUtilities.ToDecimal( CreateNonEmptyNumber( uxWholesalePrice2Text.Text ) ),
product.GetProductPrice( "0" ).WholesalePrice2,
productPrice.WholesalePrice2,
productPrice.UseDefaultWholeSalePrice2,
uxWholesale2Check.Checked,
out useDefaultWholesalePrice2 );
}
private void SetWholesalePrice3( Product product, string storeID, string storeViewID, out decimal wholesalePrice3, out bool useDefaultWholesalePrice3 )
{
ProductPrice productPrice = product.GetProductPrice( storeID );
wholesalePrice3 = VerifyPrice(
storeID,
storeViewID,
ConvertUtilities.ToDecimal( CreateNonEmptyNumber( uxWholesalePrice3Text.Text ) ),
product.GetProductPrice( "0" ).WholesalePrice3,
productPrice.WholesalePrice3,
productPrice.UseDefaultWholeSalePrice3,
uxWholesale3Check.Checked,
out useDefaultWholesalePrice3 );
}
private decimal VerifyPrice(
string storeID,
string storeViewID,
decimal enteredPrice,
decimal defaultPrice,
decimal price,
bool useDefaultPrice,
bool enteredUseDefaultPrice,
out bool isUseDefaultPrice )
{
isUseDefaultPrice = true;
if (_isEditMode)
{
return ProductPrice.VerifyPrice(
storeID, storeViewID, enteredPrice, defaultPrice, price, useDefaultPrice, enteredUseDefaultPrice, out isUseDefaultPrice );
}
else
{
return enteredPrice;
}
}
private void SetProductPrice( Product product, string storeID, string storeViewID )
{
decimal price;
bool useDefaultPrice;
decimal retailPrice;
bool useDefalutRetailPrice;
decimal wholesalePrice;
bool useDefaultWholesalePrice;
decimal wholesalePrice2;
bool useDefaultWholesalePrice2;
decimal wholesalePrice3;
bool useDefaultWholesalePrice3;
SetPrice( product, storeID, storeViewID, out price, out useDefaultPrice );
if (RetailPriceMode)
{
SetRetailPrice( product, storeID, storeViewID, out retailPrice, out useDefalutRetailPrice );
}
else
{
SetPrice( product, storeID, storeViewID, out retailPrice, out useDefalutRetailPrice );
}
if (WholesaleMode == 1)
{
SetWholesalePrice( product, storeID, storeViewID, out wholesalePrice, out useDefaultWholesalePrice );
}
else
{
SetPrice( product, storeID, storeViewID, out wholesalePrice, out useDefaultWholesalePrice );
}
SetWholesalePrice2( product, storeID, storeViewID, out wholesalePrice2, out useDefaultWholesalePrice2 );
SetWholesalePrice3( product, storeID, storeViewID, out wholesalePrice3, out useDefaultWholesalePrice3 );
product.SetPrice( storeID,
price,
retailPrice,
wholesalePrice,
wholesalePrice2,
wholesalePrice3,
useDefaultPrice,
useDefalutRetailPrice,
useDefaultWholesalePrice,
useDefaultWholesalePrice2,
useDefaultWholesalePrice3 );
}
private void SetupProductPrices( Product product, string storeID )
{
if (storeID != "0")
{
SetProductPrice( product, storeID, storeID );
}
else
{
SetProductPrice( product, "0", "0" );
IList<Store> storeList = DataAccessContext.StoreRepository.GetAll( "StoreID" );
foreach (Store store in storeList)
{
SetProductPrice( product, store.StoreID, "0" );
}
}
}
private Control GetAjaxTabControl( Control control )
{
if (control.GetType().ToString() == "AjaxControlToolkit.TabContainer")
return control;
if (control.Parent == null)
return null;
return GetAjaxTabControl( control.Parent );
}
private void InitSpecificationGroup()
{
uxSpecificationGroupDrop.DataSource = DataAccessContext.SpecificationGroupRepository.GetAll( CurrentCulture );
uxSpecificationGroupDrop.DataTextField = "Name";
uxSpecificationGroupDrop.DataValueField = "SpecificationGroupID";
uxSpecificationGroupDrop.DataBind();
uxSpecificationGroupDrop.Items.Insert( 0, new ListItem( "None", "0" ) );
}
private void InitManufacturerList()
{
IList<Manufacturer> manufacturerList = DataAccessContext.ManufacturerRepository.GetAll( CurrentCulture, BoolFilter.ShowAll, "SortOrder" );
uxManufacturerDrop.Items.Add( new ListItem( "None", "" ) );
foreach (Manufacturer manufacturer in manufacturerList)
{
if (manufacturer.IsEnabled)
uxManufacturerDrop.Items.Add( new ListItem( manufacturer.Name, manufacturer.ManufacturerID ) );
}
}
#endregion
#region Protected
protected void uxDownloadPathLinkButton_Click( object sender, EventArgs e )
{
uxDownloadPathUpload.ShowControl = true;
}
protected void uxOptionalUploadLinkButton_Click( object sender, EventArgs e )
{
uxOptionalUpload.ShowControl = true;
}
protected void QuantityValidator( object source, ServerValidateEventArgs args )
{
if (String.IsNullOrEmpty( uxMinimumQuantityText.Text ) && String.IsNullOrEmpty( uxMaximumQuantityText.Text ))
{
args.IsValid = true;
return;
}
int minQuantity = ConvertUtilities.ToInt32( uxMinimumQuantityText.Text );
int maxQuantity = ConvertUtilities.ToInt32( uxMaximumQuantityText.Text );
if (maxQuantity != 0 && minQuantity > maxQuantity)
{
args.IsValid = false;
return;
}
args.IsValid = true;
}
protected void CustomPriceValidator( object source, ServerValidateEventArgs args )
{
decimal defaultPrice = ConvertUtilities.ToDecimal( uxDefaultPriceText.Text );
decimal minimumPrice = ConvertUtilities.ToDecimal( uxMinimumPriceText.Text );
if (minimumPrice > defaultPrice)
{
args.IsValid = false;
return;
}
args.IsValid = true;
}
protected void uxAddImagesButton_Click( object sender, EventArgs e )
{
Control control = GetAjaxTabControl( this );
AjaxControlToolkit.TabContainer tabControl = (AjaxControlToolkit.TabContainer) control;
tabControl.ActiveTab = tabControl.Tabs[1];
}
protected void uxSpecificationGroupDrop_SelectedIndexChanged( object sender, EventArgs e )
{
SetVisibleSpecificationControls();
}
protected void uxPriceCheck_OnCheckedChanged( object sender, EventArgs e )
{
if (uxPriceCheck.Checked)
{
uxPriceText.Enabled = false;
}
else
{
uxPriceText.Enabled = true;
}
}
protected void uxRetailPriceCheck_OnCheckedChanged( object sender, EventArgs e )
{
if (uxRetailPriceCheck.Checked)
{
uxRetailPriceText.Enabled = false;
}
else
{
uxRetailPriceText.Enabled = true;
}
}
protected void uxWholesaleCheck_OnCheckedChanged( object sender, EventArgs e )
{
if (uxWholesaleCheck.Checked)
{
uxWholesalePriceText.Enabled = false;
}
else
{
uxWholesalePriceText.Enabled = true;
}
}
protected void uxWholesaleCheck2_OnCheckedChanged( object sender, EventArgs e )
{
if (uxWholesale2Check.Checked)
{
uxWholesalePrice2Text.Enabled = false;
}
else
{
uxWholesalePrice2Text.Enabled = true;
}
}
protected void uxWholesaleCheck3_OnCheckedChanged( object sender, EventArgs e )
{
if (uxWholesale3Check.Checked)
{
uxWholesalePrice3Text.Enabled = false;
}
else
{
uxWholesalePrice3Text.Enabled = true;
}
}
protected void uxUseCustomPriceCheck_OnCheckedChanged( object sender, EventArgs e )
{
if (uxUseCustomPriceCheck.Checked)
{
uxUseCustomPriceTR.Visible = true;
RelatedPricePanelHide();
uxIsDynamicProductKitPriceCheck.Enabled = false;
uxCallForPricePanel.Visible = false;
uxIsCallForPriceCheck.Checked = false;
}
else
{
uxUseCustomPriceTR.Visible = false;
RelatedPricePanelShow();
uxIsDynamicProductKitPriceCheck.Enabled = true;
uxCallForPricePanel.Visible = true;
}
}
protected void uxIsCallForPriceCheck_OnCheckedChanged( object sender, EventArgs e )
{
if (uxIsCallForPriceCheck.Checked)
{
uxUseCustomPriceTR.Visible = false;
uxUseCustomPriceCheck.Checked = false;
}
else
{
uxUseCustomPriceTR.Visible = true;
}
}
protected void uxIncludeVatLabel_PreRender( object sender, EventArgs e )
{
uxIncludeVatLabel.Visible = DataAccessContext.Configurations.GetBoolValue( "TaxIncludedInPrice" );
}
protected void Page_Load( object sender, EventArgs e )
{
uxProductDetailsLayoutPathPanel.Style["display"] = "none";
uxOverrideProductLayoutDrop.Attributes.Add( "onchange", String.Format( "ShowHideObject('{0}')", uxProductDetailsLayoutPathPanel.ClientID ) );
if (!MainContext.IsPostBack)
{
InitSpecificationGroup();
InitManufacturerList();
uxOptionalUpload.PathDestination = _pathUploadProduct;
uxDownloadPathUpload.PathDestination = _pathUploadProductFile;
uxOptionalUpload.ReturnTextControlClientID = uxImageSecondaryText.ClientID;
uxDownloadPathUpload.ReturnTextControlClientID = uxDownloadPathText.ClientID;
if (_isEditMode)
{
AddImagesTR.Visible = false;
uxProductSeo.Visible = false;
uxCreateDatePanel.Visible = true;
uxViewCountPanel.Visible = true;
}
else
{
uxPriceCheck.Visible = false;
uxUseDefaultPriceLabel.Visible = false;
uxRetailPriceCheck.Visible = false;
uxUseDefaultRetailLabel.Visible = false;
uxWholesaleCheck.Visible = false;
uxUseDefaultWholesaleLabel.Visible = false;
uxWholesale2Check.Visible = false;
uxUseDefaultWholesale2Label.Visible = false;
uxWholesale3Check.Visible = false;
uxUseDefaultWholesale3Label.Visible = false;
uxMinimumQuantityText.Text = "1";
uxMaximumQuantityText.Text = "0";
uxRmaText.Text = "0";
uxCreateDatePanel.Visible = false;
uxViewCountPanel.Visible = false;
}
}
}
#endregion
#region Public Methods
public string Price { get { return FormatNumber( CreateNonEmptyNumber( uxPriceText.Text ) ); } }
public string RetailPrice { get { return FormatNumber( CreateNonEmptyNumber( uxRetailPriceText.Text ) ); } }
public string WholeSalePrice { get { return FormatNumber( CreateNonEmptyNumber( uxWholesalePriceText.Text ) ); } }
public string WholeSalePrice2 { get { return FormatNumber( CreateNonEmptyNumber( uxWholesalePrice2Text.Text ) ); } }
public string WholeSalePrice3 { get { return FormatNumber( CreateNonEmptyNumber( uxWholesalePrice3Text.Text ) ); } }
public string ImageSecondary { get { return FormatNumber( CreateNonEmptyNumber( uxImageSecondaryText.Text ) ); } }
public int WholesaleMode { get { return int.Parse( DataAccessContext.Configurations.GetValue( "WholesaleMode" ) ); } }
public int WholesaleLevel { get { return int.Parse( DataAccessContext.Configurations.GetValue( "WholesaleLevel" ) ); } }
public bool RetailPriceMode { get { return DataAccessContext.Configurations.GetBoolValue( "RetailPriceMode" ); } }
public Culture CurrentCulture
{
get
{
if (ViewState["Culture"] == null)
return null;
else
return (Culture) ViewState["Culture"];
}
set
{
ViewState["Culture"] = value;
uxProductSeo.CurrentCulture = value;
uxInventoryAndOption.CurrentCulture = value;
}
}
public void PopulateStockOptionControl()
{
uxInventoryAndOption.PopulateStockOptionControl();
}
public void PopulateStockVisibility()
{
uxInventoryAndOption.PopulateStockVisibility();
}
public void SetEditMode( bool isEditMode )
{
_isEditMode = isEditMode;
uxInventoryAndOption.IsEditMode = isEditMode;
}
public void ClearInputFields()
{
uxInventoryAndOption.ClearInputFields();
uxProductSeo.ClearInputFields();
uxSkuText.Text = "";
uxBrandText.Text = "";
uxModelText.Text = "";
uxImageSecondaryText.Text = "";
uxWeightText.Text = "";
uxFixedShippingCostDrop.SelectedValue = "False";
uxIsFreeShippingCostCheck.Checked = false;
uxWholesalePriceText.Text = "";
uxWholesalePrice2Text.Text = "";
uxWholesalePrice3Text.Text = "";
uxPriceText.Text = "";
uxRetailPriceText.Text = "";
uxKeywordsText.Text = "";
uxIsTodaySpecialCheck.Checked = false;
uxDownloadableCheck.Checked = false;
uxDownloadPathText.Text = "";
uxIsEnabledCheck.Checked = true;
uxQuantityDiscount.Clear();
uxMinimumQuantityText.Text = "1";
uxMaximumQuantityText.Text = "0";
uxRelatedProducts.Text = "";
uxImageSecondaryText.Text = "";
uxProductImage.ImageUrl = "";
uxProductImage.Visible = false;
uxManufacturerPartNumberText.Text = "";
uxUpcText.Text = "";
uxProductRating.Text = "";
uxTaxClassDrop.SelectedValue = TaxClass.NonTaxClassID;
uxOtherOneText.Text = "";
uxOtherTwoText.Text = "";
uxOtherThreeText.Text = "";
uxOtherFourText.Text = "";
uxOtherFiveText.Text = "";
uxViewCount.Text = "";
uxCreateDateTime.Text = "";
uxIsAffiliate.Checked = false;
uxOverrideProductLayoutDrop.SelectedValue = "False";
uxProductDetailsLayoutPathDrop.SelectedValue = "";
uxProductDetailsLayoutPathPanel.Style["display"] = "none";
uxUseCustomPriceCheck.Checked = false;
uxDefaultPriceText.Text = "";
uxMinimumPriceText.Text = "";
uxIsCallForPriceCheck.Checked = false;
uxSpecificationGroupDrop.SelectedIndex = 0;
uxRmaText.Text = "0";
uxIsDynamicProductKitPriceCheck.Checked = false;
uxIsDynamicProductKitWeightCheck.Checked = false;
uxUseCustomPriceCheck.Enabled = true;
uxWeightText.Enabled = true;
uxWholesalePriceText.Enabled = true;
uxWholesalePrice2Text.Enabled = true;
uxWholesalePrice3Text.Enabled = true;
uxPriceText.Enabled = true;
uxRetailPriceText.Enabled = true;
uxManufacturerDrop.SelectedIndex = 0;
uxLengthText.Text = "";
uxWidthText.Text = "";
uxHeightText.Text = "";
}
private string GetProductSpecificationGroupID( Product product )
{
foreach (ProductSpecification item in product.ProductSpecifications)
{
SpecificationItem specificationItem = DataAccessContext.SpecificationItemRepository.GetOne(
CurrentCulture, item.SpecificationItemID );
return specificationItem.SpecificationGroupID;
}
return "0";
}
public void PopulateControls( Product product, string storeID )
{
PopulateShippingCost( product );
PopulateProductPrices( product, storeID );
uxSpecificationGroupDrop.SelectedValue = GetProductSpecificationGroupID( product );
PopulateSpecificationItem( product );
SetVisibleSpecificationControls();
SetVisibleRmaControl();
uxInventoryAndOption.PopulateControls( product );
uxSkuText.Text = product.Sku;
uxBrandText.Text = product.Brand;
uxModelText.Text = product.Model;
uxImageSecondaryText.Text = product.ImageSecondary;
uxWeightText.Text = product.Weight.ToString();
uxFixedShippingCostDrop.SelectedValue = product.FixedShippingCost.ToString();
uxIsFreeShippingCostCheck.Checked = product.FreeShippingCost;
uxKeywordsText.Text = product.Keywords;
uxProductImage.ImageUrl = AdminConfig.UrlFront + product.ImageSecondary;
uxProductRating.Text =
Convert.ToString( Convert.ToDouble( product.MerchantRating ) *
Convert.ToInt32( DataAccessContext.Configurations.GetValue( "StarRatingAmount" ) ) );
PopulateProductImage( product.ImageSecondary );
uxIsTodaySpecialCheck.Checked = product.IsTodaySpecial;
uxDownloadableCheck.Checked = product.IsDownloadable;
uxDownloadPathText.Text = product.DownloadPath;
uxIsEnabledCheck.Checked = product.IsEnabled;
uxMinimumQuantityText.Text = product.MinQuantity.ToString();
uxMaximumQuantityText.Text = product.MaxQuantity.ToString();
uxRelatedProducts.Text = product.RelatedProducts;
uxQuantityDiscount.Refresh( product.DiscountGroupID );
uxManufacturerPartNumberText.Text = product.ManufacturerPartNumber;
uxUpcText.Text = product.Upc;
uxTaxClassDrop.SelectedValue = product.TaxClassID;
uxOtherOneText.Text = product.Other1;
uxOtherTwoText.Text = product.Other2;
uxOtherThreeText.Text = product.Other3;
uxOtherFourText.Text = product.Other4;
uxOtherFiveText.Text = product.Other5;
uxViewCount.Text = product.ViewCount.ToString();
uxCrateDateCalendar.SelectedDateText = product.CreateDate.ToShortDateString();
uxCrateDateCalendar.Visible = true;
uxCreateDateTime.Visible = false;
uxIsAffiliate.Checked = product.IsAffiliate;
uxIsCallForPriceCheck.Checked = product.IsCallForPrice;
if (uxIsCallForPriceCheck.Checked)
uxUseCustomPriceTR.Visible = false;
uxUseCustomPriceCheck.Checked = product.IsCustomPrice;
if (uxUseCustomPriceCheck.Checked)
uxCallForPricePanel.Visible = false;
uxDefaultPriceText.Text = String.Format( "{0:f2}", product.ProductCustomPrice.DefaultPrice );
uxMinimumPriceText.Text = String.Format( "{0:f2}", product.ProductCustomPrice.MinimumPrice );
uxRmaText.Text = product.ReturnTime.ToString();
if (!String.IsNullOrEmpty( product.ProductDetailsLayoutPath ))
{
uxOverrideProductLayoutDrop.SelectedValue = "True";
uxProductDetailsLayoutPathDrop.SelectedValue = product.ProductDetailsLayoutPath;
uxProductDetailsLayoutPathPanel.Style["display"] = "";
}
else
{
uxOverrideProductLayoutDrop.SelectedValue = "False";
uxProductDetailsLayoutPathPanel.Style["display"] = "none";
uxProductDetailsLayoutPathDrop.SelectedValue = "";
}
uxIsDynamicProductKitPriceCheck.Checked = product.IsDynamicProductKitPrice;
uxIsDynamicProductKitWeightCheck.Checked = product.IsDynamicProductKitWeight;
if (uxManufacturerDrop.Items.FindByValue( product.Manufacturer ) != null)
uxManufacturerDrop.SelectedValue = product.Manufacturer;
else
uxManufacturerDrop.SelectedValue = "";
uxLengthText.Text = product.Length.ToString();
uxWidthText.Text = product.Width.ToString();
uxHeightText.Text = product.Height.ToString();
}
public void SetDisplayControls()
{
uxInventoryAndOption.SetUpDisplay();
uxDownloadPathTR.Visible = true;
uxIsDownloadableTR.Visible = true;
uxRelateProductTR.Visible = true;
uxWeightTR.Visible = true;
uxIsEnabledTR.Visible = true;
}
public Product Setup( Product product, string storeID )
{
if (!_isEditMode)
{
product = uxProductSeo.Setup( product, storeID );
}
SetupProductPrices( product, storeID );
product.Sku = uxSkuText.Text;
product.Brand = uxBrandText.Text;
product.Model = uxModelText.Text;
product.ImageSecondary = ImageSecondary;
product.Weight = ConvertUtilities.ToDouble( CreateNonEmptyNumber( uxWeightText.Text ) );
product.FixedShippingCost = bool.Parse( uxFixedShippingCostDrop.SelectedValue );
product.FreeShippingCost = uxIsFreeShippingCostCheck.Checked;
product.Manufacturer = uxManufacturerDrop.SelectedValue;
product.Keywords = uxKeywordsText.Text;
product.Other1 = uxOtherOneText.Text;
product.Other2 = uxOtherTwoText.Text;
product.Other3 = uxOtherThreeText.Text;
product.Other4 = uxOtherFourText.Text;
product.Other5 = uxOtherFiveText.Text;
if (uxIsAffiliate.Visible)
{
product.IsAffiliate = uxIsAffiliate.Checked;
}
product.IsTodaySpecial = uxIsTodaySpecialCheck.Checked;
product.IsCustomPrice = uxUseCustomPriceCheck.Checked;
if (!String.IsNullOrEmpty( uxMinimumQuantityText.Text ) && !String.IsNullOrEmpty( uxMaximumQuantityText.Text ))
{
product.MinQuantity = ConvertUtilities.ToInt32( uxMinimumQuantityText.Text );
product.MaxQuantity = ConvertUtilities.ToInt32( uxMaximumQuantityText.Text );
}
product.IsDownloadable = uxDownloadableCheck.Checked;
product.DownloadPath = uxDownloadPathText.Text;
product.IsEnabled = uxIsEnabledCheck.Checked;
product.RelatedProducts = uxRelatedProducts.Text.Trim().Replace( " ", "" );
product.MerchantRating = ConvertProductRatingForDatabase();
product.DiscountGroupID = uxQuantityDiscount.DiscountGounpID;
product.ManufacturerPartNumber = uxManufacturerPartNumberText.Text;
product.Upc = uxUpcText.Text;
product.IsCallForPrice = uxIsCallForPriceCheck.Checked;
if (uxCustomPriceTR.Visible)
{
product.IsCustomPrice = uxUseCustomPriceCheck.Checked;
/* Save Product Custom Price */
ProductCustomPrice productCustomPrice = new ProductCustomPrice();
productCustomPrice.DefaultPrice = ConvertUtilities.ToDecimal( CreateNonEmptyNumber( uxDefaultPriceText.Text ) );
productCustomPrice.MinimumPrice = ConvertUtilities.ToDecimal( CreateNonEmptyNumber( uxMinimumPriceText.Text ) );
product.ProductCustomPrice = productCustomPrice;
}
else
{
product.IsCustomPrice = false;
}
product.TaxClassID = uxTaxClassDrop.SelectedValue;
product.UseInventory = uxInventoryAndOption.IsUseInventory;
if (ConvertUtilities.ToBoolean( uxOverrideProductLayoutDrop.SelectedValue ))
{
product.ProductDetailsLayoutPath = uxProductDetailsLayoutPathDrop.SelectedValue;
uxProductDetailsLayoutPathPanel.Style["display"] = "";
}
else
{
product.ProductDetailsLayoutPath = String.Empty;
uxProductDetailsLayoutPathPanel.Style["display"] = "none";
}
if (uxRmaTR.Visible)
{
product.ReturnTime = ConvertUtilities.ToInt32( uxRmaText.Text );
}
else
{
product.ReturnTime = 0;
}
product.IsDynamicProductKitPrice = uxIsDynamicProductKitPriceCheck.Checked;
product.IsDynamicProductKitWeight = uxIsDynamicProductKitWeightCheck.Checked;
if (uxCrateDateCalendar.Visible)
{
product.CreateDate = uxCrateDateCalendar.SelectedDate;
}
product.Length = ConvertUtilities.ToDouble( CreateNonEmptyNumber( uxLengthText.Text ) );
product.Width = ConvertUtilities.ToDouble( CreateNonEmptyNumber( uxWidthText.Text ) );
product.Height = ConvertUtilities.ToDouble( CreateNonEmptyNumber( uxHeightText.Text ) );
return product;
}
public void IsDownloadableEnabled( bool isEnabled )
{
if (!isEnabled)
{
uxDownloadableCheck.Checked = false;
uxDownloadableCheck.Enabled = false;
}
else
{
uxDownloadableCheck.Enabled = true;
}
}
public void SetEnabledControlsForProductSubscription( bool isEnabled )
{
if (!isEnabled)
{
uxInventoryAndOption.IsProductOptionVisible( false );
uxInventoryAndOption.IsStockOptionVisible( false );
uxIsFreeShippingCostCheck.Checked = false;
uxIsFreeShippingCostCheck.Enabled = false;
uxFixedShippingCostDrop.SelectedValue = "False";
uxFixedShippingCostDrop.Enabled = false;
}
else
{
uxInventoryAndOption.IsProductOptionVisible( true );
uxInventoryAndOption.IsStockOptionVisible( true );
uxIsFreeShippingCostCheck.Enabled = true;
uxFixedShippingCostDrop.Enabled = true;
}
}
public void SetEnabledWeightText( bool enable )
{
uxWeightText.Enabled = enable;
}
public void SetEnabledMinMaxQTY( bool enable )
{
uxMinimumQuantityText.Enabled = enable;
uxMaximumQuantityText.Enabled = enable;
}
public void SetMaxQuantity( int max )
{
uxMaximumQuantityText.Text = max.ToString();
}
public void SetMinQuantity( int min )
{
uxMinimumQuantityText.Text = min.ToString();
}
public void SetEnabledQuantityDiscount( bool enabled )
{
uxQuantityDiscount.IsQuantityDiscountEnabled( enabled );
}
public void SetVisibleSpecificationControls()
{
if (uxSpecificationGroupDrop.SelectedValue != "0")
{
uxSpecificationItemTR.Visible = true;
IList<SpecificationGroup> groups = DataAccessContext.SpecificationGroupRepository.GetAll( CurrentCulture );
foreach (SpecificationGroup group in groups)
{
Panel rowPanel = (Panel) uxSpecificationItemTR.FindControl( "RowPanelSpecificationGroup" + group.SpecificationGroupID );
if (group.SpecificationGroupID == uxSpecificationGroupDrop.SelectedValue)
rowPanel.Visible = true;
else
rowPanel.Visible = false;
}
}
else
uxSpecificationItemTR.Visible = false;
}
public void SetVisibleRmaControl()
{
if (DataAccessContext.Configurations.GetBoolValue( "EnableRMA" ))
{
uxRmaTR.Visible = true;
}
else
{
uxRmaTR.Visible = false;
}
}
public void SetFixedShippingCostVisibility( bool isGiftCertificate )
{
if (uxDownloadableCheck.Checked || isGiftCertificate)
{
uxFixedShippingCostTR.Visible = false;
uxShippingCostTR.Visible = false;
uxIsFreeShippingCostTR.Visible = false;
}
else
{
uxIsFreeShippingCostTR.Visible = true;
uxFixedShippingCostTR.Visible = true;
uxShippingCostTR.Visible = true;
if (uxIsFreeShippingCostCheck.Checked)
{
uxFixedShippingCostTR.Visible = false;
uxShippingCostTR.Visible = false;
}
else
{
if (ConvertUtilities.ToBoolean( uxFixedShippingCostDrop.SelectedValue ))
uxShippingCostTR.Visible = true;
else
uxShippingCostTR.Visible = false;
}
}
}
public bool IsFixPrice( bool isFixedPrice, bool isGiftCertificate, bool isRecurring, bool isCallForPrice )
{
bool isFixPrice = true;
//check donation display with gift certificate
if (isGiftCertificate || isRecurring)
{
IsProductCustomPrice( isGiftCertificate, isRecurring, isCallForPrice );
if (isFixedPrice)
{
if (isCustomPrice)
{
RelatedPricePanelShow();
}
}
else
{
RelatedPricePanelHide();
isFixPrice = false;
}
}
else
{
IsProductCustomPrice( isGiftCertificate, isRecurring, isCallForPrice );
if (isCustomPrice)
{
RelatedPricePanelHide();
}
else
{
RelatedPricePanelShow();
}
}
return isFixPrice;
}
public bool IsProductSkuExist()
{
string sku = uxSkuText.Text;
string productID = DataAccessContext.ProductRepository.GetProductIDBySku( sku );
if (String.IsNullOrEmpty( productID ))
{
return false;
}
else
{
return true;
}
}
// check donation display with gift certificate
private void IsProductCustomPrice( bool isGiftCertificate, bool isRecurring, bool isCallForPrice )
{
if (isGiftCertificate || isRecurring || isCallForPrice)
{
uxUseCustomPriceTR.Visible = false;
uxCustomPriceTR.Visible = false;
}
else
{
uxUseCustomPriceTR.Visible = true;
uxCustomPriceTR.Visible = isCustomPrice;
uxRetailPriceRequiredValidator.Enabled = false;
uxPriceRequiredValidator.Enabled = false;
}
}
private void RelatedPricePanelHide()
{
uxPriceTR.Visible = false;
uxRetailPriceTR.Style.Add( "display", "none" );
uxWholesalePriceTR.Style.Add( "display", "none" );
uxWholesalePrice2TR.Style.Add( "display", "none" );
uxWholesalePrice3TR.Style.Add( "display", "none" );
}
private void RelatedPricePanelShow()
{
uxPriceTR.Visible = true;
uxRetailPriceTR.Style.Add( "display", "" );
uxWholesalePriceTR.Style.Add( "display", "" );
uxWholesalePrice2TR.Style.Add( "display", "" );
uxWholesalePrice3TR.Style.Add( "display", "" );
}
// End Donation
private TextBox PopulateTextbox( string specItemID )
{
TextBox txtBox = new TextBox();
txtBox.ID = "SpecificationItem" + specItemID;
txtBox.CssClass = "TextBox";
return txtBox;
}
private DropDownList PopulateDropDownList( string specItemID )
{
DropDownList dropList = new DropDownList();
dropList.ID = "SpecificationItem" + specItemID;
dropList.CssClass = "DropDown";
dropList.DataSource = DataAccessContext.SpecificationItemValueRepository.GetBySpecificationItemID( CurrentCulture, specItemID );
dropList.DataTextField = "DisplayValue";
dropList.DataValueField = "Value";
dropList.DataBind();
dropList.Items.Insert( 0, new ListItem( "None", "" ) );
return dropList;
}
private ListBox PopulateMultiSelect( string specItemID )
{
ListBox listBox = new ListBox();
listBox.SelectionMode = ListSelectionMode.Multiple;
listBox.ID = "SpecificationItem" + specItemID;
listBox.CssClass = "MultiCatalogInnerListBox";
listBox.DataSource = DataAccessContext.SpecificationItemValueRepository.GetBySpecificationItemID( CurrentCulture, specItemID );
listBox.DataTextField = "DisplayValue";
listBox.DataValueField = "Value";
listBox.DataBind();
return listBox;
}
public void PopulateShippingCostControl()
{
int i = 0;
IList<ShippingOption> nonRealTimeShippings = DataAccessContext.ShippingOptionRepository.GetShipping(
CurrentCulture, BoolFilter.ShowFalse );
for (int rowIndex = 0; rowIndex < nonRealTimeShippings.Count; rowIndex++)
{
ShippingOption shippingOption = nonRealTimeShippings[rowIndex];
Panel rowPanel = new Panel();
rowPanel.ID = "RowPanel" + shippingOption.ShippingID;
rowPanel.CssClass = "CommonRowStyle";
uxShippingCostTR.Controls.Add( rowPanel );
Panel panel = new Panel();
panel.ID = "NamePanel" + shippingOption.ShippingID;
panel.CssClass = "Label";
Label label = new Label();
label.ID = "NameLabel" + shippingOption.ShippingID;
label.Text = " " + shippingOption.ShippingName;
label.CssClass = " BulletLabel";
panel.Controls.Add( label );
rowPanel.Controls.Add( panel );
TextBox txtBox = new TextBox();
txtBox.ID = shippingOption.ShippingID;
txtBox.CssClass = "TextBox";
rowPanel.Controls.Add( txtBox );
panel = new Panel();
panel.CssClass = "Clear";
rowPanel.Controls.Add( panel );
label = new Label();
label.ID = "Label" + shippingOption.ShippingID; ;
label.Text += "";
rowPanel.Controls.Add( label );
i++;
}
}
public void PopulateSpecificationItemControls()
{
uxSpecificationItemTR.Controls.Clear();
IList<SpecificationGroup> groups = DataAccessContext.SpecificationGroupRepository.GetAll( CurrentCulture );
foreach (SpecificationGroup group in groups)
{
IList<SpecificationItem> items = DataAccessContext.SpecificationItemRepository.GetBySpecificationGroupID(
CurrentCulture, group.SpecificationGroupID );
Panel rowPanel = new Panel();
rowPanel.ID = "RowPanelSpecificationGroup" + group.SpecificationGroupID;
rowPanel.CssClass = "CommonRowStyle";
foreach (SpecificationItem item in items)
{
Label label = new Label();
label.ID = "SpecificationNameLabel" + item.SpecificationItemID;
label.Text = " " + item.Name;
label.CssClass = " BulletLabel";
rowPanel.Controls.Add( label );
Control specItemControl = new Control();
switch (item.Type)
{
case SpecificationItemControlType.Textbox:
specItemControl = (Control) PopulateTextbox( item.SpecificationItemID );
break;
case SpecificationItemControlType.DropDownList:
specItemControl = (Control) PopulateDropDownList( item.SpecificationItemID );
break;
case SpecificationItemControlType.MultiSelect:
specItemControl = (Control) PopulateMultiSelect( item.SpecificationItemID );
break;
default:
specItemControl = (Control) PopulateTextbox( item.SpecificationItemID );
break;
}
rowPanel.Controls.Add( specItemControl );
Panel panel = new Panel();
panel.CssClass = "Clear";
rowPanel.Controls.Add( panel );
}
uxSpecificationItemTR.Controls.Add( rowPanel );
}
SetVisibleSpecificationControls();
}
public void RestoreSessionData()
{
if (IsRestoreSession)
{
InputControlRecorder inputRecorder = (InputControlRecorder) Session[ProductDetailsSessionName];
inputRecorder.Restore( this );
PopulateStockOptionControl();
inputRecorder.Restore( this );
Session[ProductDetailsSessionName] = null;
if (!_isEditMode)
{
if (!String.IsNullOrEmpty( ProductImageData.SecondaryImagePath ))
uxImageSecondaryText.Text = ProductImageData.SecondaryImagePath;
}
else
{
uxImageSecondaryText.Text = DataAccessContext.ProductRepository.GetOne( CurrentCulture, CurrentID, new StoreRetriever().GetCurrentStoreID() ).ImageSecondary;
}
uxProductImage.ImageUrl = AdminConfig.UrlFront + uxImageSecondaryText.Text +
"?State=" + RandomUtilities.RandomNumberNDigits( 3 );
}
}
public void SetOptionList()
{
uxInventoryAndOption.SetOptionList();
}
public void SelectOptionList( Product product )
{
uxInventoryAndOption.SelectOptionList( product );
}
public bool VerifyInputListOption()
{
return uxInventoryAndOption.VerifyInputListOption();
}
public void AddOptionGroup( Product product )
{
uxInventoryAndOption.AddOptionGroup( product );
}
public void CreateStockOption( Product product )
{
uxInventoryAndOption.CreateStockOption( product );
}
public void UpdateProductShippingCost( Product product )
{
IList<ShippingOption> shippingList =
DataAccessContext.ShippingOptionRepository.GetShipping( CurrentCulture, BoolFilter.ShowFalse );
for (int i = 0; i < shippingList.Count; i++)
{
TextBox txt = (TextBox) uxShippingCostTR.FindControl( shippingList[i].ShippingID );
ProductShippingCost productShippingCost = new ProductShippingCost();
productShippingCost.ShippingID = shippingList[i].ShippingID;
productShippingCost.FixedShippingCost = ConvertUtilities.ToDecimal( txt.Text );
product.ProductShippingCosts.Add( productShippingCost );
}
}
public void HideUploadButton()
{
uxOptionalUploadLinkButton.Visible = false;
uxDownloadPathLinkButton.Visible = false;
}
public void PopulateDropdown()
{
string[] fileList = Directory.GetFiles( Server.MapPath( SystemConst.LayoutProductDetailsPath ) );
uxProductDetailsLayoutPathDrop.Items.Clear();
uxProductDetailsLayoutPathDrop.Items.Add( new ListItem( "Plese Select...", "" ) );
foreach (string item in fileList)
{
string itemName = item.Substring( item.LastIndexOf( "\\" ) + 1 );
if (itemName.Substring( itemName.LastIndexOf( "." ) + 1 ) == "ascx")
{
uxProductDetailsLayoutPathDrop.Items.Add( new ListItem( itemName, itemName ) );
}
}
uxProductDetailsLayoutPathDrop.SelectedValue = DataAccessContext.Configurations.GetValueNoThrow( "DefaultProductDetailsLayout" );
}
public void HideStockOption()
{
uxInventoryAndOption.HideStockOption();
}
public void SetWholesaleVisible( bool isFixedPrice, bool isGiftCertificate, bool isRecurring )
{
if (WholesaleMode == 1 && IsFixPrice( isFixedPrice, isGiftCertificate, isRecurring, IsCallForPrice ))
{
if (WholesaleLevel >= 1)
uxWholesalePriceTR.Visible = true;
else
uxWholesalePriceTR.Visible = false;
if (WholesaleLevel >= 2)
uxWholesalePrice2TR.Visible = true;
else
uxWholesalePrice2TR.Visible = false;
if (WholesaleLevel >= 3)
uxWholesalePrice3TR.Visible = true;
else
uxWholesalePrice3TR.Visible = false;
}
else
{
uxWholesalePriceTR.Visible = false;
uxWholesalePrice2TR.Visible = false;
uxWholesalePrice3TR.Visible = false;
}
}
public void SetRetailPriceVisible( bool isFixedPrice, bool isGiftCertificate, bool isRecurring )
{
if (RetailPriceMode && IsFixPrice( isFixedPrice, isGiftCertificate, isRecurring, IsCallForPrice ))
uxRetailPriceTR.Visible = true;
else
uxRetailPriceTR.Visible = false;
}
public void SetTaxClassVisible( bool isVisible )
{
uxTaxClassTR.Visible = isVisible;
}
public void SetProductRatingVisible( bool isGiftCertificate )
{
if (DataAccessContext.Configurations.GetBoolValue( "MerchantRating" )
&& !isGiftCertificate)
{
uxProductRatingRow.Visible = true;
}
else
{
uxProductRatingRow.Visible = false;
uxProductRating.Text = String.Empty;
}
}
public void SetProductKitControlVisible( bool isProductKit )
{
uxIsDynamicProductKitPricePanel.Visible = isProductKit;
uxIsDynamicProductKitWeightPanel.Visible = isProductKit;
if (!isProductKit)
{
uxIsDynamicProductKitPriceCheck.Checked = false;
uxIsDynamicProductKitWeightCheck.Checked = false;
}
}
public void SetStockWhenAdd()
{
uxInventoryAndOption.SetStockWhenAdd();
}
public void InitDiscountDrop()
{
uxQuantityDiscountTR.Visible = true;
}
public void InitTaxClassDrop()
{
uxTaxClassDrop.DataSource = DataAccessContext.TaxClassRepository.GetAll( "TaxClassID" );
uxTaxClassDrop.DataTextField = "TaxClassName";
uxTaxClassDrop.DataValueField = "TaxClassID";
uxTaxClassDrop.DataBind();
uxTaxClassDrop.Items.Insert( 0, new ListItem( "None", "0" ) );
}
public void SetProductSpecifications( Product product )
{
product.ProductSpecifications = new List<ProductSpecification>();
if (uxSpecificationGroupDrop.SelectedValue != "0")
{
IList<SpecificationItem> items = DataAccessContext.SpecificationItemRepository.GetBySpecificationGroupID(
CurrentCulture, uxSpecificationGroupDrop.SelectedValue );
Panel rowPanel = (Panel) uxSpecificationItemTR.FindControl( "RowPanelSpecificationGroup" + uxSpecificationGroupDrop.SelectedValue );
foreach (SpecificationItem item in items)
{
ProductSpecification productSpecification = new ProductSpecification();
productSpecification.ProductID = CurrentID;
productSpecification.SpecificationItemID = item.SpecificationItemID;
switch (item.Type)
{
case SpecificationItemControlType.Textbox:
TextBox text = (TextBox) rowPanel.FindControl( "SpecificationItem" + item.SpecificationItemID );
productSpecification.Value = text.Text;
product.ProductSpecifications.Add( productSpecification );
break;
case SpecificationItemControlType.DropDownList:
DropDownList dropDown = (DropDownList) rowPanel.FindControl( "SpecificationItem" + item.SpecificationItemID );
productSpecification.Value = dropDown.SelectedValue;
product.ProductSpecifications.Add( productSpecification );
break;
case SpecificationItemControlType.MultiSelect:
ListBox multiSelect = (ListBox) rowPanel.FindControl( "SpecificationItem" + item.SpecificationItemID );
string selectedItem = string.Empty;
IList<ProductSpecification> productSpecList = new List<ProductSpecification>();
foreach (int index in multiSelect.GetSelectedIndices())
{
productSpecification = new ProductSpecification();
productSpecification.ProductID = CurrentID;
productSpecification.SpecificationItemID = item.SpecificationItemID;
productSpecification.Value = multiSelect.Items[index].Value;
productSpecList.Add( productSpecification );
}
foreach (ProductSpecification spec in productSpecList)
{
product.ProductSpecifications.Add( spec );
}
break;
default:
TextBox textDefault = (TextBox) rowPanel.FindControl( "SpecificationItem" + item.SpecificationItemID );
productSpecification.Value = textDefault.Text;
product.ProductSpecifications.Add( productSpecification );
break;
}
}
}
}
public bool IsCallForPrice
{
get { return uxIsCallForPriceCheck.Checked; }
}
#endregion
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities
{
using System.ComponentModel;
using System.Collections.Generic;
public sealed class ActivityAction : ActivityDelegate
{
static readonly IList<RuntimeDelegateArgument> EmptyDelegateParameters = new List<RuntimeDelegateArgument>(0);
public ActivityAction()
{
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
return ActivityAction.EmptyDelegateParameters;
}
}
public sealed class ActivityAction<T> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T> Argument
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(1)
{
{ new RuntimeDelegateArgument(ActivityDelegate.ArgumentName, typeof(T), ArgumentDirection.In, this.Argument) }
};
return result;
}
}
public sealed class ActivityAction<T1, T2> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(2)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) }
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(3)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) }
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(4)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) }
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4, T5> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T5> Argument5
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(5)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument5Name, typeof(T5), ArgumentDirection.In, this.Argument5) }
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4, T5, T6> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T5> Argument5
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T6> Argument6
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(6)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument5Name, typeof(T5), ArgumentDirection.In, this.Argument5) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument6Name, typeof(T6), ArgumentDirection.In, this.Argument6) },
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4, T5, T6, T7> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T5> Argument5
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T6> Argument6
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T7> Argument7
{
get;
set;
}
[DefaultValue(null)]
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(7)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument5Name, typeof(T5), ArgumentDirection.In, this.Argument5) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument6Name, typeof(T6), ArgumentDirection.In, this.Argument6) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument7Name, typeof(T7), ArgumentDirection.In, this.Argument7) },
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T5> Argument5
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T6> Argument6
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T7> Argument7
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T8> Argument8
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(8)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument5Name, typeof(T5), ArgumentDirection.In, this.Argument5) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument6Name, typeof(T6), ArgumentDirection.In, this.Argument6) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument7Name, typeof(T7), ArgumentDirection.In, this.Argument7) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument8Name, typeof(T8), ArgumentDirection.In, this.Argument8) },
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T5> Argument5
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T6> Argument6
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T7> Argument7
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T8> Argument8
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T9> Argument9
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(9)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument5Name, typeof(T5), ArgumentDirection.In, this.Argument5) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument6Name, typeof(T6), ArgumentDirection.In, this.Argument6) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument7Name, typeof(T7), ArgumentDirection.In, this.Argument7) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument8Name, typeof(T8), ArgumentDirection.In, this.Argument8) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument9Name, typeof(T9), ArgumentDirection.In, this.Argument9) },
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T5> Argument5
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T6> Argument6
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T7> Argument7
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T8> Argument8
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T9> Argument9
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T10> Argument10
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(10)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument5Name, typeof(T5), ArgumentDirection.In, this.Argument5) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument6Name, typeof(T6), ArgumentDirection.In, this.Argument6) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument7Name, typeof(T7), ArgumentDirection.In, this.Argument7) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument8Name, typeof(T8), ArgumentDirection.In, this.Argument8) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument9Name, typeof(T9), ArgumentDirection.In, this.Argument9) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument10Name, typeof(T10), ArgumentDirection.In, this.Argument10) },
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T5> Argument5
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T6> Argument6
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T7> Argument7
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T8> Argument8
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T9> Argument9
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T10> Argument10
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T11> Argument11
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(11)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument5Name, typeof(T5), ArgumentDirection.In, this.Argument5) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument6Name, typeof(T6), ArgumentDirection.In, this.Argument6) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument7Name, typeof(T7), ArgumentDirection.In, this.Argument7) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument8Name, typeof(T8), ArgumentDirection.In, this.Argument8) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument9Name, typeof(T9), ArgumentDirection.In, this.Argument9) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument10Name, typeof(T10), ArgumentDirection.In, this.Argument10) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument11Name, typeof(T11), ArgumentDirection.In, this.Argument11) },
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T5> Argument5
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T6> Argument6
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T7> Argument7
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T8> Argument8
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T9> Argument9
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T10> Argument10
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T11> Argument11
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T12> Argument12
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(12)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument5Name, typeof(T5), ArgumentDirection.In, this.Argument5) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument6Name, typeof(T6), ArgumentDirection.In, this.Argument6) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument7Name, typeof(T7), ArgumentDirection.In, this.Argument7) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument8Name, typeof(T8), ArgumentDirection.In, this.Argument8) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument9Name, typeof(T9), ArgumentDirection.In, this.Argument9) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument10Name, typeof(T10), ArgumentDirection.In, this.Argument10) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument11Name, typeof(T11), ArgumentDirection.In, this.Argument11) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument12Name, typeof(T12), ArgumentDirection.In, this.Argument12) },
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T5> Argument5
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T6> Argument6
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T7> Argument7
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T8> Argument8
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T9> Argument9
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T10> Argument10
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T11> Argument11
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T12> Argument12
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T13> Argument13
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(13)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument5Name, typeof(T5), ArgumentDirection.In, this.Argument5) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument6Name, typeof(T6), ArgumentDirection.In, this.Argument6) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument7Name, typeof(T7), ArgumentDirection.In, this.Argument7) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument8Name, typeof(T8), ArgumentDirection.In, this.Argument8) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument9Name, typeof(T9), ArgumentDirection.In, this.Argument9) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument10Name, typeof(T10), ArgumentDirection.In, this.Argument10) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument11Name, typeof(T11), ArgumentDirection.In, this.Argument11) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument12Name, typeof(T12), ArgumentDirection.In, this.Argument12) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument13Name, typeof(T13), ArgumentDirection.In, this.Argument13) }
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T5> Argument5
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T6> Argument6
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T7> Argument7
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T8> Argument8
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T9> Argument9
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T10> Argument10
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T11> Argument11
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T12> Argument12
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T13> Argument13
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T14> Argument14
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(14)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument5Name, typeof(T5), ArgumentDirection.In, this.Argument5) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument6Name, typeof(T6), ArgumentDirection.In, this.Argument6) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument7Name, typeof(T7), ArgumentDirection.In, this.Argument7) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument8Name, typeof(T8), ArgumentDirection.In, this.Argument8) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument9Name, typeof(T9), ArgumentDirection.In, this.Argument9) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument10Name, typeof(T10), ArgumentDirection.In, this.Argument10) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument11Name, typeof(T11), ArgumentDirection.In, this.Argument11) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument12Name, typeof(T12), ArgumentDirection.In, this.Argument12) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument13Name, typeof(T13), ArgumentDirection.In, this.Argument13) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument14Name, typeof(T14), ArgumentDirection.In, this.Argument14) }
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T5> Argument5
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T6> Argument6
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T7> Argument7
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T8> Argument8
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T9> Argument9
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T10> Argument10
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T11> Argument11
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T12> Argument12
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T13> Argument13
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T14> Argument14
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T15> Argument15
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(15)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument5Name, typeof(T5), ArgumentDirection.In, this.Argument5) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument6Name, typeof(T6), ArgumentDirection.In, this.Argument6) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument7Name, typeof(T7), ArgumentDirection.In, this.Argument7) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument8Name, typeof(T8), ArgumentDirection.In, this.Argument8) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument9Name, typeof(T9), ArgumentDirection.In, this.Argument9) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument10Name, typeof(T10), ArgumentDirection.In, this.Argument10) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument11Name, typeof(T11), ArgumentDirection.In, this.Argument11) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument12Name, typeof(T12), ArgumentDirection.In, this.Argument12) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument13Name, typeof(T13), ArgumentDirection.In, this.Argument13) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument14Name, typeof(T14), ArgumentDirection.In, this.Argument14) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument15Name, typeof(T15), ArgumentDirection.In, this.Argument15) }
};
return result;
}
}
public sealed class ActivityAction<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> : ActivityDelegate
{
public ActivityAction()
{
}
[DefaultValue(null)]
public DelegateInArgument<T1> Argument1
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T2> Argument2
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T3> Argument3
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T4> Argument4
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T5> Argument5
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T6> Argument6
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T7> Argument7
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T8> Argument8
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T9> Argument9
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T10> Argument10
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T11> Argument11
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T12> Argument12
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T13> Argument13
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T14> Argument14
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T15> Argument15
{
get;
set;
}
[DefaultValue(null)]
public DelegateInArgument<T16> Argument16
{
get;
set;
}
internal override IList<RuntimeDelegateArgument> InternalGetRuntimeDelegateArguments()
{
IList<RuntimeDelegateArgument> result = new List<RuntimeDelegateArgument>(16)
{
{ new RuntimeDelegateArgument(ActivityDelegate.Argument1Name, typeof(T1), ArgumentDirection.In, this.Argument1) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument2Name, typeof(T2), ArgumentDirection.In, this.Argument2) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument3Name, typeof(T3), ArgumentDirection.In, this.Argument3) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument4Name, typeof(T4), ArgumentDirection.In, this.Argument4) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument5Name, typeof(T5), ArgumentDirection.In, this.Argument5) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument6Name, typeof(T6), ArgumentDirection.In, this.Argument6) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument7Name, typeof(T7), ArgumentDirection.In, this.Argument7) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument8Name, typeof(T8), ArgumentDirection.In, this.Argument8) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument9Name, typeof(T9), ArgumentDirection.In, this.Argument9) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument10Name, typeof(T10), ArgumentDirection.In, this.Argument10) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument11Name, typeof(T11), ArgumentDirection.In, this.Argument11) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument12Name, typeof(T12), ArgumentDirection.In, this.Argument12) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument13Name, typeof(T13), ArgumentDirection.In, this.Argument13) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument14Name, typeof(T14), ArgumentDirection.In, this.Argument14) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument15Name, typeof(T15), ArgumentDirection.In, this.Argument15) },
{ new RuntimeDelegateArgument(ActivityDelegate.Argument16Name, typeof(T16), ArgumentDirection.In, this.Argument16) }
};
return result;
}
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Parallel\Testing\Tcl\TestCutMaterial.tcl
// output file is AVTestCutMaterial.cs
/// <summary>
/// The testing class derived from AVTestCutMaterial
/// </summary>
public class AVTestCutMaterialClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVTestCutMaterial(String [] argv)
{
//Prefix Content is: ""
// Lets create a data set.[]
data = new vtkImageData();
data.SetExtent((int)0,(int)31,(int)0,(int)31,(int)0,(int)31);
data.SetScalarTypeToFloat();
// First the data array:[]
gauss = new vtkImageGaussianSource();
gauss.SetWholeExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30);
gauss.SetCenter((double)18,(double)12,(double)20);
gauss.SetMaximum((double)1.0);
gauss.SetStandardDeviation((double)10.0);
gauss.Update();
a = gauss.GetOutput().GetPointData().GetScalars();
a.SetName((string)"Gauss");
data.GetCellData().SetScalars((vtkDataArray)a);
//skipping Delete gauss
// Now the material array:[]
ellipse = new vtkImageEllipsoidSource();
ellipse.SetWholeExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30);
ellipse.SetCenter((double)11,(double)12,(double)13);
ellipse.SetRadius((double)5,(double)9,(double)13);
ellipse.SetInValue((double)1);
ellipse.SetOutValue((double)0);
ellipse.SetOutputScalarTypeToInt();
ellipse.Update();
m = ellipse.GetOutput().GetPointData().GetScalars();
m.SetName((string)"Material");
data.GetCellData().AddArray((vtkAbstractArray)m);
//skipping Delete ellipse
cut = new vtkCutMaterial();
cut.SetInput((vtkDataObject)data);
cut.SetMaterialArrayName((string)"Material");
cut.SetMaterial((int)1);
cut.SetArrayName((string)"Gauss");
cut.SetUpVector((double)1,(double)0,(double)0);
cut.Update();
mapper2 = vtkPolyDataMapper.New();
mapper2.SetInputConnection((vtkAlgorithmOutput)cut.GetOutputPort());
mapper2.SetScalarRange((double)0,(double)1);
//apper2 SetScalarModeToUseCellFieldData[]
//apper2 SetColorModeToMapScalars []
//apper2 ColorByArrayComponent "vtkGhostLevels" 0[]
actor2 = new vtkActor();
actor2.SetMapper((vtkMapper)mapper2);
actor2.SetPosition((double)1.5,(double)0,(double)0);
ren = vtkRenderer.New();
ren.AddActor((vtkProp)actor2);
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren);
p = cut.GetCenterPoint();
n = cut.GetNormal();
cam = ren.GetActiveCamera();
cam.SetFocalPoint(p[0],p[1],p[2]);
cam.SetViewUp(cut.GetUpVector()[0], cut.GetUpVector()[1], cut.GetUpVector()[2]);
cam.SetPosition(
(double)(lindex(n,0))+(double)(lindex(p,0)),
(double)(lindex(n,1))+(double)(lindex(p,1)),
(double)(lindex(n,2))+(double)(lindex(p,2)));
ren.ResetCamera();
iren = vtkRenderWindowInteractor.New();
iren.SetRenderWindow(renWin);
iren.Initialize();
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkImageData data;
static vtkImageGaussianSource gauss;
static vtkDataArray a;
static vtkImageEllipsoidSource ellipse;
static vtkDataArray m;
static vtkCutMaterial cut;
static vtkPolyDataMapper mapper2;
static vtkActor actor2;
static vtkRenderer ren;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static double[] p;
static double[] n;
static vtkCamera cam;
/// <summary>
/// Returns the variable in the index [i] of the System.Array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="i"></param>
public static Object lindex(System.Array arr, int i)
{
return arr.GetValue(i);
}
/// <summary>
/// Returns the variable in the index [index] of the array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static double lindex(IntPtr arr, int index)
{
double[] destination = new double[index + 1];
System.Runtime.InteropServices.Marshal.Copy(arr, destination, 0, index + 1);
return destination[index];
}
/// <summary>
/// Returns the variable in the index [index] of the vtkLookupTable [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static long lindex(vtkLookupTable arr, double index)
{
return arr.GetIndex(index);
}
/// <summary>
/// Returns the substring ([index], [index]+1) in the string [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static int lindex(String arr, int index)
{
string[] str = arr.Split(new char[]{' '});
return System.Int32.Parse(str[index]);
}
/// <summary>
/// Returns the index [index] in the int array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static int lindex(int[] arr, int index)
{
return arr[index];
}
/// <summary>
/// Returns the index [index] in the float array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static float lindex(float[] arr, int index)
{
return arr[index];
}
/// <summary>
/// Returns the index [index] in the double array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static double lindex(double[] arr, int index)
{
return arr[index];
}
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkImageData Getdata()
{
return data;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setdata(vtkImageData toSet)
{
data = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkImageGaussianSource Getgauss()
{
return gauss;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setgauss(vtkImageGaussianSource toSet)
{
gauss = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataArray Geta()
{
return a;
}
///<summary> A Set Method for Static Variables </summary>
public static void Seta(vtkDataArray toSet)
{
a = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkImageEllipsoidSource Getellipse()
{
return ellipse;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setellipse(vtkImageEllipsoidSource toSet)
{
ellipse = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkDataArray Getm()
{
return m;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setm(vtkDataArray toSet)
{
m = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCutMaterial Getcut()
{
return cut;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcut(vtkCutMaterial toSet)
{
cut = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper Getmapper2()
{
return mapper2;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmapper2(vtkPolyDataMapper toSet)
{
mapper2 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor Getactor2()
{
return actor2;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setactor2(vtkActor toSet)
{
actor2 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren()
{
return ren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren(vtkRenderer toSet)
{
ren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double[] Getp()
{
return p;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setp(double[] toSet)
{
p = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double[] Getn()
{
return n;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setn(double[] toSet)
{
n = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcam()
{
return cam;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcam(vtkCamera toSet)
{
cam = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(data!= null){data.Dispose();}
if(gauss!= null){gauss.Dispose();}
if(a!= null){a.Dispose();}
if(ellipse!= null){ellipse.Dispose();}
if(m!= null){m.Dispose();}
if(cut!= null){cut.Dispose();}
if(mapper2!= null){mapper2.Dispose();}
if(actor2!= null){actor2.Dispose();}
if(ren!= null){ren.Dispose();}
if(renWin!= null){renWin.Dispose();}
if (iren != null) { iren.Dispose(); }
}
}
//--- end of script --//
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Steamworks.Data;
namespace Steamworks
{
internal unsafe class ISteamUtils : SteamInterface
{
internal ISteamUtils( bool IsGameServer )
{
SetupInterface( IsGameServer );
}
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_SteamUtils_v010", CallingConvention = Platform.CC)]
internal static extern IntPtr SteamAPI_SteamUtils_v010();
public override IntPtr GetUserInterfacePointer() => SteamAPI_SteamUtils_v010();
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_SteamGameServerUtils_v010", CallingConvention = Platform.CC)]
internal static extern IntPtr SteamAPI_SteamGameServerUtils_v010();
public override IntPtr GetServerInterfacePointer() => SteamAPI_SteamGameServerUtils_v010();
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetSecondsSinceAppActive", CallingConvention = Platform.CC)]
private static extern uint _GetSecondsSinceAppActive( IntPtr self );
#endregion
internal uint GetSecondsSinceAppActive()
{
var returnValue = _GetSecondsSinceAppActive( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetSecondsSinceComputerActive", CallingConvention = Platform.CC)]
private static extern uint _GetSecondsSinceComputerActive( IntPtr self );
#endregion
internal uint GetSecondsSinceComputerActive()
{
var returnValue = _GetSecondsSinceComputerActive( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetConnectedUniverse", CallingConvention = Platform.CC)]
private static extern Universe _GetConnectedUniverse( IntPtr self );
#endregion
internal Universe GetConnectedUniverse()
{
var returnValue = _GetConnectedUniverse( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetServerRealTime", CallingConvention = Platform.CC)]
private static extern uint _GetServerRealTime( IntPtr self );
#endregion
internal uint GetServerRealTime()
{
var returnValue = _GetServerRealTime( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetIPCountry", CallingConvention = Platform.CC)]
private static extern Utf8StringPointer _GetIPCountry( IntPtr self );
#endregion
internal string GetIPCountry()
{
var returnValue = _GetIPCountry( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetImageSize", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetImageSize( IntPtr self, int iImage, ref uint pnWidth, ref uint pnHeight );
#endregion
internal bool GetImageSize( int iImage, ref uint pnWidth, ref uint pnHeight )
{
var returnValue = _GetImageSize( Self, iImage, ref pnWidth, ref pnHeight );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetImageRGBA", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetImageRGBA( IntPtr self, int iImage, [In,Out] byte[] pubDest, int nDestBufferSize );
#endregion
internal bool GetImageRGBA( int iImage, [In,Out] byte[] pubDest, int nDestBufferSize )
{
var returnValue = _GetImageRGBA( Self, iImage, pubDest, nDestBufferSize );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetCurrentBatteryPower", CallingConvention = Platform.CC)]
private static extern byte _GetCurrentBatteryPower( IntPtr self );
#endregion
internal byte GetCurrentBatteryPower()
{
var returnValue = _GetCurrentBatteryPower( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetAppID", CallingConvention = Platform.CC)]
private static extern uint _GetAppID( IntPtr self );
#endregion
internal uint GetAppID()
{
var returnValue = _GetAppID( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_SetOverlayNotificationPosition", CallingConvention = Platform.CC)]
private static extern void _SetOverlayNotificationPosition( IntPtr self, NotificationPosition eNotificationPosition );
#endregion
internal void SetOverlayNotificationPosition( NotificationPosition eNotificationPosition )
{
_SetOverlayNotificationPosition( Self, eNotificationPosition );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_IsAPICallCompleted", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _IsAPICallCompleted( IntPtr self, SteamAPICall_t hSteamAPICall, [MarshalAs( UnmanagedType.U1 )] ref bool pbFailed );
#endregion
internal bool IsAPICallCompleted( SteamAPICall_t hSteamAPICall, [MarshalAs( UnmanagedType.U1 )] ref bool pbFailed )
{
var returnValue = _IsAPICallCompleted( Self, hSteamAPICall, ref pbFailed );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetAPICallFailureReason", CallingConvention = Platform.CC)]
private static extern SteamAPICallFailure _GetAPICallFailureReason( IntPtr self, SteamAPICall_t hSteamAPICall );
#endregion
internal SteamAPICallFailure GetAPICallFailureReason( SteamAPICall_t hSteamAPICall )
{
var returnValue = _GetAPICallFailureReason( Self, hSteamAPICall );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetAPICallResult", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetAPICallResult( IntPtr self, SteamAPICall_t hSteamAPICall, IntPtr pCallback, int cubCallback, int iCallbackExpected, [MarshalAs( UnmanagedType.U1 )] ref bool pbFailed );
#endregion
internal bool GetAPICallResult( SteamAPICall_t hSteamAPICall, IntPtr pCallback, int cubCallback, int iCallbackExpected, [MarshalAs( UnmanagedType.U1 )] ref bool pbFailed )
{
var returnValue = _GetAPICallResult( Self, hSteamAPICall, pCallback, cubCallback, iCallbackExpected, ref pbFailed );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetIPCCallCount", CallingConvention = Platform.CC)]
private static extern uint _GetIPCCallCount( IntPtr self );
#endregion
internal uint GetIPCCallCount()
{
var returnValue = _GetIPCCallCount( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_SetWarningMessageHook", CallingConvention = Platform.CC)]
private static extern void _SetWarningMessageHook( IntPtr self, IntPtr pFunction );
#endregion
internal void SetWarningMessageHook( IntPtr pFunction )
{
_SetWarningMessageHook( Self, pFunction );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_IsOverlayEnabled", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _IsOverlayEnabled( IntPtr self );
#endregion
internal bool IsOverlayEnabled()
{
var returnValue = _IsOverlayEnabled( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_BOverlayNeedsPresent", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _BOverlayNeedsPresent( IntPtr self );
#endregion
internal bool BOverlayNeedsPresent()
{
var returnValue = _BOverlayNeedsPresent( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_CheckFileSignature", CallingConvention = Platform.CC)]
private static extern SteamAPICall_t _CheckFileSignature( IntPtr self, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string szFileName );
#endregion
internal CallResult<CheckFileSignature_t> CheckFileSignature( [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string szFileName )
{
var returnValue = _CheckFileSignature( Self, szFileName );
return new CallResult<CheckFileSignature_t>( returnValue, IsServer );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_ShowGamepadTextInput", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _ShowGamepadTextInput( IntPtr self, GamepadTextInputMode eInputMode, GamepadTextInputLineMode eLineInputMode, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchDescription, uint unCharMax, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchExistingText );
#endregion
internal bool ShowGamepadTextInput( GamepadTextInputMode eInputMode, GamepadTextInputLineMode eLineInputMode, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchDescription, uint unCharMax, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchExistingText )
{
var returnValue = _ShowGamepadTextInput( Self, eInputMode, eLineInputMode, pchDescription, unCharMax, pchExistingText );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetEnteredGamepadTextLength", CallingConvention = Platform.CC)]
private static extern uint _GetEnteredGamepadTextLength( IntPtr self );
#endregion
internal uint GetEnteredGamepadTextLength()
{
var returnValue = _GetEnteredGamepadTextLength( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetEnteredGamepadTextInput", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _GetEnteredGamepadTextInput( IntPtr self, IntPtr pchText, uint cchText );
#endregion
internal bool GetEnteredGamepadTextInput( out string pchText )
{
using var mempchText = Helpers.TakeMemory();
var returnValue = _GetEnteredGamepadTextInput( Self, mempchText, (1024 * 32) );
pchText = Helpers.MemoryToString( mempchText );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetSteamUILanguage", CallingConvention = Platform.CC)]
private static extern Utf8StringPointer _GetSteamUILanguage( IntPtr self );
#endregion
internal string GetSteamUILanguage()
{
var returnValue = _GetSteamUILanguage( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_IsSteamRunningInVR", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _IsSteamRunningInVR( IntPtr self );
#endregion
internal bool IsSteamRunningInVR()
{
var returnValue = _IsSteamRunningInVR( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_SetOverlayNotificationInset", CallingConvention = Platform.CC)]
private static extern void _SetOverlayNotificationInset( IntPtr self, int nHorizontalInset, int nVerticalInset );
#endregion
internal void SetOverlayNotificationInset( int nHorizontalInset, int nVerticalInset )
{
_SetOverlayNotificationInset( Self, nHorizontalInset, nVerticalInset );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_IsSteamInBigPictureMode", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _IsSteamInBigPictureMode( IntPtr self );
#endregion
internal bool IsSteamInBigPictureMode()
{
var returnValue = _IsSteamInBigPictureMode( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_StartVRDashboard", CallingConvention = Platform.CC)]
private static extern void _StartVRDashboard( IntPtr self );
#endregion
internal void StartVRDashboard()
{
_StartVRDashboard( Self );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_IsVRHeadsetStreamingEnabled", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _IsVRHeadsetStreamingEnabled( IntPtr self );
#endregion
internal bool IsVRHeadsetStreamingEnabled()
{
var returnValue = _IsVRHeadsetStreamingEnabled( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_SetVRHeadsetStreamingEnabled", CallingConvention = Platform.CC)]
private static extern void _SetVRHeadsetStreamingEnabled( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bEnabled );
#endregion
internal void SetVRHeadsetStreamingEnabled( [MarshalAs( UnmanagedType.U1 )] bool bEnabled )
{
_SetVRHeadsetStreamingEnabled( Self, bEnabled );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_IsSteamChinaLauncher", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _IsSteamChinaLauncher( IntPtr self );
#endregion
internal bool IsSteamChinaLauncher()
{
var returnValue = _IsSteamChinaLauncher( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_InitFilterText", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _InitFilterText( IntPtr self, uint unFilterOptions );
#endregion
internal bool InitFilterText( uint unFilterOptions )
{
var returnValue = _InitFilterText( Self, unFilterOptions );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_FilterText", CallingConvention = Platform.CC)]
private static extern int _FilterText( IntPtr self, TextFilteringContext eContext, SteamId sourceSteamID, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchInputMessage, IntPtr pchOutFilteredText, uint nByteSizeOutFilteredText );
#endregion
internal int FilterText( TextFilteringContext eContext, SteamId sourceSteamID, [MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof( Utf8StringToNative ) )] string pchInputMessage, out string pchOutFilteredText )
{
using var mempchOutFilteredText = Helpers.TakeMemory();
var returnValue = _FilterText( Self, eContext, sourceSteamID, pchInputMessage, mempchOutFilteredText, (1024 * 32) );
pchOutFilteredText = Helpers.MemoryToString( mempchOutFilteredText );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_GetIPv6ConnectivityState", CallingConvention = Platform.CC)]
private static extern SteamIPv6ConnectivityState _GetIPv6ConnectivityState( IntPtr self, SteamIPv6ConnectivityProtocol eProtocol );
#endregion
internal SteamIPv6ConnectivityState GetIPv6ConnectivityState( SteamIPv6ConnectivityProtocol eProtocol )
{
var returnValue = _GetIPv6ConnectivityState( Self, eProtocol );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_IsSteamRunningOnSteamDeck", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _IsSteamRunningOnSteamDeck( IntPtr self );
#endregion
internal bool IsSteamRunningOnSteamDeck()
{
var returnValue = _IsSteamRunningOnSteamDeck( Self );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_ShowFloatingGamepadTextInput", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _ShowFloatingGamepadTextInput( IntPtr self, TextInputMode eKeyboardMode, int nTextFieldXPosition, int nTextFieldYPosition, int nTextFieldWidth, int nTextFieldHeight );
#endregion
internal bool ShowFloatingGamepadTextInput( TextInputMode eKeyboardMode, int nTextFieldXPosition, int nTextFieldYPosition, int nTextFieldWidth, int nTextFieldHeight )
{
var returnValue = _ShowFloatingGamepadTextInput( Self, eKeyboardMode, nTextFieldXPosition, nTextFieldYPosition, nTextFieldWidth, nTextFieldHeight );
return returnValue;
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_SetGameLauncherMode", CallingConvention = Platform.CC)]
private static extern void _SetGameLauncherMode( IntPtr self, [MarshalAs( UnmanagedType.U1 )] bool bLauncherMode );
#endregion
internal void SetGameLauncherMode( [MarshalAs( UnmanagedType.U1 )] bool bLauncherMode )
{
_SetGameLauncherMode( Self, bLauncherMode );
}
#region FunctionMeta
[DllImport( Platform.LibraryName, EntryPoint = "SteamAPI_ISteamUtils_DismissFloatingGamepadTextInput", CallingConvention = Platform.CC)]
[return: MarshalAs( UnmanagedType.I1 )]
private static extern bool _DismissFloatingGamepadTextInput( IntPtr self );
#endregion
internal bool DismissFloatingGamepadTextInput()
{
var returnValue = _DismissFloatingGamepadTextInput( Self );
return returnValue;
}
}
}
| |
using System;
using System.Reflection;
using System.Web;
using Castle.Core;
using Castle.MicroKernel;
using Castle.Windsor;
using Cuyahoga.Core.Service;
using Cuyahoga.Core.Util;
using Cuyahoga.Web.Components;
using log4net;
using log4net.Config;
namespace Cuyahoga.Web
{
public class Global : HttpApplication, IContainerAccessor
{
private static ILog log = LogManager.GetLogger(typeof(Global));
private static readonly string ERROR_PAGE_LOCATION = "~/Error.aspx";
/// <summary>
/// Obtain the container.
/// </summary>
public IWindsorContainer Container
{
get { return IoC.Container; }
}
public Global()
{
InitializeComponent();
}
protected void Application_Start(Object sender, EventArgs e)
{
// Initialize Cuyahoga environment
// Set application level flags.
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["IsFirstRequest"] = true;
HttpContext.Current.Application["ModulesLoaded"] = false;
HttpContext.Current.Application["IsModuleLoading"] = false;
HttpContext.Current.Application["IsInstalling"] = false;
HttpContext.Current.Application["IsUpgrading"] = false;
HttpContext.Current.Application.UnLock();
// Initialize log4net
XmlConfigurator.Configure();
// Initialize Windsor
IWindsorContainer container = new CuyahogaContainer();
container.Kernel.ComponentCreated += new ComponentInstanceDelegate(Kernel_ComponentCreated);
container.Kernel.ComponentDestroyed += new ComponentInstanceDelegate(Kernel_ComponentDestroyed);
// Inititialize the static Windsor helper class.
IoC.Initialize(container);
}
protected void Session_Start(Object sender, EventArgs e)
{
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
// Bootstrap Cuyahoga at the first request. We can't do this in Application_Start because
// we need the HttpContext.Response object to perform redirect. In IIS 7 integrated mode, the
// Response isn't available in Application_Start.
if ((bool)HttpContext.Current.Application["IsFirstRequest"])
{
// Check for any new versions
CheckInstaller();
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["IsFirstRequest"] = false;
HttpContext.Current.Application.UnLock();
}
// Load active modules. This can't be done in Application_Start because the Installer might kick in
// before modules are loaded.
if (! (bool)HttpContext.Current.Application["ModulesLoaded"]
&& !(bool)HttpContext.Current.Application["IsModuleLoading"]
&& !(bool)HttpContext.Current.Application["IsInstalling"]
&& !(bool)HttpContext.Current.Application["IsUpgrading"])
{
LoadModules();
}
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
}
protected void Application_Error(Object sender, EventArgs e)
{
if (Context != null && Context.IsCustomErrorEnabled)
{
Server.Transfer(ERROR_PAGE_LOCATION, false);
}
}
protected void Session_End(Object sender, EventArgs e)
{
}
protected void Application_End(Object sender, EventArgs e)
{
IWindsorContainer container = IoC.Container;
container.Kernel.ComponentCreated -= new ComponentInstanceDelegate(Kernel_ComponentCreated);
container.Kernel.ComponentDestroyed -= new ComponentInstanceDelegate(Kernel_ComponentDestroyed);
container.Dispose();
}
#region Web Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
}
#endregion
private void CheckInstaller()
{
if (!HttpContext.Current.Request.RawUrl.Contains("Install"))
{
// Check version and redirect to install pages if neccessary.
DatabaseInstaller dbInstaller = new DatabaseInstaller(HttpContext.Current.Server.MapPath("~/Install/Core"),
Assembly.Load("Cuyahoga.Core"));
if (dbInstaller.TestDatabaseConnection())
{
if (dbInstaller.CanUpgrade)
{
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["IsUpgrading"] = true;
HttpContext.Current.Application.UnLock();
HttpContext.Current.Response.Redirect("~/Install/Upgrade.aspx");
}
else if (dbInstaller.CanInstall)
{
HttpContext.Current.Application.Lock();
HttpContext.Current.Application["IsInstalling"] = true;
HttpContext.Current.Application.UnLock();
HttpContext.Current.Response.Redirect("~/Install/Install.aspx");
}
}
else
{
throw new Exception("Cuyahoga can't connect to the database. Please check your application settings.");
}
}
}
private void LoadModules()
{
if (log.IsDebugEnabled)
{
log.Debug("Entering module loading.");
}
// Load module types into the container.
ModuleLoader loader = Container.Resolve<ModuleLoader>();
loader.RegisterActivatedModules();
if (log.IsDebugEnabled)
{
log.Debug("Finished module loading. Now redirecting to self.");
}
// Re-load the requested page (to avoid conflicts with first-time configured NHibernate modules )
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl);
}
private void Kernel_ComponentCreated(ComponentModel model, object instance)
{
if (log.IsDebugEnabled)
{
log.Debug("Component created: " + instance.ToString());
}
}
private void Kernel_ComponentDestroyed(ComponentModel model, object instance)
{
if (log.IsDebugEnabled)
{
log.Debug("Component destroyed: " + instance.ToString());
}
}
}
}
| |
// ReSharper disable UnusedMember.Local
namespace Gu.State.Tests.CopyTests
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
public static class CopyTypes
{
public struct Struct
{
public int Value { get; set; }
}
public class ComplexType
{
public static readonly TestComparer Comparer = new TestComparer();
public static readonly IEqualityComparer<ComplexType> ByNameComparer = new NameComparer();
public ComplexType()
{
}
public ComplexType(string name, int value)
{
this.Name = name;
this.Value = value;
}
public string Name { get; set; }
public int Value { get; set; }
public sealed class TestComparer : IEqualityComparer<ComplexType>, IComparer<ComplexType>, IComparer
{
public bool Equals(ComplexType x, ComplexType y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x is null)
{
return false;
}
if (y is null)
{
return false;
}
if (x.GetType() != y.GetType())
{
return false;
}
return string.Equals(x.Name, y.Name, StringComparison.Ordinal) && x.Value == y.Value;
}
public int GetHashCode(ComplexType obj)
{
unchecked
{
return ((obj.Name?.GetHashCode() ?? 0) * 397) ^ obj.Value;
}
}
public int Compare(ComplexType x, ComplexType y)
{
return this.Equals(x, y)
? 0
: -1;
}
int IComparer.Compare(object x, object y)
{
return this.Compare((ComplexType)x, (ComplexType)y);
}
}
private sealed class NameComparer : IEqualityComparer<ComplexType>
{
public bool Equals(ComplexType x, ComplexType y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (x.GetType() != y.GetType())
{
return false;
}
return string.Equals(x.Name, y.Name, StringComparison.Ordinal);
}
public int GetHashCode(ComplexType obj)
{
return obj.Name.GetHashCode();
}
}
}
public sealed class Immutable : IEquatable<Immutable>
{
public Immutable(int value)
{
this.Value = value;
}
public int Value { get; }
public static bool operator ==(Immutable left, Immutable right)
{
return Equals(left, right);
}
public static bool operator !=(Immutable left, Immutable right)
{
return !Equals(left, right);
}
public bool Equals(Immutable other)
{
if (other is null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return this.Value == other.Value;
}
public override bool Equals(object obj) => obj is Immutable immutable && this.Equals(immutable);
public override int GetHashCode() => this.Value;
}
public class WithArrayProperty
{
public WithArrayProperty()
{
}
public WithArrayProperty(string name, int value)
{
this.Name = name;
this.Value = value;
}
public WithArrayProperty(string name, int value, int[] array)
{
this.Name = name;
this.Value = value;
this.Array = array;
}
public string Name { get; set; }
public int Value { get; set; }
public int[] Array { get; set; }
}
public class WithCalculatedProperty : INotifyPropertyChanged
{
private readonly int factor;
private int value;
public WithCalculatedProperty(int factor = 1)
{
this.factor = factor;
}
public event PropertyChangedEventHandler PropertyChanged;
public int Value
{
get => this.value;
set
{
if (value == this.value)
{
return;
}
this.value = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(this.CalculatedValue));
}
}
public int CalculatedValue => this.Value * this.factor;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class WithComplexProperty
{
public WithComplexProperty()
{
}
public WithComplexProperty(string name, int value)
{
this.Name = name;
this.Value = value;
}
public string Name { get; set; }
public int Value { get; set; }
public ComplexType ComplexType { get; set; }
}
public class WithListProperty<T>
{
public List<T> Items { get; } = new List<T>();
}
public class With<T>
{
public With()
{
}
public With(T value)
{
this.Value = value;
}
public T Value { get; set; }
}
public class IntCollection : IReadOnlyList<int>
{
private readonly IReadOnlyList<int> ints;
public IntCollection(params int[] ints)
{
this.ints = ints;
}
public int Count => this.ints.Count;
public int this[int index] => this.ints[index];
public IEnumerator<int> GetEnumerator() => this.ints.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}
public class WithReadonlyField
{
public readonly int ReadonlyValue;
public int Value;
public WithReadonlyField(int readonlyValue, int value)
{
this.ReadonlyValue = readonlyValue;
this.Value = value;
}
}
public class WithReadonlyProperty<T>
{
public WithReadonlyProperty(T value)
{
this.Value = value;
}
public T Value { get; }
}
public class WithSimpleFields
{
internal static readonly TestComparer Comparer = new TestComparer();
internal int IntValue;
internal int? NullableIntValue;
internal string StringValue;
internal StringSplitOptions EnumValue;
public WithSimpleFields()
{
}
public WithSimpleFields(int intValue, int? nullableIntValue, string stringValue, StringSplitOptions enumValue)
{
this.IntValue = intValue;
this.NullableIntValue = nullableIntValue;
this.StringValue = stringValue;
this.EnumValue = enumValue;
}
internal sealed class TestComparer : IEqualityComparer<WithSimpleFields>, IComparer
{
public bool Equals(WithSimpleFields x, WithSimpleFields y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x is null)
{
return false;
}
if (y is null)
{
return false;
}
if (x.GetType() != y.GetType())
{
return false;
}
return x.IntValue == y.IntValue &&
x.NullableIntValue == y.NullableIntValue &&
string.Equals(x.StringValue, y.StringValue, StringComparison.Ordinal) &&
x.EnumValue == y.EnumValue;
}
public int GetHashCode(WithSimpleFields obj)
{
unchecked
{
var hashCode = obj.IntValue;
hashCode = (hashCode * 397) ^ obj.NullableIntValue.GetHashCode();
hashCode = (hashCode * 397) ^ (obj.StringValue != null
? obj.StringValue.GetHashCode()
: 0);
hashCode = (hashCode * 397) ^ (int)obj.EnumValue;
return hashCode;
}
}
int IComparer.Compare(object x, object y)
{
return this.Equals((WithSimpleFields)x, (WithSimpleFields)y)
? 0
: -1;
}
}
}
public class WithSimpleProperties : INotifyPropertyChanged
{
internal static readonly TestComparer Comparer = new TestComparer();
private int intValue;
private int? nullableIntValue;
private string stringValue;
private StringSplitOptions enumValue;
public WithSimpleProperties()
{
}
public WithSimpleProperties(int intValue, int? nullableIntValue, string stringValue, StringSplitOptions enumValue)
{
this.intValue = intValue;
this.nullableIntValue = nullableIntValue;
this.stringValue = stringValue;
this.enumValue = enumValue;
}
public event PropertyChangedEventHandler PropertyChanged;
public int IntValue
{
get => this.intValue;
set
{
if (value == this.intValue)
{
return;
}
this.intValue = value;
this.OnPropertyChanged();
}
}
public int? NullableIntValue
{
get => this.nullableIntValue;
set
{
if (value == this.nullableIntValue)
{
return;
}
this.nullableIntValue = value;
this.OnPropertyChanged();
}
}
public string StringValue
{
get => this.stringValue;
set
{
if (value == this.stringValue)
{
return;
}
this.stringValue = value;
this.OnPropertyChanged();
}
}
public StringSplitOptions EnumValue
{
get => this.enumValue;
set
{
if (value == this.enumValue)
{
return;
}
this.enumValue = value;
this.OnPropertyChanged();
}
}
public void SetFields(int newIntValue, string newStringValue)
{
this.intValue = newIntValue;
this.stringValue = newStringValue;
}
public virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
internal sealed class TestComparer : IEqualityComparer<WithSimpleProperties>, IComparer
{
public bool Equals(WithSimpleProperties x, WithSimpleProperties y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x is null)
{
return false;
}
if (y is null)
{
return false;
}
if (x.GetType() != y.GetType())
{
return false;
}
return x.IntValue == y.IntValue &&
x.NullableIntValue == y.NullableIntValue
&& string.Equals(x.StringValue, y.StringValue, StringComparison.Ordinal) &&
x.EnumValue == y.EnumValue;
}
public int GetHashCode(WithSimpleProperties obj)
{
unchecked
{
var hashCode = obj.IntValue;
hashCode = (hashCode * 397) ^ obj.NullableIntValue.GetHashCode();
hashCode = (hashCode * 397) ^ (obj.StringValue?.GetHashCode() ?? 0);
hashCode = (hashCode * 397) ^ (int)obj.EnumValue;
return hashCode;
}
}
int IComparer.Compare(object x, object y)
{
return this.Equals((WithSimpleProperties)x, (WithSimpleProperties)y)
? 0
: -1;
}
}
}
public class WithoutDefaultCtor
{
private int value;
public WithoutDefaultCtor(int value)
{
this.value = value;
}
public int Value
{
get => this.value;
set => this.value = value;
}
}
public class WithIllegalIndexer
{
// ReSharper disable once UnusedParameter.Global
public int this[int index]
{
get => 0;
//// ReSharper disable once ValueParameterNotUsed
set { }
}
}
public class Parent
{
private Child child;
public Parent(string name, Child child)
{
this.Name = name;
this.Child = child;
}
public string Name { get; set; }
public Child Child
{
get => this.child;
set
{
if (value != null)
{
value.Parent = this;
}
this.child = value;
}
}
}
public class Child
{
public Child(string name)
{
this.Name = name;
}
private Child()
{
}
public string Name { get; set; }
public Parent Parent { get; set; }
}
public abstract class BaseClass
{
public double BaseValue { get; set; }
}
public class Derived1 : BaseClass
{
public double Derived1Value { get; set; }
}
public class Derived2 : BaseClass
{
public double Derived2Value { get; set; }
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using NUnit.Framework;
using SIL.Keyboarding;
using SIL.Reporting;
using SIL.Windows.Forms.Keyboarding.Windows;
namespace SIL.Windows.Forms.Keyboarding.Tests
{
[TestFixture]
[Platform(Exclude = "Linux", Reason = "Windows specific tests")]
[Category("SkipOnTeamCity")] // TeamCity builds don't seem to be able to see any installed keyboards.
public class WindowsKeyboardControllerTests
{
[TestFixtureSetUp]
public void FixtureSetup()
{
KeyboardController.Initialize();
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
KeyboardController.Shutdown();
}
[SetUp]
public void Setup()
{
ErrorReport.IsOkToInteractWithUser = false;
}
[Test]
[Category("Windows IME")]
public void GetAllKeyboards_GivesSeveral()
{
var keyboards = Keyboard.Controller.AvailableKeyboards;
Assert.Greater(keyboards.Count(), 1, "This test requires that the Windows IME has at least two languages installed.");
}
IKeyboardDefinition FirstInactiveKeyboard
{
get
{
WinKeyboardDescription[] keyboards = Keyboard.Controller.AvailableKeyboards.OfType<WinKeyboardDescription>().ToArray();
if (keyboards.Length < 2)
Assert.Ignore("This test requires that the Windows IME has at least two languages installed.");
WinKeyboardDescription d = keyboards.FirstOrDefault(x => x != Keyboard.Controller.ActiveKeyboard);
if (d == null)
return keyboards.First(); // Some tests have some value even if it is an active keyboard.
return d;
}
}
[Test]
[Category("Windows IME")]
public void WindowsIME_ActivateKeyboardUsingKeyboard_ReportsItWasActivated()
{
IKeyboardDefinition d = FirstInactiveKeyboard;
d.Activate();
Assert.AreEqual(d, Keyboard.Controller.ActiveKeyboard);
}
[Test]
[Category("Windows IME")]
public void WindowsIME_DeActivateKeyboard_RevertsToDefault()
{
IKeyboardDefinition[] keyboards = Keyboard.Controller.AvailableKeyboards.Where(kd => kd is WinKeyboardDescription).ToArray();
if(keyboards.Length < 2)
Assert.Ignore("This test requires that the Windows IME has at least two languages installed.");
IKeyboardDefinition d = GetNonDefaultKeyboard(keyboards);
d.Activate();
Assert.AreEqual(d, Keyboard.Controller.ActiveKeyboard);
Keyboard.Controller.ActivateDefaultKeyboard();
Assert.AreNotEqual(d, Keyboard.Controller.ActiveKeyboard);
}
private static IKeyboardDefinition GetNonDefaultKeyboard(IList<IKeyboardDefinition> keyboards)
{
// The default language is not necessarily the first one, so we have to make sure
// that we don't select the default one.
IKeyboardDefinition defaultKeyboard = Keyboard.Controller.GetKeyboard(new InputLanguageWrapper(InputLanguage.DefaultInputLanguage));
int index = keyboards.Count - 1;
while (index >= 0)
{
if (!keyboards[index].Equals(defaultKeyboard))
break;
index--;
}
if (index < 0)
Assert.Fail("Could not find a non-default keyboard !?");
return keyboards[index];
}
[Test]
[Category("Windows IME")]
public void WindowsIME_GetKeyboards_GivesSeveralButOnlyWindowsOnes()
{
WinKeyboardDescription[] keyboards = Keyboard.Controller.AvailableKeyboards.OfType<WinKeyboardDescription>().ToArray();
if (keyboards.Length < 2)
Assert.Ignore("This test requires that the Windows IME has at least two languages installed.");
Assert.That(keyboards.Select(keyboard => keyboard.Engine), Is.All.TypeOf<WindowsKeyboardSwitchingAdapter>());
}
[Test]
public void ActivateDefaultKeyboard_ActivatesDefaultInputLanguage()
{
Keyboard.Controller.ActivateDefaultKeyboard();
Assert.That(WinKeyboardUtils.GetInputLanguage((WinKeyboardDescription) Keyboard.Controller.ActiveKeyboard),
Is.EqualTo(InputLanguage.DefaultInputLanguage));
}
[Test]
public void CreateKeyboardDefinition_NewKeyboard_ReturnsNewObject()
{
var keyboard = Keyboard.Controller.CreateKeyboard("en-US_foo", KeyboardFormat.Unknown, null);
Assert.That(keyboard, Is.Not.Null);
Assert.That(keyboard, Is.TypeOf<WinKeyboardDescription>());
Assert.That(((KeyboardDescription) keyboard).InputLanguage, Is.Not.Null);
}
// TODO: Remove or implement
#if WANT_PORT
[Test]
[Category("Keyman6")]
[Platform(Exclude = "Linux", Reason = "Keyman not supported on Linux")]
public void Keyman6_GetKeyboards_GivesAtLeastOneAndOnlyKeyman6Ones()
{
RequiresKeyman6();
List<KeyboardController.KeyboardDescriptor> keyboards = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman6);
Assert.Greater(keyboards.Count, 0);
foreach (KeyboardController.KeyboardDescriptor keyboard in keyboards)
{
Assert.AreEqual(KeyboardController.Engines.Keyman6, keyboard.engine);
}
}
[Test]
[Category("Keyman6")]
[Platform(Exclude = "Linux", Reason = "Doesn't need to run on Linux")]
public void Keyman6_ActivateKeyboard_ReportsItWasActivated()
{
RequiresKeyman6();
RequiresWindow();
KeyboardController.KeyboardDescriptor d = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman6)[0];
Application.DoEvents(); //required
Keyboard.Controller.SetKeyboard(d.ShortName);
Application.DoEvents(); //required
Assert.AreEqual(d.ShortName, KeyboardController.GetActiveKeyboard());
}
[Test]
[Category("Keyman6")]
[Platform(Exclude = "Linux", Reason = "Doesn't need to run on Linux")]
public void Keyman6_DeActivateKeyboard_RevertsToDefault()
{
RequiresKeyman6();
var d = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman6)[0];
Keyboard.Controller.SetKeyboard(d.ShortName);
Application.DoEvents();//required
KeyboardController.DeactivateKeyboard();
Application.DoEvents();//required
Assert.AreNotEqual(d.ShortName, KeyboardController.GetActiveKeyboard());
}
[Test]
[Category("Keyman7")]
[Platform(Exclude = "Linux", Reason = "Doesn't need to run on Linux")]
public void Keyman7_ActivateKeyboard_ReportsItWasActivated()
{
RequiresKeyman7();
KeyboardController.KeyboardDescriptor d = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman7)[0];
Keyboard.Controller.SetKeyboard(d.ShortName);
Application.DoEvents();//required
Assert.AreEqual(d.ShortName, KeyboardController.GetActiveKeyboard());
}
[Test]
[Category("Keyman7")]
[Platform(Exclude = "Linux", Reason = "Doesn't need to run on Linux")]
public void Keyman7_DeActivateKeyboard_RevertsToDefault()
{
RequiresKeyman7();
KeyboardController.KeyboardDescriptor d = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman7)[0];
Keyboard.Controller.SetKeyboard(d.ShortName);
Application.DoEvents();//required
KeyboardController.DeactivateKeyboard();
Application.DoEvents();//required
Assert.AreNotEqual(d.ShortName, KeyboardController.GetActiveKeyboard());
}
[Test]
[Category("Keyman7")]
[Platform(Exclude = "Linux", Reason = "Doesn't need to run on Linux")]
public void Keyman7_GetKeyboards_GivesAtLeastOneAndOnlyKeyman7Ones()
{
RequiresKeyman7();
List<KeyboardController.KeyboardDescriptor> keyboards = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman7);
Assert.Greater(keyboards.Count, 0);
foreach (KeyboardController.KeyboardDescriptor keyboard in keyboards)
{
Assert.AreEqual(KeyboardController.Engines.Keyman7, keyboard.engine);
}
}
/// <summary>
/// The main thing here is that it doesn't crash doing a LoadLibrary()
/// </summary>
[Test]
public void NoKeyman7_GetKeyboards_DoesNotCrash()
{
KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman7);
}
private static void RequiresKeyman6()
{
Assert.IsTrue(KeyboardController.EngineAvailable(KeyboardController.Engines.Keyman6),
"Keyman 6 Not available");
}
private static void RequiresKeyman7()
{
Assert.IsTrue(KeyboardController.EngineAvailable(KeyboardController.Engines.Keyman7),
"Keyman 7 Not available");
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
public partial class TimerFiringTests
{
internal const int MaxPositiveTimeoutInMs = 30000;
[Fact]
public void Timer_Fires_After_DueTime_Ellapses()
{
AutoResetEvent are = new AutoResetEvent(false);
using (var t = new Timer(new TimerCallback((object s) =>
{
are.Set();
}), null, TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
{
Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
}
}
[Fact]
public void Timer_Fires_AndPassesStateThroughCallback()
{
AutoResetEvent are = new AutoResetEvent(false);
object state = new object();
using (var t = new Timer(new TimerCallback((object s) =>
{
Assert.Same(s, state);
are.Set();
}), state, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
{
Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
}
}
[Fact]
public void Timer_Fires_AndPassesNullStateThroughCallback()
{
AutoResetEvent are = new AutoResetEvent(false);
using (var t = new Timer(new TimerCallback((object s) =>
{
Assert.Null(s);
are.Set();
}), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
{
Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
}
}
[Fact]
public void Timer_Fires_After_DueTime_AndOn_Period()
{
int count = 0;
AutoResetEvent are = new AutoResetEvent(false);
using (var t = new Timer(new TimerCallback((object s) =>
{
if (Interlocked.Increment(ref count) >= 2)
{
are.Set();
}
}), null, TimeSpan.FromMilliseconds(250), TimeSpan.FromMilliseconds(50)))
{
Assert.True(are.WaitOne(TimeSpan.FromMilliseconds(MaxPositiveTimeoutInMs)));
}
}
[Fact]
public void Timer_FiresOnlyOnce_OnDueTime_With_InfinitePeriod()
{
int count = 0;
AutoResetEvent are = new AutoResetEvent(false);
using (var t = new Timer(new TimerCallback((object s) =>
{
if (Interlocked.Increment(ref count) >= 2)
{
are.Set();
}
}), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(Timeout.Infinite) /* not relevant */))
{
Assert.False(are.WaitOne(TimeSpan.FromMilliseconds(250 /*enough for 2 fires + buffer*/)));
}
}
[Fact]
public void Timer_CanDisposeSelfInCallback()
{
Timer t = null;
AutoResetEvent are = new AutoResetEvent(false);
TimerCallback tc = new TimerCallback((object o) =>
{
t.Dispose();
are.Set();
});
t = new Timer(tc, null, -1, -1);
t.Change(1, -1);
Assert.True(are.WaitOne(MaxPositiveTimeoutInMs));
GC.KeepAlive(t);
}
[Fact]
public void Timer_CanBeDisposedMultipleTimes()
{
// There's nothing to validate besides that we don't throw an exception, so rely on xunit
// to catch any exception that would be thrown and signal a test failure
TimerCallback tc = new TimerCallback((object o) => { });
var t = new Timer(tc, null, 100, -1);
for (int i = 0; i < 10; i++)
t.Dispose();
}
[Fact]
public void NonRepeatingTimer_ThatHasAlreadyFired_CanChangeAndFireAgain()
{
AutoResetEvent are = new AutoResetEvent(false);
TimerCallback tc = new TimerCallback((object o) => are.Set());
using (var t = new Timer(tc, null, 1, Timeout.Infinite))
{
Assert.True(are.WaitOne(MaxPositiveTimeoutInMs), "Should have received first timer event");
Assert.False(are.WaitOne(500), "Should not have received a second timer event");
t.Change(10, Timeout.Infinite);
Assert.True(are.WaitOne(MaxPositiveTimeoutInMs), "Should have received a second timer event after changing it");
}
}
[Fact]
public void MultpleTimers_PeriodicTimerIsntBlockedByBlockedCallback()
{
int callbacks = 2;
Barrier b = new Barrier(callbacks + 1);
Timer t = null;
t = new Timer(_ =>
{
if (Interlocked.Decrement(ref callbacks) >= 0)
{
Assert.True(b.SignalAndWait(MaxPositiveTimeoutInMs));
}
t.Dispose();
}, null, -1, -1);
t.Change(1, 50);
Assert.True(b.SignalAndWait(MaxPositiveTimeoutInMs));
GC.KeepAlive(t);
}
[Fact]
public void ManyTimers_EachTimerDoesFire()
{
int maxTimers = 10000;
CountdownEvent ce = new CountdownEvent(maxTimers);
Timer[] timers = System.Linq.Enumerable.Range(0, maxTimers).Select(_ => new Timer(s => ce.Signal(), null, 100 /* enough time to wait on the are */, -1)).ToArray();
try
{
Assert.True(ce.Wait(MaxPositiveTimeoutInMs), string.Format("Not all timers fired, {0} left of {1}", ce.CurrentCount, maxTimers));
}
finally
{
foreach (Timer t in timers)
t.Dispose();
}
}
[Fact]
public void Timer_Constructor_CallbackOnly_Change()
{
var e = new ManualResetEvent(false);
using (var t = new Timer(s => e.Set()))
{
t.Change(0u, 0u);
Assert.True(e.WaitOne(MaxPositiveTimeoutInMs));
}
}
[Fact]
public void Timer_Dispose_WaitHandle_Negative()
{
Assert.Throws<ArgumentNullException>(() => new Timer(s => { }).Dispose(null));
}
[Fact]
public void Timer_Dispose_WaitHandle()
{
int tickCount = 0;
var someTicksPending = new ManualResetEvent(false);
var completeTicks = new ManualResetEvent(false);
var allTicksCompleted = new ManualResetEvent(false);
var t =
new Timer(s =>
{
if (Interlocked.Increment(ref tickCount) == 2)
someTicksPending.Set();
Assert.True(completeTicks.WaitOne(MaxPositiveTimeoutInMs));
Interlocked.Decrement(ref tickCount);
}, null, 0, 1);
Assert.True(someTicksPending.WaitOne(MaxPositiveTimeoutInMs));
completeTicks.Set();
t.Dispose(allTicksCompleted);
Assert.True(allTicksCompleted.WaitOne(MaxPositiveTimeoutInMs));
Assert.Equal(0, tickCount);
Assert.Throws<ObjectDisposedException>(() => t.Change(0, 0));
}
[OuterLoop("Takes several seconds")]
[Fact]
public async Task Timer_ManyDifferentSingleDueTimes_AllFireSuccessfully()
{
await Task.WhenAll(from p in Enumerable.Range(0, Environment.ProcessorCount)
select Task.Run(async () =>
{
await Task.WhenAll(from i in Enumerable.Range(1, 1_000) select DueTimeAsync(i));
await Task.WhenAll(from i in Enumerable.Range(1, 1_000) select DueTimeAsync(1_001 - i));
}));
}
[OuterLoop("Takes several seconds")]
[Fact]
public async Task Timer_ManyDifferentPeriodicTimes_AllFireSuccessfully()
{
await Task.WhenAll(from p in Enumerable.Range(0, Environment.ProcessorCount)
select Task.Run(async () =>
{
await Task.WhenAll(from i in Enumerable.Range(1, 400) select PeriodAsync(period: i, iterations: 3));
await Task.WhenAll(from i in Enumerable.Range(1, 400) select PeriodAsync(period: 401 - i, iterations: 3));
}));
}
[PlatformSpecific(~TestPlatforms.OSX)] // macOS in CI appears to have a lot more variation
[OuterLoop("Takes several seconds")]
[Theory] // selection based on 333ms threshold used by implementation
[InlineData(new int[] { 15 })]
[InlineData(new int[] { 333 })]
[InlineData(new int[] { 332, 333, 334 })]
[InlineData(new int[] { 200, 300, 400 })]
[InlineData(new int[] { 200, 250, 300 })]
[InlineData(new int[] { 400, 450, 500 })]
[InlineData(new int[] { 1000 })]
public async Task Timer_ManyDifferentSerialSingleDueTimes_AllFireWithinAllowedRange(int[] dueTimes)
{
const int MillisecondsPadding = 100; // for each timer, out of range == Math.Abs(actualTime - dueTime) > MillisecondsPadding
const int MaxAllowedOutOfRangePercentage = 20; // max % allowed out of range to pass test
var outOfRange = new ConcurrentQueue<KeyValuePair<int, long>>();
long totalTimers = 0;
await Task.WhenAll(from p in Enumerable.Range(0, Environment.ProcessorCount)
select Task.Run(async () =>
{
await Task.WhenAll(from dueTimeTemplate in dueTimes
from dueTime in Enumerable.Repeat(dueTimeTemplate, 10)
select Task.Run(async () =>
{
var sw = new Stopwatch();
for (int i = 1; i <= 1_000 / dueTime; i++)
{
sw.Restart();
await DueTimeAsync(dueTime);
sw.Stop();
Interlocked.Increment(ref totalTimers);
if (Math.Abs(sw.ElapsedMilliseconds - dueTime) > MillisecondsPadding)
{
outOfRange.Enqueue(new KeyValuePair<int, long>(dueTime, sw.ElapsedMilliseconds));
}
}
}));
}));
double percOutOfRange = (double)outOfRange.Count / totalTimers * 100;
if (percOutOfRange > MaxAllowedOutOfRangePercentage)
{
IOrderedEnumerable<IGrouping<int, KeyValuePair<int, long>>> results =
from sample in outOfRange
group sample by sample.Key into groupedByDueTime
orderby groupedByDueTime.Key
select groupedByDueTime;
var sb = new StringBuilder();
sb.AppendFormat("{0}% out of {1} timer firings were off by more than {2}ms",
percOutOfRange, totalTimers, MillisecondsPadding);
foreach (IGrouping<int, KeyValuePair<int, long>> result in results)
{
sb.AppendLine();
sb.AppendFormat("Expected: {0}, Actuals: {1}", result.Key, string.Join(", ", result.Select(k => k.Value)));
}
Assert.True(false, sb.ToString());
}
}
private static Task DueTimeAsync(int dueTime)
{
// We could just use Task.Delay, but it only uses Timer as an implementation detail.
// Since these are Timer tests, we use an implementation that explicitly uses Timer.
var tcs = new TaskCompletionSource<bool>();
var t = new Timer(_ => tcs.SetResult(true)); // rely on Timer(TimerCallback) rooting itself
t.Change(dueTime, -1);
return tcs.Task;
}
private static async Task PeriodAsync(int period, int iterations)
{
var tcs = new TaskCompletionSource<bool>();
using (var t = new Timer(_ => { if (Interlocked.Decrement(ref iterations) == 0) tcs.SetResult(true); })) // rely on Timer(TimerCallback) rooting itself
{
t.Change(period, period);
await tcs.Task.ConfigureAwait(false);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Runtime.Serialization
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
class DataMember
{
[Fx.Tag.SecurityNote(Critical = "Holds instance of CriticalHelper which keeps state that is cached statically for serialization."
+ " Static fields are marked SecurityCritical or readonly to prevent data from being modified or leaked to other components in appdomain.")]
[SecurityCritical]
CriticalHelper helper;
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
internal DataMember()
{
helper = new CriticalHelper();
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
internal DataMember(MemberInfo memberInfo)
{
helper = new CriticalHelper(memberInfo);
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
internal DataMember(string name)
{
helper = new CriticalHelper(name);
}
[Fx.Tag.SecurityNote(Critical = "Initializes SecurityCritical field 'helper'.",
Safe = "Doesn't leak anything.")]
[SecuritySafeCritical]
internal DataMember(DataContract memberTypeContract, string name, bool isNullable, bool isRequired, bool emitDefaultValue, int order)
{
helper = new CriticalHelper(memberTypeContract, name, isNullable, isRequired, emitDefaultValue, order);
}
internal MemberInfo MemberInfo
{
[SecuritySafeCritical]
get { return helper.MemberInfo; }
}
internal string Name
{
[SecuritySafeCritical]
get { return helper.Name; }
[SecurityCritical]
set { helper.Name = value; }
}
internal int Order
{
[SecuritySafeCritical]
get { return helper.Order; }
[SecurityCritical]
set { helper.Order = value; }
}
internal bool IsRequired
{
[SecuritySafeCritical]
get { return helper.IsRequired; }
[SecurityCritical]
set { helper.IsRequired = value; }
}
internal bool EmitDefaultValue
{
[SecuritySafeCritical]
get { return helper.EmitDefaultValue; }
[SecurityCritical]
set { helper.EmitDefaultValue = value; }
}
internal bool IsNullable
{
[SecuritySafeCritical]
get { return helper.IsNullable; }
[SecurityCritical]
set { helper.IsNullable = value; }
}
internal bool IsGetOnlyCollection
{
[SecuritySafeCritical]
get { return helper.IsGetOnlyCollection; }
[SecurityCritical]
set { helper.IsGetOnlyCollection = value; }
}
internal Type MemberType
{
[SecuritySafeCritical]
get { return helper.MemberType; }
}
internal DataContract MemberTypeContract
{
[SecuritySafeCritical]
get { return helper.MemberTypeContract; }
[SecurityCritical]
set { helper.MemberTypeContract = value; }
}
internal bool HasConflictingNameAndType
{
[SecuritySafeCritical]
get { return helper.HasConflictingNameAndType; }
[SecurityCritical]
set { helper.HasConflictingNameAndType = value; }
}
internal DataMember ConflictingMember
{
[SecuritySafeCritical]
get { return helper.ConflictingMember; }
[SecurityCritical]
set { helper.ConflictingMember = value; }
}
[Fx.Tag.SecurityNote(Critical = "Critical.")]
#if !NO_SECURITY_ATTRIBUTES
[SecurityCritical(SecurityCriticalScope.Everything)]
#endif
class CriticalHelper
{
DataContract memberTypeContract;
string name;
int order;
bool isRequired;
bool emitDefaultValue;
bool isNullable;
bool isGetOnlyCollection = false;
MemberInfo memberInfo;
bool hasConflictingNameAndType;
DataMember conflictingMember;
internal CriticalHelper()
{
this.emitDefaultValue = Globals.DefaultEmitDefaultValue;
}
internal CriticalHelper(MemberInfo memberInfo)
{
this.emitDefaultValue = Globals.DefaultEmitDefaultValue;
this.memberInfo = memberInfo;
}
internal CriticalHelper(string name)
{
this.Name = name;
}
internal CriticalHelper(DataContract memberTypeContract, string name, bool isNullable, bool isRequired, bool emitDefaultValue, int order)
{
this.MemberTypeContract = memberTypeContract;
this.Name = name;
this.IsNullable = isNullable;
this.IsRequired = isRequired;
this.EmitDefaultValue = emitDefaultValue;
this.Order = order;
}
internal MemberInfo MemberInfo
{
get { return memberInfo; }
}
internal string Name
{
get { return name; }
set { name = value; }
}
internal int Order
{
get { return order; }
set { order = value; }
}
internal bool IsRequired
{
get { return isRequired; }
set { isRequired = value; }
}
internal bool EmitDefaultValue
{
get { return emitDefaultValue; }
set { emitDefaultValue = value; }
}
internal bool IsNullable
{
get { return isNullable; }
set { isNullable = value; }
}
internal bool IsGetOnlyCollection
{
get { return isGetOnlyCollection; }
set { isGetOnlyCollection = value; }
}
internal Type MemberType
{
get
{
FieldInfo field = MemberInfo as FieldInfo;
if (field != null)
return field.FieldType;
return ((PropertyInfo)MemberInfo).PropertyType;
}
}
internal DataContract MemberTypeContract
{
get
{
if (memberTypeContract == null)
{
if (MemberInfo != null)
{
if (this.IsGetOnlyCollection)
{
memberTypeContract = DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(MemberType.TypeHandle), MemberType.TypeHandle, MemberType, SerializationMode.SharedContract);
}
else
{
memberTypeContract = DataContract.GetDataContract(MemberType);
}
}
}
return memberTypeContract;
}
set
{
memberTypeContract = value;
}
}
internal bool HasConflictingNameAndType
{
get { return this.hasConflictingNameAndType; }
set { this.hasConflictingNameAndType = value; }
}
internal DataMember ConflictingMember
{
get { return this.conflictingMember; }
set { this.conflictingMember = value; }
}
}
#if !NO_DYNAMIC_CODEGEN
[Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks member visibility to calculate if access to it requires MemberAccessPermission for serialization."
+ " Since this information is used to determine whether to give the generated code access"
+ " permissions to private members, any changes to the logic should be reviewed.")]
internal bool RequiresMemberAccessForGet()
{
MemberInfo memberInfo = MemberInfo;
FieldInfo field = memberInfo as FieldInfo;
if (field != null)
{
return DataContract.FieldRequiresMemberAccess(field);
}
else
{
PropertyInfo property = (PropertyInfo)memberInfo;
MethodInfo getMethod = property.GetGetMethod(true /*nonPublic*/);
if (getMethod != null)
return DataContract.MethodRequiresMemberAccess(getMethod) || !DataContract.IsTypeVisible(property.PropertyType);
}
return false;
}
[Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview - checks member visibility to calculate if access to it requires MemberAccessPermission for deserialization."
+ " Since this information is used to determine whether to give the generated code access"
+ " permissions to private members, any changes to the logic should be reviewed.")]
internal bool RequiresMemberAccessForSet()
{
MemberInfo memberInfo = MemberInfo;
FieldInfo field = memberInfo as FieldInfo;
if (field != null)
{
return DataContract.FieldRequiresMemberAccess(field);
}
else
{
PropertyInfo property = (PropertyInfo)memberInfo;
MethodInfo setMethod = property.GetSetMethod(true /*nonPublic*/);
if (setMethod != null)
return DataContract.MethodRequiresMemberAccess(setMethod) || !DataContract.IsTypeVisible(property.PropertyType);
}
return false;
}
#endif
internal DataMember BindGenericParameters(DataContract[] paramContracts, Dictionary<DataContract, DataContract> boundContracts)
{
DataContract memberTypeContract = this.MemberTypeContract.BindGenericParameters(paramContracts, boundContracts);
DataMember boundDataMember = new DataMember(memberTypeContract,
this.Name,
!memberTypeContract.IsValueType,
this.IsRequired,
this.EmitDefaultValue,
this.Order);
return boundDataMember;
}
internal bool Equals(object other, Dictionary<DataContractPairKey, object> checkedContracts)
{
if ((object)this == other)
return true;
DataMember dataMember = other as DataMember;
if (dataMember != null)
{
// Note: comparison does not use Order hint since it influences element order but does not specify exact order
bool thisIsNullable = (MemberTypeContract == null) ? false : !MemberTypeContract.IsValueType;
bool dataMemberIsNullable = (dataMember.MemberTypeContract == null) ? false : !dataMember.MemberTypeContract.IsValueType;
return (Name == dataMember.Name
&& (IsNullable || thisIsNullable) == (dataMember.IsNullable || dataMemberIsNullable)
&& IsRequired == dataMember.IsRequired
&& EmitDefaultValue == dataMember.EmitDefaultValue
&& MemberTypeContract.Equals(dataMember.MemberTypeContract, checkedContracts));
}
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="UserListServiceClient"/> instances.</summary>
public sealed partial class UserListServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="UserListServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="UserListServiceSettings"/>.</returns>
public static UserListServiceSettings GetDefault() => new UserListServiceSettings();
/// <summary>Constructs a new <see cref="UserListServiceSettings"/> object with default settings.</summary>
public UserListServiceSettings()
{
}
private UserListServiceSettings(UserListServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetUserListSettings = existing.GetUserListSettings;
MutateUserListsSettings = existing.MutateUserListsSettings;
OnCopy(existing);
}
partial void OnCopy(UserListServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>UserListServiceClient.GetUserList</c> and <c>UserListServiceClient.GetUserListAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetUserListSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>UserListServiceClient.MutateUserLists</c> and <c>UserListServiceClient.MutateUserListsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateUserListsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="UserListServiceSettings"/> object.</returns>
public UserListServiceSettings Clone() => new UserListServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="UserListServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
internal sealed partial class UserListServiceClientBuilder : gaxgrpc::ClientBuilderBase<UserListServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public UserListServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public UserListServiceClientBuilder()
{
UseJwtAccessWithScopes = UserListServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref UserListServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<UserListServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override UserListServiceClient Build()
{
UserListServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<UserListServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<UserListServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private UserListServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return UserListServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<UserListServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return UserListServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => UserListServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => UserListServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => UserListServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>UserListService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage user lists.
/// </remarks>
public abstract partial class UserListServiceClient
{
/// <summary>
/// The default endpoint for the UserListService service, which is a host of "googleads.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default UserListService scopes.</summary>
/// <remarks>
/// The default UserListService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="UserListServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="UserListServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="UserListServiceClient"/>.</returns>
public static stt::Task<UserListServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new UserListServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="UserListServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="UserListServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="UserListServiceClient"/>.</returns>
public static UserListServiceClient Create() => new UserListServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="UserListServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="UserListServiceSettings"/>.</param>
/// <returns>The created <see cref="UserListServiceClient"/>.</returns>
internal static UserListServiceClient Create(grpccore::CallInvoker callInvoker, UserListServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
UserListService.UserListServiceClient grpcClient = new UserListService.UserListServiceClient(callInvoker);
return new UserListServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC UserListService client</summary>
public virtual UserListService.UserListServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested user list.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::UserList GetUserList(GetUserListRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested user list.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::UserList> GetUserListAsync(GetUserListRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested user list.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::UserList> GetUserListAsync(GetUserListRequest request, st::CancellationToken cancellationToken) =>
GetUserListAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested user list.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the user list to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::UserList GetUserList(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetUserList(new GetUserListRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested user list.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the user list to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::UserList> GetUserListAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetUserListAsync(new GetUserListRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested user list.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the user list to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::UserList> GetUserListAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetUserListAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested user list.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the user list to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::UserList GetUserList(gagvr::UserListName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetUserList(new GetUserListRequest
{
ResourceNameAsUserListName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested user list.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the user list to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::UserList> GetUserListAsync(gagvr::UserListName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetUserListAsync(new GetUserListRequest
{
ResourceNameAsUserListName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested user list.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the user list to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::UserList> GetUserListAsync(gagvr::UserListName resourceName, st::CancellationToken cancellationToken) =>
GetUserListAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates or updates user lists. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperationAccessDeniedError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UserListError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateUserListsResponse MutateUserLists(MutateUserListsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates or updates user lists. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperationAccessDeniedError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UserListError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateUserListsResponse> MutateUserListsAsync(MutateUserListsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates or updates user lists. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperationAccessDeniedError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UserListError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateUserListsResponse> MutateUserListsAsync(MutateUserListsRequest request, st::CancellationToken cancellationToken) =>
MutateUserListsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates or updates user lists. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperationAccessDeniedError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UserListError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose user lists are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual user lists.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateUserListsResponse MutateUserLists(string customerId, scg::IEnumerable<UserListOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateUserLists(new MutateUserListsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates or updates user lists. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperationAccessDeniedError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UserListError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose user lists are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual user lists.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateUserListsResponse> MutateUserListsAsync(string customerId, scg::IEnumerable<UserListOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateUserListsAsync(new MutateUserListsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates or updates user lists. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperationAccessDeniedError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UserListError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose user lists are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual user lists.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateUserListsResponse> MutateUserListsAsync(string customerId, scg::IEnumerable<UserListOperation> operations, st::CancellationToken cancellationToken) =>
MutateUserListsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>UserListService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage user lists.
/// </remarks>
public sealed partial class UserListServiceClientImpl : UserListServiceClient
{
private readonly gaxgrpc::ApiCall<GetUserListRequest, gagvr::UserList> _callGetUserList;
private readonly gaxgrpc::ApiCall<MutateUserListsRequest, MutateUserListsResponse> _callMutateUserLists;
/// <summary>
/// Constructs a client wrapper for the UserListService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="UserListServiceSettings"/> used within this client.</param>
public UserListServiceClientImpl(UserListService.UserListServiceClient grpcClient, UserListServiceSettings settings)
{
GrpcClient = grpcClient;
UserListServiceSettings effectiveSettings = settings ?? UserListServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetUserList = clientHelper.BuildApiCall<GetUserListRequest, gagvr::UserList>(grpcClient.GetUserListAsync, grpcClient.GetUserList, effectiveSettings.GetUserListSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetUserList);
Modify_GetUserListApiCall(ref _callGetUserList);
_callMutateUserLists = clientHelper.BuildApiCall<MutateUserListsRequest, MutateUserListsResponse>(grpcClient.MutateUserListsAsync, grpcClient.MutateUserLists, effectiveSettings.MutateUserListsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateUserLists);
Modify_MutateUserListsApiCall(ref _callMutateUserLists);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetUserListApiCall(ref gaxgrpc::ApiCall<GetUserListRequest, gagvr::UserList> call);
partial void Modify_MutateUserListsApiCall(ref gaxgrpc::ApiCall<MutateUserListsRequest, MutateUserListsResponse> call);
partial void OnConstruction(UserListService.UserListServiceClient grpcClient, UserListServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC UserListService client</summary>
public override UserListService.UserListServiceClient GrpcClient { get; }
partial void Modify_GetUserListRequest(ref GetUserListRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateUserListsRequest(ref MutateUserListsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested user list.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::UserList GetUserList(GetUserListRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetUserListRequest(ref request, ref callSettings);
return _callGetUserList.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested user list.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::UserList> GetUserListAsync(GetUserListRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetUserListRequest(ref request, ref callSettings);
return _callGetUserList.Async(request, callSettings);
}
/// <summary>
/// Creates or updates user lists. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperationAccessDeniedError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UserListError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateUserListsResponse MutateUserLists(MutateUserListsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateUserListsRequest(ref request, ref callSettings);
return _callMutateUserLists.Sync(request, callSettings);
}
/// <summary>
/// Creates or updates user lists. Operation statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotAllowlistedError]()
/// [NotEmptyError]()
/// [OperationAccessDeniedError]()
/// [QuotaError]()
/// [RangeError]()
/// [RequestError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// [UserListError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateUserListsResponse> MutateUserListsAsync(MutateUserListsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateUserListsRequest(ref request, ref callSettings);
return _callMutateUserLists.Async(request, callSettings);
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml.Linq;
using MediaServer.Configuration;
using MediaServer.Media.Nodes;
using MediaServer.Utility;
using System.Collections.Generic;
namespace MediaServer.Media
{
public class MediaRepository : IMediaRepository
{
private static readonly XNamespace Didl = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";
private static readonly XNamespace Dc = "http://purl.org/dc/elements/1.1/";
private static readonly XNamespace Upnp = "urn:schemas-upnp-org:metadata-1-0/upnp/";
private readonly ReadWriteLockedCache<Guid, MediaNode> _resourceCache =
new ReadWriteLockedCache<Guid, MediaNode>();
#region Singleton
private static readonly Lazy<MediaRepository> SingletonInstance = new Lazy<MediaRepository>(() => new MediaRepository());
public static MediaRepository Instance
{
get
{
return SingletonInstance.Value;
}
}
#endregion
private MediaRepository()
{
//Settings.Instance.ConfigurationChanged += OnConfigurationChanged;
}
//private void OnConfigurationChanged(object sender, EventArgs e)
//{
// Logger.Instance.Info("Configuration file changed, reloading media tree structure");
// Initialize();
//}
private static void AddMediaFolders(FolderNode root)
{
var query = (from item in Settings.Instance.MediaFolders
where System.IO.Directory.Exists(item.Path)
select new FilesystemFolderNode(root, item.Name, item.Path)).Cast<MediaNode>().ToList();
if (query.Count() > 0)
{
root.AddRange(query);
}
}
private static void AddiTunesFolders(FolderNode root)
{
var query = (from item in Settings.Instance.iTunesFolders
where File.Exists(item.Path)
select new iTunesFolderNode(root, item.Name, item.Path, item.Remap)).Cast<MediaNode>().ToList();
var count = query.Count();
if (count > 0)
{
root.AddRange(query);
}
}
private static void AddiPhotoFolders(FolderNode root)
{
var query = (from item in Settings.Instance.iPhotoFolders
where File.Exists(item.Path)
select new iPhotoFolderNode(root, item.Name, item.Path, item.Remap)).Cast<MediaNode>().ToList();
var count = query.Count();
if (count > 0)
{
root.AddRange(query);
}
}
private void InternalInitialize()
{
_resourceCache.Clear();
var root = new FolderNode(null, "Root");
AddMediaFolders(root);
AddiTunesFolders(root);
AddiPhotoFolders(root);
//var onlineFolder = new FolderNode(root, "Online");
//root.Add(onlineFolder);
// This makes no sense. how is this possible? I guess mf. itf, or pf will be null if /Volumesn isnt up yet
// so I guess this should stay... got to think about it...
// Actually, maybe not.
//if (mf == false && itf == false && ipf == false) _timer.Change(TimeSpan.FromSeconds(30), TimeSpan.FromMilliseconds(-1));
}
public void Initialize()
{
InternalInitialize();
//_timer.Change(TimeSpan.FromSeconds(0), TimeSpan.FromMilliseconds(-1));
}
public void AddNodeToIndex(MediaNode node)
{
_resourceCache.Add(node.Id, node);
}
public void AddNodesToIndex(IEnumerable<MediaNode> nodes)
{
_resourceCache.AddMulti(nodes.Select(item => new KeyValuePair<Guid, MediaNode>(item.Id, item)));
}
public void RemoveNodesFromIndexes(IEnumerable<MediaNode> nodes)
{
_resourceCache.DeleteMulti(nodes.Select(item => item.Id));
}
public void RemoveNodeFromIndexes(MediaNode node)
{
_resourceCache.Delete(node.Id);
}
#region Implementation of IMediaRepository
public uint SystemUpdateId
{
get
{
unchecked
{
return _resourceCache.VersionId;
}
}
}
public void BrowseMetadata(string objectId, string filter, uint startingIndex,
uint requestedCount, string sortCriteria, out string result, out uint numberReturned,
out uint totalMatches, out uint updateId, IPEndPoint queryEndpoint, IPEndPoint mediaEndpoint)
{
result = "";
numberReturned = 0;
totalMatches = 0;
updateId = 0;
var oid = (objectId == "0") ? Guid.Empty : new Guid(objectId);
MediaNode node;
if (_resourceCache.TryGetValue(oid, out node))
{
var folder = node as FolderNode;
if (folder == null) return;
var findings =
new XElement(
Didl + "DIDL-Lite",
new XAttribute(XNamespace.Xmlns + "dc", Dc.ToString()),
new XAttribute(XNamespace.Xmlns + "upnp", Upnp.ToString()),
folder.RenderMetadata(queryEndpoint, mediaEndpoint));
result = findings.ToString();
numberReturned = 1;
totalMatches = 1;
updateId = oid == Guid.Empty ? SystemUpdateId : folder.ContainerUpdateId;
}
}
public void BrowseDirectChildren(string objectId, string filter, uint startingIndex,
uint requestedCount, string sortCriteria, out string result, out uint numberReturned,
out uint totalMatches, out uint updateId, IPEndPoint queryEndpoint, IPEndPoint mediaEndpoint)
{
result = "";
numberReturned = 0;
totalMatches = 0;
updateId = 0;
var oid = (objectId == "0") ? Guid.Empty : new Guid(objectId);
if (requestedCount == 0) requestedCount = int.MaxValue;
MediaNode node;
if (_resourceCache.TryGetValue(oid, out node))
{
var folder = node as FolderNode;
if (folder == null) return;
var findings =
new XElement(
Didl + "DIDL-Lite",
new XAttribute(XNamespace.Xmlns + "dc", Dc.ToString()),
new XAttribute(XNamespace.Xmlns + "upnp", Upnp.ToString()),
folder.RenderDirectChildren(startingIndex, requestedCount, queryEndpoint, mediaEndpoint)
);
result = findings.ToString();
numberReturned = (uint) findings.Elements().Count();
totalMatches = (uint)folder.Count;
updateId = oid == Guid.Empty ? SystemUpdateId : folder.ContainerUpdateId;
}
}
public ResourceNode GetNodeForId(Guid id)
{
MediaNode node;
_resourceCache.TryGetValue(id, out node);
return node as ResourceNode;
}
#endregion
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the elastictranscoder-2012-09-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticTranscoder.Model
{
/// <summary>
/// The <code>VideoParameters</code> structure.
/// </summary>
public partial class VideoParameters
{
private string _aspectRatio;
private string _bitRate;
private string _codec;
private Dictionary<string, string> _codecOptions = new Dictionary<string, string>();
private string _displayAspectRatio;
private string _fixedGOP;
private string _frameRate;
private string _keyframesMaxDist;
private string _maxFrameRate;
private string _maxHeight;
private string _maxWidth;
private string _paddingPolicy;
private string _resolution;
private string _sizingPolicy;
private List<PresetWatermark> _watermarks = new List<PresetWatermark>();
/// <summary>
/// Gets and sets the property AspectRatio. <important>
/// <para>
/// To better control resolution and aspect ratio of output videos, we recommend that
/// you use the values <code>MaxWidth</code>, <code>MaxHeight</code>, <code>SizingPolicy</code>,
/// <code>PaddingPolicy</code>, and <code>DisplayAspectRatio</code> instead of <code>Resolution</code>
/// and <code>AspectRatio</code>. The two groups of settings are mutually exclusive. Do
/// not use them together.
/// </para>
/// </important>
/// <para>
/// The display aspect ratio of the video in the output file. Valid values include:
/// </para>
///
/// <para>
/// <code>auto</code>, <code>1:1</code>, <code>4:3</code>, <code>3:2</code>, <code>16:9</code>
/// </para>
///
/// <para>
/// If you specify <code>auto</code>, Elastic Transcoder tries to preserve the aspect
/// ratio of the input file.
/// </para>
///
/// <para>
/// If you specify an aspect ratio for the output file that differs from aspect ratio
/// of the input file, Elastic Transcoder adds pillarboxing (black bars on the sides)
/// or letterboxing (black bars on the top and bottom) to maintain the aspect ratio of
/// the active region of the video.
/// </para>
/// </summary>
public string AspectRatio
{
get { return this._aspectRatio; }
set { this._aspectRatio = value; }
}
// Check to see if AspectRatio property is set
internal bool IsSetAspectRatio()
{
return this._aspectRatio != null;
}
/// <summary>
/// Gets and sets the property BitRate.
/// <para>
/// The bit rate of the video stream in the output file, in kilobits/second. Valid values
/// depend on the values of <code>Level</code> and <code>Profile</code>. If you specify
/// <code>auto</code>, Elastic Transcoder uses the detected bit rate of the input source.
/// If you specify a value other than <code>auto</code>, we recommend that you specify
/// a value less than or equal to the maximum H.264-compliant value listed for your level
/// and profile:
/// </para>
///
/// <para>
/// <i>Level - Maximum video bit rate in kilobits/second (baseline and main Profile)
/// : maximum video bit rate in kilobits/second (high Profile)</i>
/// </para>
/// <ul> <li>1 - 64 : 80</li> <li>1b - 128 : 160</li> <li>1.1 - 192 : 240</li> <li>1.2
/// - 384 : 480</li> <li>1.3 - 768 : 960</li> <li>2 - 2000 : 2500</li> <li>3 - 10000 :
/// 12500</li> <li>3.1 - 14000 : 17500</li> <li>3.2 - 20000 : 25000</li> <li>4 - 20000
/// : 25000</li> <li>4.1 - 50000 : 62500</li> </ul>
/// </summary>
public string BitRate
{
get { return this._bitRate; }
set { this._bitRate = value; }
}
// Check to see if BitRate property is set
internal bool IsSetBitRate()
{
return this._bitRate != null;
}
/// <summary>
/// Gets and sets the property Codec.
/// <para>
/// The video codec for the output file. Valid values include <code>gif</code>, <code>H.264</code>,
/// <code>mpeg2</code>, and <code>vp8</code>. You can only specify <code>vp8</code> when
/// the container type is <code>webm</code>, <code>gif</code> when the container type
/// is <code>gif</code>, and <code>mpeg2</code> when the container type is <code>mpg</code>.
/// </para>
/// </summary>
public string Codec
{
get { return this._codec; }
set { this._codec = value; }
}
// Check to see if Codec property is set
internal bool IsSetCodec()
{
return this._codec != null;
}
/// <summary>
/// Gets and sets the property CodecOptions.
/// <para>
/// <b>Profile (H.264/VP8 Only)</b>
/// </para>
///
/// <para>
/// The H.264 profile that you want to use for the output file. Elastic Transcoder supports
/// the following profiles:
/// </para>
/// <ul> <li> <code>baseline</code>: The profile most commonly used for videoconferencing
/// and for mobile applications.</li> <li> <code>main</code>: The profile used for standard-definition
/// digital TV broadcasts.</li> <li> <code>high</code>: The profile used for high-definition
/// digital TV broadcasts and for Blu-ray discs.</li> </ul>
/// <para>
/// <b>Level (H.264 Only)</b>
/// </para>
///
/// <para>
/// The H.264 level that you want to use for the output file. Elastic Transcoder supports
/// the following levels:
/// </para>
///
/// <para>
/// <code>1</code>, <code>1b</code>, <code>1.1</code>, <code>1.2</code>, <code>1.3</code>,
/// <code>2</code>, <code>2.1</code>, <code>2.2</code>, <code>3</code>, <code>3.1</code>,
/// <code>3.2</code>, <code>4</code>, <code>4.1</code>
/// </para>
///
/// <para>
/// <b>MaxReferenceFrames (H.264 Only)</b>
/// </para>
///
/// <para>
/// Applicable only when the value of Video:Codec is H.264. The maximum number of previously
/// decoded frames to use as a reference for decoding future frames. Valid values are
/// integers 0 through 16, but we recommend that you not use a value greater than the
/// following:
/// </para>
///
/// <para>
/// <code>Min(Floor(Maximum decoded picture buffer in macroblocks * 256 / (Width in pixels
/// * Height in pixels)), 16)</code>
/// </para>
///
/// <para>
/// where <i>Width in pixels</i> and <i>Height in pixels</i> represent either MaxWidth
/// and MaxHeight, or Resolution. <i>Maximum decoded picture buffer in macroblocks</i>
/// depends on the value of the <code>Level</code> object. See the list below. (A macroblock
/// is a block of pixels measuring 16x16.)
/// </para>
/// <ul> <li>1 - 396</li> <li>1b - 396</li> <li>1.1 - 900</li> <li>1.2 - 2376</li> <li>1.3
/// - 2376</li> <li>2 - 2376</li> <li>2.1 - 4752</li> <li>2.2 - 8100</li> <li>3 - 8100</li>
/// <li>3.1 - 18000</li> <li>3.2 - 20480</li> <li>4 - 32768</li> <li>4.1 - 32768</li>
/// </ul>
/// <para>
/// <b>MaxBitRate (Optional, H.264/MPEG2/VP8 only)</b>
/// </para>
///
/// <para>
/// The maximum number of bits per second in a video buffer; the size of the buffer is
/// specified by <code>BufferSize</code>. Specify a value between 16 and 62,500. You can
/// reduce the bandwidth required to stream a video by reducing the maximum bit rate,
/// but this also reduces the quality of the video.
/// </para>
///
/// <para>
/// <b>BufferSize (Optional, H.264/MPEG2/VP8 only)</b>
/// </para>
///
/// <para>
/// The maximum number of bits in any x seconds of the output video. This window is commonly
/// 10 seconds, the standard segment duration when you're using FMP4 or MPEG-TS for the
/// container type of the output video. Specify an integer greater than 0. If you specify
/// <code>MaxBitRate</code> and omit <code>BufferSize</code>, Elastic Transcoder sets
/// <code>BufferSize</code> to 10 times the value of <code>MaxBitRate</code>.
/// </para>
///
/// <para>
/// <b>InterlacedMode (Optional, H.264/MPEG2 Only)</b>
/// </para>
///
/// <para>
/// The interlace mode for the output video.
/// </para>
///
/// <para>
/// Interlaced video is used to double the perceived frame rate for a video by interlacing
/// two fields (one field on every other line, the other field on the other lines) so
/// that the human eye registers multiple pictures per frame. Interlacing reduces the
/// bandwidth required for transmitting a video, but can result in blurred images and
/// flickering.
/// </para>
///
/// <para>
/// Valid values include <code>Progressive</code> (no interlacing, top to bottom), <code>TopFirst</code>
/// (top field first), <code>BottomFirst</code> (bottom field first), and <code>Auto</code>.
/// </para>
///
/// <para>
/// If <code>InterlaceMode</code> is not specified, Elastic Transcoder uses <code>Progressive</code>
/// for the output. If <code>Auto</code> is specified, Elastic Transcoder interlaces the
/// output.
/// </para>
///
/// <para>
/// <b>ColorSpaceConversionMode (Optional, H.264/MPEG2 Only)</b>
/// </para>
///
/// <para>
/// The color space conversion Elastic Transcoder applies to the output video. Color spaces
/// are the algorithms used by the computer to store information about how to render color.
/// <code>Bt.601</code> is the standard for standard definition video, while <code>Bt.709</code>
/// is the standard for high definition video.
/// </para>
///
/// <para>
/// Valid values include <code>None</code>, <code>Bt709toBt601</code>, <code>Bt601toBt709</code>,
/// and <code>Auto</code>.
/// </para>
///
/// <para>
/// If you chose <code>Auto</code> for <code>ColorSpaceConversionMode</code> and your
/// output is interlaced, your frame rate is one of <code>23.97</code>, <code>24</code>,
/// <code>25</code>, <code>29.97</code>, <code>50</code>, or <code>60</code>, your <code>SegmentDuration</code>
/// is null, and you are using one of the resolution changes from the list below, Elastic
/// Transcoder applies the following color space conversions:
/// </para>
/// <ul> <li> <i>Standard to HD, 720x480 to 1920x1080</i> - Elastic Transcoder applies
/// <code>Bt601ToBt709</code> </li> <li> <i>Standard to HD, 720x576 to 1920x1080</i> -
/// Elastic Transcoder applies <code>Bt601ToBt709</code> </li> <li> <i>HD to Standard,
/// 1920x1080 to 720x480</i> - Elastic Transcoder applies <code>Bt709ToBt601</code> </li>
/// <li> <i>HD to Standard, 1920x1080 to 720x576</i> - Elastic Transcoder applies <code>Bt709ToBt601</code>
/// </li> </ul> <note>Elastic Transcoder may change the behavior of the <code>ColorspaceConversionMode</code>
/// <code>Auto</code> mode in the future. All outputs in a playlist must use the same
/// <code>ColorSpaceConversionMode</code>.</note>
/// <para>
/// If you do not specify a <code>ColorSpaceConversionMode</code>, Elastic Transcoder
/// does not change the color space of a file. If you are unsure what <code>ColorSpaceConversionMode</code>
/// was applied to your output file, you can check the <code>AppliedColorSpaceConversion</code>
/// parameter included in your job response. If your job does not have an <code>AppliedColorSpaceConversion</code>
/// in its response, no <code>ColorSpaceConversionMode</code> was applied.
/// </para>
///
/// <para>
/// <b>ChromaSubsampling</b>
/// </para>
///
/// <para>
/// The sampling pattern for the chroma (color) channels of the output video. Valid values
/// include <code>yuv420p</code> and <code>yuv422p</code>.
/// </para>
///
/// <para>
/// <code>yuv420p</code> samples the chroma information of every other horizontal and
/// every other vertical line, <code>yuv422p</code> samples the color information of every
/// horizontal line and every other vertical line.
/// </para>
///
/// <para>
/// <b>LoopCount (Gif Only)</b>
/// </para>
///
/// <para>
/// The number of times you want the output gif to loop. Valid values include <code>Infinite</code>
/// and integers between <code>0</code> and <code>100</code>, inclusive.
/// </para>
/// </summary>
public Dictionary<string, string> CodecOptions
{
get { return this._codecOptions; }
set { this._codecOptions = value; }
}
// Check to see if CodecOptions property is set
internal bool IsSetCodecOptions()
{
return this._codecOptions != null && this._codecOptions.Count > 0;
}
/// <summary>
/// Gets and sets the property DisplayAspectRatio.
/// <para>
/// The value that Elastic Transcoder adds to the metadata in the output file.
/// </para>
/// </summary>
public string DisplayAspectRatio
{
get { return this._displayAspectRatio; }
set { this._displayAspectRatio = value; }
}
// Check to see if DisplayAspectRatio property is set
internal bool IsSetDisplayAspectRatio()
{
return this._displayAspectRatio != null;
}
/// <summary>
/// Gets and sets the property FixedGOP.
/// <para>
/// Applicable only when the value of Video:Codec is one of <code>H.264</code>, <code>MPEG2</code>,
/// or <code>VP8</code>.
/// </para>
///
/// <para>
/// Whether to use a fixed value for <code>FixedGOP</code>. Valid values are <code>true</code>
/// and <code>false</code>:
/// </para>
/// <ul> <li> <code>true</code>: Elastic Transcoder uses the value of <code>KeyframesMaxDist</code>
/// for the distance between key frames (the number of frames in a group of pictures,
/// or GOP).</li> <li> <code>false</code>: The distance between key frames can vary.</li>
/// </ul> <important>
/// <para>
/// <code>FixedGOP</code> must be set to <code>true</code> for <code>fmp4</code> containers.
/// </para>
/// </important>
/// </summary>
public string FixedGOP
{
get { return this._fixedGOP; }
set { this._fixedGOP = value; }
}
// Check to see if FixedGOP property is set
internal bool IsSetFixedGOP()
{
return this._fixedGOP != null;
}
/// <summary>
/// Gets and sets the property FrameRate.
/// <para>
/// The frames per second for the video stream in the output file. Valid values include:
/// </para>
///
/// <para>
/// <code>auto</code>, <code>10</code>, <code>15</code>, <code>23.97</code>, <code>24</code>,
/// <code>25</code>, <code>29.97</code>, <code>30</code>, <code>60</code>
/// </para>
///
/// <para>
/// If you specify <code>auto</code>, Elastic Transcoder uses the detected frame rate
/// of the input source. If you specify a frame rate, we recommend that you perform the
/// following calculation:
/// </para>
///
/// <para>
/// <code>Frame rate = maximum recommended decoding speed in luma samples/second / (width
/// in pixels * height in pixels)</code>
/// </para>
///
/// <para>
/// where:
/// </para>
/// <ul> <li> <i>width in pixels</i> and <i>height in pixels</i> represent the Resolution
/// of the output video.</li> <li> <i>maximum recommended decoding speed in Luma samples/second</i>
/// is less than or equal to the maximum value listed in the following table, based on
/// the value that you specified for Level.</li> </ul>
/// <para>
/// The maximum recommended decoding speed in Luma samples/second for each level is described
/// in the following list (<i>Level - Decoding speed</i>):
/// </para>
/// <ul> <li>1 - 380160</li> <li>1b - 380160</li> <li>1.1 - 76800</li> <li>1.2 - 1536000</li>
/// <li>1.3 - 3041280</li> <li>2 - 3041280</li> <li>2.1 - 5068800</li> <li>2.2 - 5184000</li>
/// <li>3 - 10368000</li> <li>3.1 - 27648000</li> <li>3.2 - 55296000</li> <li>4 - 62914560</li>
/// <li>4.1 - 62914560</li> </ul>
/// </summary>
public string FrameRate
{
get { return this._frameRate; }
set { this._frameRate = value; }
}
// Check to see if FrameRate property is set
internal bool IsSetFrameRate()
{
return this._frameRate != null;
}
/// <summary>
/// Gets and sets the property KeyframesMaxDist.
/// <para>
/// Applicable only when the value of Video:Codec is one of <code>H.264</code>, <code>MPEG2</code>,
/// or <code>VP8</code>.
/// </para>
///
/// <para>
/// The maximum number of frames between key frames. Key frames are fully encoded frames;
/// the frames between key frames are encoded based, in part, on the content of the key
/// frames. The value is an integer formatted as a string; valid values are between 1
/// (every frame is a key frame) and 100000, inclusive. A higher value results in higher
/// compression but may also discernibly decrease video quality.
/// </para>
///
/// <para>
/// For <code>Smooth</code> outputs, the <code>FrameRate</code> must have a constant ratio
/// to the <code>KeyframesMaxDist</code>. This allows <code>Smooth</code> playlists to
/// switch between different quality levels while the file is being played.
/// </para>
///
/// <para>
/// For example, an input file can have a <code>FrameRate</code> of 30 with a <code>KeyframesMaxDist</code>
/// of 90. The output file then needs to have a ratio of 1:3. Valid outputs would have
/// <code>FrameRate</code> of 30, 25, and 10, and <code>KeyframesMaxDist</code> of 90,
/// 75, and 30, respectively.
/// </para>
///
/// <para>
/// Alternately, this can be achieved by setting <code>FrameRate</code> to auto and having
/// the same values for <code>MaxFrameRate</code> and <code>KeyframesMaxDist</code>.
/// </para>
/// </summary>
public string KeyframesMaxDist
{
get { return this._keyframesMaxDist; }
set { this._keyframesMaxDist = value; }
}
// Check to see if KeyframesMaxDist property is set
internal bool IsSetKeyframesMaxDist()
{
return this._keyframesMaxDist != null;
}
/// <summary>
/// Gets and sets the property MaxFrameRate.
/// <para>
/// If you specify <code>auto</code> for <code>FrameRate</code>, Elastic Transcoder uses
/// the frame rate of the input video for the frame rate of the output video. Specify
/// the maximum frame rate that you want Elastic Transcoder to use when the frame rate
/// of the input video is greater than the desired maximum frame rate of the output video.
/// Valid values include: <code>10</code>, <code>15</code>, <code>23.97</code>, <code>24</code>,
/// <code>25</code>, <code>29.97</code>, <code>30</code>, <code>60</code>.
/// </para>
/// </summary>
public string MaxFrameRate
{
get { return this._maxFrameRate; }
set { this._maxFrameRate = value; }
}
// Check to see if MaxFrameRate property is set
internal bool IsSetMaxFrameRate()
{
return this._maxFrameRate != null;
}
/// <summary>
/// Gets and sets the property MaxHeight.
/// <para>
/// The maximum height of the output video in pixels. If you specify <code>auto</code>,
/// Elastic Transcoder uses 1080 (Full HD) as the default value. If you specify a numeric
/// value, enter an even integer between 96 and 3072.
/// </para>
/// </summary>
public string MaxHeight
{
get { return this._maxHeight; }
set { this._maxHeight = value; }
}
// Check to see if MaxHeight property is set
internal bool IsSetMaxHeight()
{
return this._maxHeight != null;
}
/// <summary>
/// Gets and sets the property MaxWidth.
/// <para>
/// The maximum width of the output video in pixels. If you specify <code>auto</code>,
/// Elastic Transcoder uses 1920 (Full HD) as the default value. If you specify a numeric
/// value, enter an even integer between 128 and 4096.
/// </para>
/// </summary>
public string MaxWidth
{
get { return this._maxWidth; }
set { this._maxWidth = value; }
}
// Check to see if MaxWidth property is set
internal bool IsSetMaxWidth()
{
return this._maxWidth != null;
}
/// <summary>
/// Gets and sets the property PaddingPolicy.
/// <para>
/// When you set <code>PaddingPolicy</code> to <code>Pad</code>, Elastic Transcoder may
/// add black bars to the top and bottom and/or left and right sides of the output video
/// to make the total size of the output video match the values that you specified for
/// <code>MaxWidth</code> and <code>MaxHeight</code>.
/// </para>
/// </summary>
public string PaddingPolicy
{
get { return this._paddingPolicy; }
set { this._paddingPolicy = value; }
}
// Check to see if PaddingPolicy property is set
internal bool IsSetPaddingPolicy()
{
return this._paddingPolicy != null;
}
/// <summary>
/// Gets and sets the property Resolution. <important>
/// <para>
/// To better control resolution and aspect ratio of output videos, we recommend that
/// you use the values <code>MaxWidth</code>, <code>MaxHeight</code>, <code>SizingPolicy</code>,
/// <code>PaddingPolicy</code>, and <code>DisplayAspectRatio</code> instead of <code>Resolution</code>
/// and <code>AspectRatio</code>. The two groups of settings are mutually exclusive. Do
/// not use them together.
/// </para>
/// </important>
/// <para>
/// The width and height of the video in the output file, in pixels. Valid values are
/// <code>auto</code> and <i>width</i> x <i>height</i>:
/// </para>
/// <ul> <li> <code>auto</code>: Elastic Transcoder attempts to preserve the width and
/// height of the input file, subject to the following rules.</li> <li> <code><i>width</i>
/// x <i>height</i></code>: The width and height of the output video in pixels.</li> </ul>
///
/// <para>
/// Note the following about specifying the width and height:
/// </para>
/// <ul> <li>The width must be an even integer between 128 and 4096, inclusive.</li>
/// <li>The height must be an even integer between 96 and 3072, inclusive.</li> <li>If
/// you specify a resolution that is less than the resolution of the input file, Elastic
/// Transcoder rescales the output file to the lower resolution.</li> <li>If you specify
/// a resolution that is greater than the resolution of the input file, Elastic Transcoder
/// rescales the output to the higher resolution.</li> <li>We recommend that you specify
/// a resolution for which the product of width and height is less than or equal to the
/// applicable value in the following list (<i>List - Max width x height value</i>):</li>
/// <ul> <li>1 - 25344</li> <li>1b - 25344</li> <li>1.1 - 101376</li> <li>1.2 - 101376</li>
/// <li>1.3 - 101376</li> <li>2 - 101376</li> <li>2.1 - 202752</li> <li>2.2 - 404720</li>
/// <li>3 - 404720</li> <li>3.1 - 921600</li> <li>3.2 - 1310720</li> <li>4 - 2097152</li>
/// <li>4.1 - 2097152</li> </ul> </ul>
/// </summary>
public string Resolution
{
get { return this._resolution; }
set { this._resolution = value; }
}
// Check to see if Resolution property is set
internal bool IsSetResolution()
{
return this._resolution != null;
}
/// <summary>
/// Gets and sets the property SizingPolicy.
/// <para>
/// Specify one of the following values to control scaling of the output video:
/// </para>
///
/// <para>
/// <ul> <li> <code>Fit</code>: Elastic Transcoder scales the output video so it matches
/// the value that you specified in either <code>MaxWidth</code> or <code>MaxHeight</code>
/// without exceeding the other value.</li> <li> <code>Fill</code>: Elastic Transcoder
/// scales the output video so it matches the value that you specified in either <code>MaxWidth</code>
/// or <code>MaxHeight</code> and matches or exceeds the other value. Elastic Transcoder
/// centers the output video and then crops it in the dimension (if any) that exceeds
/// the maximum value.</li> <li> <code>Stretch</code>: Elastic Transcoder stretches the
/// output video to match the values that you specified for <code>MaxWidth</code> and
/// <code>MaxHeight</code>. If the relative proportions of the input video and the output
/// video are different, the output video will be distorted.</li> <li> <code>Keep</code>:
/// Elastic Transcoder does not scale the output video. If either dimension of the input
/// video exceeds the values that you specified for <code>MaxWidth</code> and <code>MaxHeight</code>,
/// Elastic Transcoder crops the output video.</li> <li> <code>ShrinkToFit</code>: Elastic
/// Transcoder scales the output video down so that its dimensions match the values that
/// you specified for at least one of <code>MaxWidth</code> and <code>MaxHeight</code>
/// without exceeding either value. If you specify this option, Elastic Transcoder does
/// not scale the video up.</li> <li> <code>ShrinkToFill</code>: Elastic Transcoder scales
/// the output video down so that its dimensions match the values that you specified for
/// at least one of <code>MaxWidth</code> and <code>MaxHeight</code> without dropping
/// below either value. If you specify this option, Elastic Transcoder does not scale
/// the video up.</li> </ul>
/// </para>
/// </summary>
public string SizingPolicy
{
get { return this._sizingPolicy; }
set { this._sizingPolicy = value; }
}
// Check to see if SizingPolicy property is set
internal bool IsSetSizingPolicy()
{
return this._sizingPolicy != null;
}
/// <summary>
/// Gets and sets the property Watermarks.
/// <para>
/// Settings for the size, location, and opacity of graphics that you want Elastic Transcoder
/// to overlay over videos that are transcoded using this preset. You can specify settings
/// for up to four watermarks. Watermarks appear in the specified size and location, and
/// with the specified opacity for the duration of the transcoded video.
/// </para>
///
/// <para>
/// Watermarks can be in .png or .jpg format. If you want to display a watermark that
/// is not rectangular, use the .png format, which supports transparency.
/// </para>
///
/// <para>
/// When you create a job that uses this preset, you specify the .png or .jpg graphics
/// that you want Elastic Transcoder to include in the transcoded videos. You can specify
/// fewer graphics in the job than you specify watermark settings in the preset, which
/// allows you to use the same preset for up to four watermarks that have different dimensions.
/// </para>
/// </summary>
public List<PresetWatermark> Watermarks
{
get { return this._watermarks; }
set { this._watermarks = value; }
}
// Check to see if Watermarks property is set
internal bool IsSetWatermarks()
{
return this._watermarks != null && this._watermarks.Count > 0;
}
}
}
| |
// 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.Concurrent;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml;
using System.Xml.Serialization;
namespace WcfService
{
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class RpcEncSingleNsService : ICalculatorRpcEnc
{
private static ConcurrentDictionary<Guid, object> s_sessions = new ConcurrentDictionary<Guid, object>();
[OperationBehavior]
public int Sum2(int i, int j)
{
return i + j;
}
[OperationBehavior]
public int Sum(IntParams par)
{
return par.P1 + par.P2;
}
[OperationBehavior]
public float Divide(FloatParams par)
{
return (float)(par.P1 / par.P2);
}
[OperationBehavior]
public string Concatenate(IntParams par)
{
return string.Format("{0}{1}", par.P1, par.P2);
}
[OperationBehavior]
public void AddIntParams(Guid guid, IntParams par)
{
if (!s_sessions.TryAdd(guid, par))
{
throw new InvalidOperationException(string.Format("Guid {0} already existed, and the value was {1}.", guid, s_sessions[guid]));
}
}
[OperationBehavior]
public IntParams GetAndRemoveIntParams(Guid guid)
{
object value;
s_sessions.TryRemove(guid, out value);
return value as IntParams;
}
[OperationBehavior]
public DateTime ReturnInputDateTime(DateTime dt)
{
return dt;
}
[OperationBehavior]
public byte[] CreateSet(ByteParams par)
{
return new byte[] { par.P1, par.P2 };
}
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class RpcLitSingleNsService : ICalculatorRpcLit
{
private static ConcurrentDictionary<Guid, object> s_sessions = new ConcurrentDictionary<Guid, object>();
[OperationBehavior]
public int Sum2(int i, int j)
{
return i + j;
}
[OperationBehavior]
public int Sum(IntParams par)
{
return par.P1 + par.P2;
}
[OperationBehavior]
public float Divide(FloatParams par)
{
return (float)(par.P1 / par.P2);
}
[OperationBehavior]
public string Concatenate(IntParams par)
{
return string.Format("{0}{1}", par.P1, par.P2);
}
[OperationBehavior]
public void AddIntParams(Guid guid, IntParams par)
{
if (!s_sessions.TryAdd(guid, par))
{
throw new InvalidOperationException(string.Format("Guid {0} already existed, and the value was {1}.", guid, s_sessions[guid]));
}
}
[OperationBehavior]
public IntParams GetAndRemoveIntParams(Guid guid)
{
object value;
s_sessions.TryRemove(guid, out value);
return value as IntParams;
}
[OperationBehavior]
public DateTime ReturnInputDateTime(DateTime dt)
{
return dt;
}
[OperationBehavior]
public byte[] CreateSet(ByteParams par)
{
return new byte[] { par.P1, par.P2 };
}
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class DocLitSingleNsService : ICalculatorDocLit
{
private static ConcurrentDictionary<Guid, object> s_sessions = new ConcurrentDictionary<Guid, object>();
[OperationBehavior]
public int Sum2(int i, int j)
{
return i + j;
}
[OperationBehavior]
public int Sum(IntParams par)
{
return par.P1 + par.P2;
}
[OperationBehavior]
public float Divide(FloatParams par)
{
return (float)(par.P1 / par.P2);
}
[OperationBehavior]
public string Concatenate(IntParams par)
{
return string.Format("{0}{1}", par.P1, par.P2);
}
[OperationBehavior]
public void AddIntParams(Guid guid, IntParams par)
{
if (!s_sessions.TryAdd(guid, par))
{
throw new InvalidOperationException(string.Format("Guid {0} already existed, and the value was {1}.", guid, s_sessions[guid]));
}
}
[OperationBehavior]
public IntParams GetAndRemoveIntParams(Guid guid)
{
object value;
s_sessions.TryRemove(guid, out value);
return value as IntParams;
}
[OperationBehavior]
public DateTime ReturnInputDateTime(DateTime dt)
{
return dt;
}
[OperationBehavior]
public byte[] CreateSet(ByteParams par)
{
return new byte[] { par.P1, par.P2 };
}
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class RpcEncDualNsService : ICalculatorRpcEnc, IHelloWorldRpcEnc
{
private static ConcurrentDictionary<Guid, object> s_sessions = new ConcurrentDictionary<Guid, object>();
[OperationBehavior]
public int Sum2(int i, int j)
{
return i + j;
}
[OperationBehavior]
public int Sum(IntParams par)
{
return par.P1 + par.P2;
}
[OperationBehavior]
public float Divide(FloatParams par)
{
return (float)(par.P1 / par.P2);
}
[OperationBehavior]
public string Concatenate(IntParams par)
{
return string.Format("{0}{1}", par.P1, par.P2);
}
[OperationBehavior]
public void AddIntParams(Guid guid, IntParams par)
{
if (!s_sessions.TryAdd(guid, par))
{
throw new InvalidOperationException(string.Format("Guid {0} already existed, and the value was {1}.", guid, s_sessions[guid]));
}
}
[OperationBehavior]
public IntParams GetAndRemoveIntParams(Guid guid)
{
object value;
s_sessions.TryRemove(guid, out value);
return value as IntParams;
}
[OperationBehavior]
public DateTime ReturnInputDateTime(DateTime dt)
{
return dt;
}
[OperationBehavior]
public byte[] CreateSet(ByteParams par)
{
return new byte[] { par.P1, par.P2 };
}
[OperationBehavior]
public void AddString(Guid guid, string testString)
{
if (!s_sessions.TryAdd(guid, testString))
{
throw new InvalidOperationException(string.Format("Guid {0} already existed, and the value was {1}.", guid, s_sessions[guid]));
}
}
[OperationBehavior]
public string GetAndRemoveString(Guid guid)
{
object value;
s_sessions.TryRemove(guid, out value);
return value as string;
}
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class RpcLitDualNsService : ICalculatorRpcLit, IHelloWorldRpcLit
{
private static ConcurrentDictionary<Guid, object> s_sessions = new ConcurrentDictionary<Guid, object>();
[OperationBehavior]
public int Sum2(int i, int j)
{
return i + j;
}
[OperationBehavior]
public int Sum(IntParams par)
{
return par.P1 + par.P2;
}
[OperationBehavior]
public float Divide(FloatParams par)
{
return (float)(par.P1 / par.P2);
}
[OperationBehavior]
public string Concatenate(IntParams par)
{
return string.Format("{0}{1}", par.P1, par.P2);
}
[OperationBehavior]
public void AddIntParams(Guid guid, IntParams par)
{
if (!s_sessions.TryAdd(guid, par))
{
throw new InvalidOperationException(string.Format("Guid {0} already existed, and the value was {1}.", guid, s_sessions[guid]));
}
}
[OperationBehavior]
public IntParams GetAndRemoveIntParams(Guid guid)
{
object value;
s_sessions.TryRemove(guid, out value);
return value as IntParams;
}
[OperationBehavior]
public DateTime ReturnInputDateTime(DateTime dt)
{
return dt;
}
[OperationBehavior]
public byte[] CreateSet(ByteParams par)
{
return new byte[] { par.P1, par.P2 };
}
[OperationBehavior]
public void AddString(Guid guid, string testString)
{
if (!s_sessions.TryAdd(guid, testString))
{
throw new InvalidOperationException(string.Format("Guid {0} already existed, and the value was {1}.", guid, s_sessions[guid]));
}
}
[OperationBehavior]
public string GetAndRemoveString(Guid guid)
{
object value;
s_sessions.TryRemove(guid, out value);
return value as string;
}
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class DocLitDualNsService : ICalculatorDocLit, IHelloWorldDocLit
{
private static ConcurrentDictionary<Guid, object> s_sessions = new ConcurrentDictionary<Guid, object>();
[OperationBehavior]
public int Sum2(int i, int j)
{
return i + j;
}
[OperationBehavior]
public int Sum(IntParams par)
{
return par.P1 + par.P2;
}
[OperationBehavior]
public float Divide(FloatParams par)
{
return (float)(par.P1 / par.P2);
}
[OperationBehavior]
public string Concatenate(IntParams par)
{
return string.Format("{0}{1}", par.P1, par.P2);
}
[OperationBehavior]
public void AddIntParams(Guid guid, IntParams par)
{
if (!s_sessions.TryAdd(guid, par))
{
throw new InvalidOperationException(string.Format("Guid {0} already existed, and the value was {1}.", guid, s_sessions[guid]));
}
}
[OperationBehavior]
public IntParams GetAndRemoveIntParams(Guid guid)
{
object value;
s_sessions.TryRemove(guid, out value);
return value as IntParams;
}
[OperationBehavior]
public DateTime ReturnInputDateTime(DateTime dt)
{
return dt;
}
[OperationBehavior]
public byte[] CreateSet(ByteParams par)
{
return new byte[] { par.P1, par.P2 };
}
[OperationBehavior]
public void AddString(Guid guid, string testString)
{
if (!s_sessions.TryAdd(guid, testString))
{
throw new InvalidOperationException(string.Format("Guid {0} already existed, and the value was {1}.", guid, s_sessions[guid]));
}
}
[OperationBehavior]
public string GetAndRemoveString(Guid guid)
{
object value;
s_sessions.TryRemove(guid, out value);
return value as string;
}
}
public class EchoRpcEncWithHeadersService : IEchoRpcEncWithHeadersService
{
static EchoRpcEncWithHeadersService()
{
var member = new XmlReflectionMember
{
MemberName = "StringHeader",
MemberType = typeof(StringHeader),
SoapAttributes = new SoapAttributes { SoapElement = new SoapElementAttribute("StringHeader") }
};
var members = new XmlReflectionMember[] { member };
var mappings = new SoapReflectionImporter().ImportMembersMapping("EchoServiceSoap", "http://tempuri.org/", members, false, false);
var serializers = XmlSerializer.FromMappings(new XmlMembersMapping[] { mappings }, typeof(EchoRpcEncWithHeadersService));
s_stringHeaderSerializer = serializers[0];
}
private static XmlSerializer s_stringHeaderSerializer { get; set; }
public EchoResponse Echo(EchoRequest request)
{
var incomingHeaders = OperationContext.Current.IncomingMessageHeaders;
int headerPos = incomingHeaders.FindHeader("StringHeader", "http://tempuri.org/");
var xmlReader = incomingHeaders.GetReaderAtHeader(headerPos);
var objs = (object[])s_stringHeaderSerializer.Deserialize(xmlReader, "http://schemas.xmlsoap.org/soap/encoding/");
if (objs.Length > 0)
{
var header = (StringHeader)objs[0];
MessageHeader responseHeader = CreateHeader(new StringHeader { HeaderValue = header.HeaderValue + header.HeaderValue });
OperationContext.Current.OutgoingMessageHeaders.Add(responseHeader);
}
return new EchoResponse { EchoResult = request.message };
}
private MessageHeader CreateHeader(StringHeader header)
{
MemoryStream memoryStream = new MemoryStream();
XmlDictionaryWriter bufferWriter = XmlDictionaryWriter.CreateTextWriter(memoryStream);
bufferWriter.WriteStartElement("root");
XmlSerializerNamespaces xs = new XmlSerializerNamespaces();
xs.Add("", "");
xs.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
xs.Add("xsd", "http://www.w3.org/2001/XMLSchema");
xs.Add("tns", "http://tempuri.org/");
s_stringHeaderSerializer.Serialize(bufferWriter, new object[] { header }, xs, "http://schemas.xmlsoap.org/soap/encoding/");
bufferWriter.WriteEndElement();
bufferWriter.Flush();
XmlDocument doc = new XmlDocument();
memoryStream.Position = 0;
doc.Load(new XmlTextReader(memoryStream) { DtdProcessing = DtdProcessing.Prohibit });
XmlElement stringHeaderElement = doc.DocumentElement.ChildNodes[0] as XmlElement;
return new XmlElementMessageHeader("StringHeader", "http://tempuri.org/", stringHeaderElement);
}
public class XmlElementMessageHeader : MessageHeader
{
MessageHeader innerHeader;
private XmlElement _headerValue;
public XmlElementMessageHeader(string name, string ns, XmlElement headerValue)
{
innerHeader = CreateHeader(name, ns, null, false, "", false);
_headerValue = headerValue;
}
public override string Name { get { return innerHeader.Name; } }
public override string Namespace { get { return innerHeader.Namespace; } }
public override bool MustUnderstand { get { return innerHeader.MustUnderstand; } }
public override bool Relay { get { return innerHeader.Relay; } }
public override string Actor { get { return innerHeader.Actor; } }
protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
writer.WriteStartElement("tns", Name, Namespace);
writer.WriteStartAttribute("tns", Name, Namespace);
OnWriteHeaderAttributes(writer, messageVersion);
}
protected void OnWriteHeaderAttributes(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
base.WriteHeaderAttributes(writer, messageVersion);
XmlDictionaryReader nodeReader = XmlDictionaryReader.CreateDictionaryReader(new XmlNodeReader(_headerValue));
nodeReader.MoveToContent();
writer.WriteAttributes(nodeReader, false);
}
protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
{
_headerValue.WriteContentTo(writer);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TWCore.Collections;
using TWCore.Messaging.Configuration;
using TWCore.Messaging.NATS;
using TWCore.Serialization;
using TWCore.Services;
// ReSharper disable ConvertToConstant.Local
// ReSharper disable UnusedMember.Global
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedVariable
// ReSharper disable AccessToDisposedClosure
namespace TWCore.Tests
{
/// <inheritdoc />
public class NATSTest : ContainerParameterService
{
public NATSTest() : base("natstest", "NATS Test") { }
protected override void OnHandler(ParameterHandlerInfo info)
{
Core.Log.Warning("Starting NATS Test");
#region Set Config
var mqConfig = new MQPairConfig
{
Name = "QueueTest",
Types = new MQObjectTypes { ClientType = typeof(NATSQueueClient), ServerType = typeof(NATSQueueServer) },
RawTypes = new MQObjectTypes { ClientType = typeof(NATSQueueRawClient), ServerType = typeof(NATSQueueRawServer) },
ClientQueues = new List<MQClientQueues>
{
new MQClientQueues
{
EnvironmentName = "",
MachineName = "",
SendQueues = new List<MQConnection> { new MQConnection("localhost:4222", "TEST_RQ", null) },
RecvQueue = new MQConnection("localhost:4222", "TEST_RS", null)
}
},
ServerQueues = new List<MQServerQueues>
{
new MQServerQueues
{
EnvironmentName = "",
MachineName = "",
RecvQueues = new List<MQConnection> { new MQConnection("localhost:4222", "TEST_RQ", null) }
}
},
RequestOptions = new MQRequestOptions
{
SerializerMimeType = SerializerManager.DefaultBinarySerializer.MimeTypes[0],
//CompressorEncodingType = "gzip",
ClientSenderOptions = new MQClientSenderOptions
{
Label = "TEST REQUEST",
MessageExpirationInSec = 30,
MessagePriority = MQMessagePriority.Normal,
Recoverable = false
},
ServerReceiverOptions = new MQServerReceiverOptions
{
MaxSimultaneousMessagesPerQueue = 20000,
ProcessingWaitOnFinalizeInSec = 10,
SleepOnExceptionInSec = 1000
}
},
ResponseOptions = new MQResponseOptions
{
SerializerMimeType = SerializerManager.DefaultBinarySerializer.MimeTypes[0],
//CompressorEncodingType = "gzip",
ClientReceiverOptions = new MQClientReceiverOptions(60,
new KeyValue<string, string>("SingleResponseQueue", "true")
),
ServerSenderOptions = new MQServerSenderOptions
{
Label = "TEST RESPONSE",
MessageExpirationInSec = 30,
MessagePriority = MQMessagePriority.Normal,
Recoverable = false
}
}
};
#endregion
JsonTextSerializerExtensions.Serializer.Indent = true;
mqConfig.SerializeToXmlFile("natsConfig.xml");
mqConfig.SerializeToJsonFile("natsConfig.json");
var manager = mqConfig.GetQueueManager();
manager.CreateClientQueues();
//Core.DebugMode = true;
//Core.Log.MaxLogLevel = Diagnostics.Log.LogLevel.InfoDetail;
Core.Log.Warning("Starting with Normal Listener and Client");
NormalTest(mqConfig);
mqConfig.ResponseOptions.ClientReceiverOptions.Parameters["SingleResponseQueue"] = "true";
Core.Log.Warning("Starting with RAW Listener and Client");
RawTest(mqConfig);
}
private static void NormalTest(MQPairConfig mqConfig)
{
using (var mqServer = mqConfig.GetServer())
{
mqServer.RequestReceived += (s, e) =>
{
e.Response.Body = new SerializedObject("Bienvenido!!!");
return Task.CompletedTask;
};
mqServer.StartListeners();
using (var mqClient = mqConfig.GetClient())
{
var totalQ = 2000;
#region Sync Mode
Core.Log.Warning("Sync Mode Test, using Unique Response Queue");
using (var w = Watch.Create($"Hello World Example in Sync Mode for {totalQ} times"))
{
for (var i = 0; i < totalQ; i++)
{
var response = mqClient.SendAndReceiveAsync<string>("Hola mundo").WaitAsync();
}
Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds));
Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ));
}
Console.ReadLine();
#endregion
totalQ = 50000;
#region Parallel Mode
Core.Log.Warning("Parallel Mode Test, using Unique Response Queue");
using (var w = Watch.Create($"Hello World Example in Parallel Mode for {totalQ} times"))
{
Task.WaitAll(
Enumerable.Range(0, totalQ).Select((i, mc) => (Task)mc.SendAndReceiveAsync<string>("Hola mundo"), mqClient).ToArray()
);
//Parallel.For(0, totalQ, i =>
//{
// var response = mqClient.SendAndReceiveAsync<string>("Hola mundo").WaitAndResults();
//});
Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds));
Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ));
}
Console.ReadLine();
#endregion
}
mqConfig.ResponseOptions.ClientReceiverOptions.Parameters["SingleResponseQueue"] = "false";
using (var mqClient = mqConfig.GetClient())
{
var totalQ = 2000;
#region Sync Mode
Core.Log.Warning("Sync Mode Test, using Multiple Response Queue");
using (var w = Watch.Create($"Hello World Example in Sync Mode for {totalQ} times"))
{
for (var i = 0; i < totalQ; i++)
{
var response = mqClient.SendAndReceiveAsync<string>("Hola mundo").WaitAndResults();
}
Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds));
Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ));
}
Console.ReadLine();
#endregion
totalQ = 50000;
#region Parallel Mode
Core.Log.Warning("Parallel Mode Test, using Multiple Response Queue");
using (var w = Watch.Create($"Hello World Example in Parallel Mode for {totalQ} times"))
{
Task.WaitAll(
Enumerable.Range(0, totalQ).Select((i, mc) => (Task)mc.SendAndReceiveAsync<string>("Hola mundo"), mqClient).ToArray()
);
//Parallel.For(0, totalQ, i =>
//{
// var response = mqClient.SendAndReceiveAsync<string>("Hola mundo").WaitAndResults();
//});
Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds));
Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ));
}
Console.ReadLine();
#endregion
}
}
}
private static void RawTest(MQPairConfig mqConfig)
{
using (var mqServer = mqConfig.GetRawServer())
{
var byteRequest = new byte[] { 0x21, 0x22, 0x23, 0x24, 0x25, 0x30, 0x31, 0x32, 0x33, 0x34 };
var byteResponse = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x10, 0x11, 0x12, 0x13, 0x14 };
mqServer.RequestReceived += (s, e) =>
{
e.Response = byteResponse;
return Task.CompletedTask;
};
mqServer.StartListeners();
using (var mqClient = mqConfig.GetRawClient())
{
var totalQ = 2000;
#region Sync Mode
Core.Log.Warning("RAW Sync Mode Test, using Unique Response Queue");
using (var w = Watch.Create($"Hello World Example in Sync Mode for {totalQ} times"))
{
for (var i = 0; i < totalQ; i++)
{
var response = mqClient.SendAndReceiveAsync(byteRequest).WaitAsync();
}
Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds));
Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ));
}
Console.ReadLine();
#endregion
totalQ = 50000;
#region Parallel Mode
Core.Log.Warning("RAW Parallel Mode Test, using Unique Response Queue");
using (var w = Watch.Create($"Hello World Example in Parallel Mode for {totalQ} times"))
{
Task.WaitAll(
Enumerable.Range(0, totalQ).Select((i, vTuple) => (Task)vTuple.mqClient.SendAndReceiveAsync(vTuple.byteRequest), (mqClient, byteRequest)).ToArray()
);
//Parallel.For(0, totalQ, i =>
//{
// var response = mqClient.SendAndReceiveAsync(byteRequest).WaitAndResults();
//});
Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds));
Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ));
}
Console.ReadLine();
#endregion
}
mqConfig.ResponseOptions.ClientReceiverOptions.Parameters["SingleResponseQueue"] = "false";
using (var mqClient = mqConfig.GetRawClient())
{
var totalQ = 2000;
#region Sync Mode
Core.Log.Warning("RAW Sync Mode Test, using Multiple Response Queue");
using (var w = Watch.Create($"Hello World Example in Sync Mode for {totalQ} times"))
{
for (var i = 0; i < totalQ; i++)
{
var response = mqClient.SendAndReceiveAsync(byteRequest).WaitAndResults();
}
Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds));
Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ));
}
Console.ReadLine();
#endregion
totalQ = 50000;
#region Parallel Mode
Core.Log.Warning("RAW Parallel Mode Test, using Multiple Response Queue");
using (var w = Watch.Create($"Hello World Example in Parallel Mode for {totalQ} times"))
{
Task.WaitAll(
Enumerable.Range(0, totalQ).Select((i, vTuple) => (Task)vTuple.mqClient.SendAndReceiveAsync(vTuple.byteRequest), (mqClient, byteRequest)).ToArray()
);
//Parallel.For(0, totalQ, i =>
//{
// var response = mqClient.SendAndReceiveAsync(byteRequest).WaitAndResults();
//});
Core.Log.InfoBasic("Total time: {0}", TimeSpan.FromMilliseconds(w.GlobalElapsedMilliseconds));
Core.Log.InfoBasic("Average time in ms: {0}. Press ENTER To Continue.", (w.GlobalElapsedMilliseconds / totalQ));
}
Console.ReadLine();
#endregion
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreAnimation;
using CoreGraphics;
using Finch.Mobile.iOS.Extensions;
using Mitten.Mobile.iOS.Extensions;
using Mitten.Mobile.Themes;
using UIKit;
namespace Mitten.Mobile.iOS.Views
{
/// <summary>
/// A custom segmented control that supports multiple rows.
/// </summary>
public class SegmentedControl : UIControl
{
private static class Constants
{
public const int DefaultButtonHeight = 36;
public const int ButtonImagePadding = 0;
public const int ButtonBorderSize = 2;
public const int ButtonBorderHalfSize = ButtonBorderSize / 2;
public const int ButtonBorderRadius = 6;
public const string ButtonBorderName = "Border";
public const int MaximumButtonsPerRow = 4;
}
private readonly List<NSLayoutConstraint> buttonHeightConstraints;
private readonly List<UIView> buttonRows;
private IEnumerable<Tuple<UIButton, SegmentedControlItem>> buttons;
private ILayoutHandler layoutHandler;
private ButtonTheme buttonTheme;
private CGColor buttonBorderColor;
private int buttonHeight;
/// <summary>
/// Initializes a new instance of the SegmentedControl class.
/// </summary>
/// <param name="maximumButtonsPerRow">The maximum number of buttons per row.</param>
public SegmentedControl(int maximumButtonsPerRow = Constants.MaximumButtonsPerRow)
{
if (maximumButtonsPerRow < 1)
{
throw new ArgumentOutOfRangeException(nameof(maximumButtonsPerRow), "The maximum number of buttons per row must be greater than 0.");
}
this.buttonHeightConstraints = new List<NSLayoutConstraint>();
this.buttonRows = new List<UIView>();
this.buttonHeight = Constants.DefaultButtonHeight;
this.layoutHandler = new DefaultLayoutHandler(maximumButtonsPerRow);
}
/// <summary>
/// Occurs after an item has been successfully pressed.
/// </summary>
public event Action<SegmentedControlItem> AfterItemPressed = delegate { };
/// <summary>
/// Gets or sets the theme used for the buttons in the current control.
/// </summary>
public ButtonTheme ButtonTheme
{
get { return this.buttonTheme; }
set
{
// TODO: consider decoupling the Theme from this control
Throw.IfArgumentNull(value, nameof(value));
this.buttonBorderColor = value.BorderColor.ToCGColor();
this.buttonTheme = value.WithTransparentBorder();
this.ApplyButtonTheme();
}
}
/// <summary>
/// Gets or sets the height of the buttons.
/// </summary>
public int ButtonHeight
{
get { return this.buttonHeight; }
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException(nameof(value), "Value must be greater than zero.");
}
if (this.buttonHeight != value)
{
this.buttonHeight = value;
foreach (NSLayoutConstraint constraint in this.buttonHeightConstraints)
{
constraint.Constant = this.buttonHeight;
}
}
}
}
/// <summary>
/// Gets or sets a layout handler for the segmented control.
/// </summary>
public ILayoutHandler LayoutHandler
{
get { return this.layoutHandler; }
set
{
Throw.IfArgumentNull(value, nameof(value));
this.layoutHandler = value;
this.LayoutButtons();
}
}
/// <summary>
/// Gets or sets the list of items for the segmented control.
/// </summary>
public IEnumerable<SegmentedControlItem> Items
{
get
{
if (this.buttons != null)
{
return this.buttons.Select(item => item.Item2);
}
return Enumerable.Empty<SegmentedControlItem>();
}
set
{
Throw.IfArgumentNull(value, nameof(value));
if (!value.Any())
{
throw new ArgumentException("At least one item must be specified.", nameof(value));
}
this.buttons = this.CreateItemButtons(value);
this.LayoutButtons();
if (this.buttonTheme != null)
{
this.ApplyButtonTheme();
}
}
}
/// <summary>
/// Gets or sets whether or not an item should be selected when pressed.
/// </summary>
public bool SelectItemWhenPressed { get; set; }
/// <summary>
/// Lays out the subviews.
/// </summary>
public override void LayoutSubviews()
{
base.LayoutSubviews();
if (this.buttonBorderColor != null)
{
this.UpdateButtonBorders();
}
this.CenterButtonImages();
}
/// <summary>
/// Selects the item associated with the specified tag.
/// </summary>
/// <param name="tag">A tag.</param>
public void SelectItemWithTag(object tag)
{
Throw.IfArgumentNull(tag, nameof(tag));
IEnumerable<SegmentedControlItem> items = this.Items.Where(item => object.Equals(item.Tag, tag));
if (!items.Any())
{
throw new ArgumentException("Item not found for the provided tag.");
}
if (items.Count() > 1)
{
throw new ArgumentException("More than one item was found with the provided tag.");
}
this.SelectItem(items.Single());
}
private void ApplyButtonTheme()
{
if (this.buttons != null)
{
foreach (Tuple<UIButton, SegmentedControlItem> item in this.buttons)
{
item.Item1.ApplyTheme(
this.buttonTheme,
item.Item2.Image,
default(UIEdgeInsets),
true,
ViewFontSizes.SmallFontSize);
item.Item1.SetTitleColor(this.buttonTheme.BackgroundColor.ToUIColor(), UIControlState.Selected);
}
this.UpdateButtonBorders();
}
}
private void LayoutButtons()
{
if (this.buttons != null)
{
int numberOfRows = this.layoutHandler.CalculateNumberOfRows(this.buttons.Count());
if (numberOfRows < 1)
{
throw new InvalidOperationException("The layout handler calculated the number of rows as less than 1.");
}
foreach (UIView row in this.buttonRows)
{
row.RemoveFromSuperview();
}
this.buttonRows.Clear();
this.buttonHeightConstraints.Clear();
for (int i = 0; i < numberOfRows; i++)
{
IEnumerable<SegmentedControlItem> itemsForRow = this.layoutHandler.SelectItemsForRow(this.buttons.Select(item => item.Item2), i);
IEnumerable<UIButton> buttonsForRow = this.buttons.Where(item => itemsForRow.Contains(item.Item2)).Select(item => item.Item1);
this.AddRow(buttonsForRow);
}
UIView topRow = this.buttonRows.First();
topRow.Anchor(AnchorEdges.Horizontal | AnchorEdges.Top);
for (int i = 1; i < this.buttonRows.Count; i++)
{
UIView currentRow = this.buttonRows[i];
currentRow.Anchor(AnchorEdges.Horizontal);
currentRow.AnchorBelow(topRow);
topRow = currentRow;
}
this.buttonRows.Last().Anchor(AnchorEdges.Bottom);
}
}
private void AddRow(IEnumerable<UIButton> items)
{
UIView row = new UIView();
row.TranslatesAutoresizingMaskIntoConstraints = false;
this.AddSubview(row);
row.AddSubviews(items.ToArray());
List<object> namesAndViews = new List<object>();
StringBuilder sb = new StringBuilder();
sb.Append("H:|");
int total = items.Count();
int count = 0;
foreach (UIView item in items)
{
string name = "item" + count++;
if (count < total)
{
string nextView = "item" + count;
sb.Append("[" + name + "(==" + nextView + ")]");
}
else
{
sb.Append("[" + name + "]");
}
namesAndViews.Add(name);
namesAndViews.Add(item);
item.Anchor(AnchorEdges.Top | AnchorEdges.Bottom);
this.buttonHeightConstraints.Add(item.AnchorHeight(this.ButtonHeight));
}
sb.Append("|");
row.AddConstraints(NSLayoutConstraint.FromVisualFormat(sb.ToString(), 0, namesAndViews.ToArray()));
this.buttonRows.Add(row);
}
private IEnumerable<Tuple<UIButton, SegmentedControlItem>> CreateItemButtons(IEnumerable<SegmentedControlItem> items)
{
List<Tuple<UIButton, SegmentedControlItem>> buttonViews = new List<Tuple<UIButton, SegmentedControlItem>>();
foreach (SegmentedControlItem item in items)
{
UIButton button = new UIButton(UIButtonType.Custom);
button.ImageView.ContentMode = UIViewContentMode.ScaleAspectFit;
button.TranslatesAutoresizingMaskIntoConstraints = false;
button.TouchUpInside += (sender, e) => this.HandleItemButtonPressed(item);
button.SetTitle(item.Title, UIControlState.Normal);
button.SetTitle(item.Title, UIControlState.Selected);
buttonViews.Add(new Tuple<UIButton, SegmentedControlItem>(button, item));
}
return buttonViews;
}
private void HandleItemButtonPressed(SegmentedControlItem item)
{
if (item.ItemPressed())
{
if (this.SelectItemWhenPressed)
{
this.SelectItem(item);
}
this.AfterItemPressed(item);
}
}
private void SelectItem(SegmentedControlItem item)
{
foreach (Tuple<UIButton, SegmentedControlItem> tuple in this.buttons)
{
if (tuple.Item2 == item)
{
tuple.Item1.Selected = true;
tuple.Item1.BackgroundColor = this.ButtonTheme.FontColor.ToUIColor();
}
else
{
tuple.Item1.Selected = false;
tuple.Item1.BackgroundColor = this.ButtonTheme.BackgroundColor.ToUIColor();
}
}
}
private void UpdateButtonBorders()
{
for (int i = 0; i < this.buttonRows.Count; i++)
{
bool isFirstRow = i == 0;
bool isLastRow = i == this.buttonRows.Count - 1;
IEnumerable<UIButton> buttonsForRow = this.buttonRows[i].Subviews.Cast<UIButton>();
int buttonsInRow = buttonsForRow.Count();
for (int j = 0; j < buttonsInRow; j++)
{
UIButton button = buttonsForRow.ElementAt(j);
button.LayoutIfNeeded();
UIRectCorner corners = 0;
bool isFirstColumn = j == 0;
bool isLastColumn = j == buttonsInRow - 1;
if (isFirstRow)
{
if (isFirstColumn)
{
corners |= UIRectCorner.TopLeft;
}
if (isLastColumn)
{
corners |= UIRectCorner.TopRight;
}
}
if (isLastRow)
{
if (isFirstColumn)
{
corners |= UIRectCorner.BottomLeft;
}
if (isLastColumn)
{
corners |= UIRectCorner.BottomRight;
}
}
this.UpdateButtonBorder(
button,
corners,
isFirstRow,
isLastRow,
isFirstColumn,
isLastColumn);
}
}
}
private void UpdateButtonBorder(
UIButton button,
UIRectCorner corners,
bool isInFirstRow,
bool isInLastRow,
bool isInFirstColumn,
bool isInLastColumn)
{
// we need to handle the situation where borders are next to each other, the problem is
// this creates an appearance where the border is twice as thick so we will use masking
// to remove borders from some buttons
CGSize radius = new CGSize(Constants.ButtonBorderRadius, Constants.ButtonBorderRadius);
CGRect borderBounds = button.Bounds;
if (!isInLastColumn)
{
// extend the border to the right so it overlaps with the border of the next button
borderBounds =
new CGRect(
button.Bounds.X,
button.Bounds.Y,
button.Bounds.Width + Constants.ButtonBorderHalfSize,
button.Bounds.Height);
}
if (!isInLastRow)
{
// extend the border down so it overlaps with the border for the next row
borderBounds = borderBounds.WithHeight(borderBounds.Height + Constants.ButtonBorderHalfSize);
}
UIBezierPath path = UIBezierPath.FromRoundedRect(borderBounds, corners, radius);
CAShapeLayer maskLayer = new CAShapeLayer();
maskLayer.Frame = borderBounds;
maskLayer.Path = path.CGPath;
button.Layer.Mask = maskLayer;
CAShapeLayer borderLayer = new CAShapeLayer();
borderLayer.FillColor = null;
borderLayer.Frame = borderBounds;
borderLayer.Name = Constants.ButtonBorderName;
borderLayer.Path = path.CGPath;
borderLayer.StrokeColor = this.buttonBorderColor;
borderLayer.LineWidth = Constants.ButtonBorderSize;
if (button.Layer.Sublayers != null)
{
CAShapeLayer oldLayer = button.Layer.Sublayers.SingleOrDefault(layer => layer.Name == Constants.ButtonBorderName) as CAShapeLayer;
if (oldLayer != null)
{
oldLayer.RemoveFromSuperLayer();
}
}
button.Layer.AddSublayer(borderLayer);
}
private void CenterButtonImages()
{
foreach (Tuple<UIButton, SegmentedControlItem> item in this.buttons)
{
if (item.Item2.Image != null)
{
CGSize imageSize = item.Item1.ImageView.Frame.Size;
CGSize titleSize = item.Item1.TitleLabel.Frame.Size;
nfloat totalHeight = imageSize.Height + titleSize.Height + Constants.ButtonImagePadding;
item.Item1.ImageEdgeInsets =
new UIEdgeInsets(
-(totalHeight - imageSize.Height),
0.0f,
0.0f,
-titleSize.Width);
item.Item1.TitleEdgeInsets =
new UIEdgeInsets(
0.0f,
-imageSize.Width,
-(totalHeight - titleSize.Height),
0.0f);
}
}
}
/// <summary>
/// Defines a handler responsible for defining the order and layout of buttons in a segmented control.
/// </summary>
public interface ILayoutHandler
{
/// <summary>
/// Calculates the number of rows needed to display the specified number of buttons.
/// </summary>
/// <param name="numberOfButtons">The number of buttons to display in the segmented control.</param>
/// <returns>The number of rows.</returns>
int CalculateNumberOfRows(int numberOfButtons);
/// <summary>
/// Selects the items for the row at the specified index.
/// </summary>
/// <param name="items">A list of all the items for the current segmented control.</param>
/// <param name="rowIndex">The row index.</param>
/// <returns>The items for row.</returns>
IEnumerable<SegmentedControlItem> SelectItemsForRow(IEnumerable<SegmentedControlItem> items, int rowIndex);
}
/// <summary>
/// The default layout handler for a segmented control.
/// </summary>
public class DefaultLayoutHandler : ILayoutHandler
{
/// <summary>
/// Initializes a new instance of the DefaultLayoutHandler class.
/// </summary>
/// <param name="maxNumberOfButtonsPerRow">The maximum number of buttons per row.</param>
public DefaultLayoutHandler(int maxNumberOfButtonsPerRow)
{
if (maxNumberOfButtonsPerRow < 1)
{
throw new ArgumentOutOfRangeException(nameof(maxNumberOfButtonsPerRow), "The maximum number of buttons per row must be greater than zero.");
}
this.MaxNumberOfButtonsPerRow = maxNumberOfButtonsPerRow;
}
/// <summary>
/// Gets the maximum number of buttons per row.
/// </summary>
public int MaxNumberOfButtonsPerRow { get; }
/// <summary>
/// Calculates the number of rows needed to display the specified number of buttons.
/// </summary>
/// <param name="numberOfButtons">The number of buttons to display in the segmented control.</param>
/// <returns>The number of rows.</returns>
public int CalculateNumberOfRows(int numberOfButtons)
{
if (numberOfButtons <= this.MaxNumberOfButtonsPerRow)
{
return 1;
}
return (numberOfButtons + this.MaxNumberOfButtonsPerRow - 1) / this.MaxNumberOfButtonsPerRow;
}
/// <summary>
/// Selects the items for the row at the specified index.
/// </summary>
/// <param name="items">A list of all the items for the current segmented control.</param>
/// <param name="rowIndex">The row index.</param>
/// <returns>The items for row.</returns>
public IEnumerable<SegmentedControlItem> SelectItemsForRow(IEnumerable<SegmentedControlItem> items, int rowIndex)
{
int numberOfButtons = items.Count();
if (numberOfButtons <= this.MaxNumberOfButtonsPerRow)
{
return items;
}
int startIndex = rowIndex * this.MaxNumberOfButtonsPerRow;
int count = Math.Min(this.MaxNumberOfButtonsPerRow, numberOfButtons - startIndex + 1);
return items.Skip(startIndex).Take(count);
}
}
}
}
| |
#region License
/*
* HttpListener.cs
*
* This code is derived from HttpListener.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2016 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <liryna.stark@gmail.com>
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading;
// TODO: Logging.
namespace WebSocketSharp.Net
{
/// <summary>
/// Provides a simple, programmatically controlled HTTP listener.
/// </summary>
public sealed class HttpListener : IDisposable
{
#region Private Fields
private AuthenticationSchemes _authSchemes;
private Func<HttpListenerRequest, AuthenticationSchemes> _authSchemeSelector;
private string _certFolderPath;
private Dictionary<HttpConnection, HttpConnection> _connections;
private object _connectionsSync;
private List<HttpListenerContext> _ctxQueue;
private object _ctxQueueSync;
private Dictionary<HttpListenerContext, HttpListenerContext> _ctxRegistry;
private object _ctxRegistrySync;
private static readonly string _defaultRealm;
private bool _disposed;
private bool _ignoreWriteExceptions;
private volatile bool _listening;
private Logger _logger;
private HttpListenerPrefixCollection _prefixes;
private string _realm;
private bool _reuseAddress;
private ServerSslConfiguration _sslConfig;
private Func<IIdentity, NetworkCredential> _userCredFinder;
private List<HttpListenerAsyncResult> _waitQueue;
private object _waitQueueSync;
#endregion
#region Static Constructor
static HttpListener ()
{
_defaultRealm = "SECRET AREA";
}
#endregion
#region Public Constructors
/// <summary>
/// Initializes a new instance of the <see cref="HttpListener"/> class.
/// </summary>
public HttpListener ()
{
_authSchemes = AuthenticationSchemes.Anonymous;
_connections = new Dictionary<HttpConnection, HttpConnection> ();
_connectionsSync = ((ICollection) _connections).SyncRoot;
_ctxQueue = new List<HttpListenerContext> ();
_ctxQueueSync = ((ICollection) _ctxQueue).SyncRoot;
_ctxRegistry = new Dictionary<HttpListenerContext, HttpListenerContext> ();
_ctxRegistrySync = ((ICollection) _ctxRegistry).SyncRoot;
_logger = new Logger ();
_prefixes = new HttpListenerPrefixCollection (this);
_waitQueue = new List<HttpListenerAsyncResult> ();
_waitQueueSync = ((ICollection) _waitQueue).SyncRoot;
}
#endregion
#region Internal Properties
internal bool IsDisposed {
get {
return _disposed;
}
}
internal bool ReuseAddress {
get {
return _reuseAddress;
}
set {
_reuseAddress = value;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the scheme used to authenticate the clients.
/// </summary>
/// <value>
/// One of the <see cref="WebSocketSharp.Net.AuthenticationSchemes"/> enum values,
/// represents the scheme used to authenticate the clients. The default value is
/// <see cref="WebSocketSharp.Net.AuthenticationSchemes.Anonymous"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public AuthenticationSchemes AuthenticationSchemes {
get {
CheckDisposed ();
return _authSchemes;
}
set {
CheckDisposed ();
_authSchemes = value;
}
}
/// <summary>
/// Gets or sets the delegate called to select the scheme used to authenticate the clients.
/// </summary>
/// <remarks>
/// If you set this property, the listener uses the authentication scheme selected by
/// the delegate for each request. Or if you don't set, the listener uses the value of
/// the <see cref="HttpListener.AuthenticationSchemes"/> property as the authentication
/// scheme for all requests.
/// </remarks>
/// <value>
/// A <c>Func<<see cref="HttpListenerRequest"/>, <see cref="AuthenticationSchemes"/>></c>
/// delegate that references the method used to select an authentication scheme. The default
/// value is <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public Func<HttpListenerRequest, AuthenticationSchemes> AuthenticationSchemeSelector {
get {
CheckDisposed ();
return _authSchemeSelector;
}
set {
CheckDisposed ();
_authSchemeSelector = value;
}
}
/// <summary>
/// Gets or sets the path to the folder in which stores the certificate files used to
/// authenticate the server on the secure connection.
/// </summary>
/// <remarks>
/// <para>
/// This property represents the path to the folder in which stores the certificate files
/// associated with each port number of added URI prefixes. A set of the certificate files
/// is a pair of the <c>'port number'.cer</c> (DER) and <c>'port number'.key</c>
/// (DER, RSA Private Key).
/// </para>
/// <para>
/// If this property is <see langword="null"/> or empty, the result of
/// <c>System.Environment.GetFolderPath
/// (<see cref="Environment.SpecialFolder.ApplicationData"/>)</c> is used as the default path.
/// </para>
/// </remarks>
/// <value>
/// A <see cref="string"/> that represents the path to the folder in which stores
/// the certificate files. The default value is <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public string CertificateFolderPath {
get {
CheckDisposed ();
return _certFolderPath;
}
set {
CheckDisposed ();
_certFolderPath = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether the listener returns exceptions that occur when
/// sending the response to the client.
/// </summary>
/// <value>
/// <c>true</c> if the listener shouldn't return those exceptions; otherwise, <c>false</c>.
/// The default value is <c>false</c>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public bool IgnoreWriteExceptions {
get {
CheckDisposed ();
return _ignoreWriteExceptions;
}
set {
CheckDisposed ();
_ignoreWriteExceptions = value;
}
}
/// <summary>
/// Gets a value indicating whether the listener has been started.
/// </summary>
/// <value>
/// <c>true</c> if the listener has been started; otherwise, <c>false</c>.
/// </value>
public bool IsListening {
get {
return _listening;
}
}
/// <summary>
/// Gets a value indicating whether the listener can be used with the current operating system.
/// </summary>
/// <value>
/// <c>true</c>.
/// </value>
public static bool IsSupported {
get {
return true;
}
}
/// <summary>
/// Gets the logging functions.
/// </summary>
/// <remarks>
/// The default logging level is <see cref="LogLevel.Error"/>. If you would like to change it,
/// you should set the <c>Log.Level</c> property to any of the <see cref="LogLevel"/> enum
/// values.
/// </remarks>
/// <value>
/// A <see cref="Logger"/> that provides the logging functions.
/// </value>
public Logger Log {
get {
return _logger;
}
}
/// <summary>
/// Gets the URI prefixes handled by the listener.
/// </summary>
/// <value>
/// A <see cref="HttpListenerPrefixCollection"/> that contains the URI prefixes.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public HttpListenerPrefixCollection Prefixes {
get {
CheckDisposed ();
return _prefixes;
}
}
/// <summary>
/// Gets or sets the name of the realm associated with the listener.
/// </summary>
/// <remarks>
/// If this property is <see langword="null"/> or empty, <c>"SECRET AREA"</c> will be used as
/// the name of the realm.
/// </remarks>
/// <value>
/// A <see cref="string"/> that represents the name of the realm. The default value is
/// <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public string Realm {
get {
CheckDisposed ();
return _realm;
}
set {
CheckDisposed ();
_realm = value;
}
}
/// <summary>
/// Gets or sets the SSL configuration used to authenticate the server and
/// optionally the client for secure connection.
/// </summary>
/// <value>
/// A <see cref="ServerSslConfiguration"/> that represents the configuration used to
/// authenticate the server and optionally the client for secure connection.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public ServerSslConfiguration SslConfiguration {
get {
CheckDisposed ();
return _sslConfig ?? (_sslConfig = new ServerSslConfiguration (null));
}
set {
CheckDisposed ();
_sslConfig = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether, when NTLM authentication is used,
/// the authentication information of first request is used to authenticate
/// additional requests on the same connection.
/// </summary>
/// <remarks>
/// This property isn't currently supported and always throws
/// a <see cref="NotSupportedException"/>.
/// </remarks>
/// <value>
/// <c>true</c> if the authentication information of first request is used;
/// otherwise, <c>false</c>.
/// </value>
/// <exception cref="NotSupportedException">
/// Any use of this property.
/// </exception>
public bool UnsafeConnectionNtlmAuthentication {
get {
throw new NotSupportedException ();
}
set {
throw new NotSupportedException ();
}
}
/// <summary>
/// Gets or sets the delegate called to find the credentials for an identity used to
/// authenticate a client.
/// </summary>
/// <value>
/// A <c>Func<<see cref="IIdentity"/>, <see cref="NetworkCredential"/>></c> delegate
/// that references the method used to find the credentials. The default value is
/// <see langword="null"/>.
/// </value>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public Func<IIdentity, NetworkCredential> UserCredentialsFinder {
get {
CheckDisposed ();
return _userCredFinder;
}
set {
CheckDisposed ();
_userCredFinder = value;
}
}
#endregion
#region Private Methods
private void cleanupConnections ()
{
HttpConnection[] conns = null;
lock (_connectionsSync) {
if (_connections.Count == 0)
return;
// Need to copy this since closing will call the RemoveConnection method.
var keys = _connections.Keys;
conns = new HttpConnection[keys.Count];
keys.CopyTo (conns, 0);
_connections.Clear ();
}
for (var i = conns.Length - 1; i >= 0; i--)
conns[i].Close (true);
}
private void cleanupContextQueue (bool sendServiceUnavailable)
{
HttpListenerContext[] ctxs = null;
lock (_ctxQueueSync) {
if (_ctxQueue.Count == 0)
return;
ctxs = _ctxQueue.ToArray ();
_ctxQueue.Clear ();
}
if (!sendServiceUnavailable)
return;
foreach (var ctx in ctxs) {
var res = ctx.Response;
res.StatusCode = (int) HttpStatusCode.ServiceUnavailable;
res.Close ();
}
}
private void cleanupContextRegistry ()
{
HttpListenerContext[] ctxs = null;
lock (_ctxRegistrySync) {
if (_ctxRegistry.Count == 0)
return;
// Need to copy this since closing will call the UnregisterContext method.
var keys = _ctxRegistry.Keys;
ctxs = new HttpListenerContext[keys.Count];
keys.CopyTo (ctxs, 0);
_ctxRegistry.Clear ();
}
for (var i = ctxs.Length - 1; i >= 0; i--)
ctxs[i].Connection.Close (true);
}
private void cleanupWaitQueue (Exception exception)
{
HttpListenerAsyncResult[] aress = null;
lock (_waitQueueSync) {
if (_waitQueue.Count == 0)
return;
aress = _waitQueue.ToArray ();
_waitQueue.Clear ();
}
foreach (var ares in aress)
ares.Complete (exception);
}
private void close (bool force)
{
if (_listening) {
_listening = false;
EndPointManager.RemoveListener (this);
}
lock (_ctxRegistrySync)
cleanupContextQueue (!force);
cleanupContextRegistry ();
cleanupConnections ();
cleanupWaitQueue (new ObjectDisposedException (GetType ().ToString ()));
_disposed = true;
}
private HttpListenerAsyncResult getAsyncResultFromQueue ()
{
if (_waitQueue.Count == 0)
return null;
var ares = _waitQueue[0];
_waitQueue.RemoveAt (0);
return ares;
}
private HttpListenerContext getContextFromQueue ()
{
if (_ctxQueue.Count == 0)
return null;
var ctx = _ctxQueue[0];
_ctxQueue.RemoveAt (0);
return ctx;
}
#endregion
#region Internal Methods
internal bool AddConnection (HttpConnection connection)
{
if (!_listening)
return false;
lock (_connectionsSync) {
if (!_listening)
return false;
_connections[connection] = connection;
return true;
}
}
internal HttpListenerAsyncResult BeginGetContext (HttpListenerAsyncResult asyncResult)
{
lock (_ctxRegistrySync) {
if (!_listening)
throw new HttpListenerException (995);
var ctx = getContextFromQueue ();
if (ctx == null)
_waitQueue.Add (asyncResult);
else
asyncResult.Complete (ctx, true);
return asyncResult;
}
}
internal void CheckDisposed ()
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
}
internal string GetRealm ()
{
var realm = _realm;
return realm != null && realm.Length > 0 ? realm : _defaultRealm;
}
internal Func<IIdentity, NetworkCredential> GetUserCredentialsFinder ()
{
return _userCredFinder;
}
internal bool RegisterContext (HttpListenerContext context)
{
if (!_listening)
return false;
if (!context.Authenticate ())
return false;
lock (_ctxRegistrySync) {
if (!_listening)
return false;
_ctxRegistry[context] = context;
var ares = getAsyncResultFromQueue ();
if (ares == null)
_ctxQueue.Add (context);
else
ares.Complete (context);
return true;
}
}
internal void RemoveConnection (HttpConnection connection)
{
lock (_connectionsSync)
_connections.Remove (connection);
}
internal AuthenticationSchemes SelectAuthenticationScheme (HttpListenerRequest request)
{
var selector = _authSchemeSelector;
if (selector == null)
return _authSchemes;
try {
return selector (request);
}
catch {
return AuthenticationSchemes.None;
}
}
internal void UnregisterContext (HttpListenerContext context)
{
lock (_ctxRegistrySync)
_ctxRegistry.Remove (context);
}
#endregion
#region Public Methods
/// <summary>
/// Shuts down the listener immediately.
/// </summary>
public void Abort ()
{
if (_disposed)
return;
close (true);
}
/// <summary>
/// Begins getting an incoming request asynchronously.
/// </summary>
/// <remarks>
/// This asynchronous operation must be completed by calling the <c>EndGetContext</c> method.
/// Typically, the method is invoked by the <paramref name="callback"/> delegate.
/// </remarks>
/// <returns>
/// An <see cref="IAsyncResult"/> that represents the status of the asynchronous operation.
/// </returns>
/// <param name="callback">
/// An <see cref="AsyncCallback"/> delegate that references the method to invoke when
/// the asynchronous operation completes.
/// </param>
/// <param name="state">
/// An <see cref="object"/> that represents a user defined object to pass to
/// the <paramref name="callback"/> delegate.
/// </param>
/// <exception cref="InvalidOperationException">
/// <para>
/// This listener has no URI prefix on which listens.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// This listener hasn't been started, or is currently stopped.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public IAsyncResult BeginGetContext (AsyncCallback callback, Object state)
{
CheckDisposed ();
if (_prefixes.Count == 0)
throw new InvalidOperationException ("The listener has no URI prefix on which listens.");
if (!_listening)
throw new InvalidOperationException ("The listener hasn't been started.");
return BeginGetContext (new HttpListenerAsyncResult (callback, state));
}
/// <summary>
/// Shuts down the listener.
/// </summary>
public void Close ()
{
if (_disposed)
return;
close (false);
}
/// <summary>
/// Ends an asynchronous operation to get an incoming request.
/// </summary>
/// <remarks>
/// This method completes an asynchronous operation started by calling
/// the <c>BeginGetContext</c> method.
/// </remarks>
/// <returns>
/// A <see cref="HttpListenerContext"/> that represents a request.
/// </returns>
/// <param name="asyncResult">
/// An <see cref="IAsyncResult"/> obtained by calling the <c>BeginGetContext</c> method.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="asyncResult"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="asyncResult"/> wasn't obtained by calling the <c>BeginGetContext</c> method.
/// </exception>
/// <exception cref="InvalidOperationException">
/// This method was already called for the specified <paramref name="asyncResult"/>.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public HttpListenerContext EndGetContext (IAsyncResult asyncResult)
{
CheckDisposed ();
if (asyncResult == null)
throw new ArgumentNullException ("asyncResult");
var ares = asyncResult as HttpListenerAsyncResult;
if (ares == null)
throw new ArgumentException ("A wrong IAsyncResult.", "asyncResult");
if (ares.EndCalled)
throw new InvalidOperationException ("This IAsyncResult cannot be reused.");
ares.EndCalled = true;
if (!ares.IsCompleted)
ares.AsyncWaitHandle.WaitOne ();
return ares.GetContext (); // This may throw an exception.
}
/// <summary>
/// Gets an incoming request.
/// </summary>
/// <remarks>
/// This method waits for an incoming request, and returns when a request is received.
/// </remarks>
/// <returns>
/// A <see cref="HttpListenerContext"/> that represents a request.
/// </returns>
/// <exception cref="InvalidOperationException">
/// <para>
/// This listener has no URI prefix on which listens.
/// </para>
/// <para>
/// -or-
/// </para>
/// <para>
/// This listener hasn't been started, or is currently stopped.
/// </para>
/// </exception>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public HttpListenerContext GetContext ()
{
CheckDisposed ();
if (_prefixes.Count == 0)
throw new InvalidOperationException ("The listener has no URI prefix on which listens.");
if (!_listening)
throw new InvalidOperationException ("The listener hasn't been started.");
var ares = BeginGetContext (new HttpListenerAsyncResult (null, null));
ares.InGet = true;
return EndGetContext (ares);
}
/// <summary>
/// Starts receiving incoming requests.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public void Start ()
{
CheckDisposed ();
if (_listening)
return;
EndPointManager.AddListener (this);
_listening = true;
}
/// <summary>
/// Stops receiving incoming requests.
/// </summary>
/// <exception cref="ObjectDisposedException">
/// This listener has been closed.
/// </exception>
public void Stop ()
{
CheckDisposed ();
if (!_listening)
return;
_listening = false;
EndPointManager.RemoveListener (this);
lock (_ctxRegistrySync)
cleanupContextQueue (true);
cleanupContextRegistry ();
cleanupConnections ();
cleanupWaitQueue (new HttpListenerException (995, "The listener is stopped."));
}
#endregion
#region Explicit Interface Implementations
/// <summary>
/// Releases all resources used by the listener.
/// </summary>
void IDisposable.Dispose ()
{
if (_disposed)
return;
close (true);
}
#endregion
}
}
| |
//
// System.Web.Services.Description.ProtocolReflector.cs
//
// Author:
// Tim Coleman (tim@timcoleman.com)
// Lluis Sanchez Gual (lluis@ximian.com)
//
// Copyright (C) Tim Coleman, 2002
//
//
// 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.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.Collections;
namespace System.Web.Services.Description {
public abstract class ProtocolReflector {
#region Fields
Binding binding;
string defaultNamespace;
MessageCollection headerMessages;
Message inputMessage;
LogicalMethodInfo[] methods;
Operation operation;
OperationBinding operationBinding;
Message outputMessage;
Port port;
PortType portType;
string protocolName;
XmlSchemaExporter schemaExporter;
Service service;
ServiceDescription serviceDescription;
Type serviceType;
string serviceUrl;
SoapSchemaExporter soapSchemaExporter;
MethodStubInfo methodStubInfo;
TypeStubInfo typeInfo;
ArrayList extensionReflectors;
ServiceDescriptionReflector serviceReflector;
XmlReflectionImporter reflectionImporter;
SoapReflectionImporter soapReflectionImporter;
CodeIdentifiers portNames;
#endregion // Fields
#region Constructors
protected ProtocolReflector ()
{
defaultNamespace = WebServiceAttribute.DefaultNamespace;
extensionReflectors = ExtensionManager.BuildExtensionReflectors ();
}
#endregion // Constructors
#region Properties
public Binding Binding {
get { return binding; }
}
public string DefaultNamespace {
get { return defaultNamespace; }
}
public MessageCollection HeaderMessages {
get { return headerMessages; } // TODO: set
}
public Message InputMessage {
get { return inputMessage; }
}
public LogicalMethodInfo Method {
get { return methodStubInfo.MethodInfo; }
}
public WebMethodAttribute MethodAttribute {
get { return methodStubInfo.MethodAttribute; }
}
public LogicalMethodInfo[] Methods {
get { return typeInfo.LogicalType.LogicalMethods; }
}
public Operation Operation {
get { return operation; }
}
public OperationBinding OperationBinding {
get { return operationBinding; }
}
public Message OutputMessage {
get { return outputMessage; }
}
public Port Port {
get { return port; }
}
public PortType PortType {
get { return portType; }
}
public abstract string ProtocolName {
get;
}
public XmlReflectionImporter ReflectionImporter
{
get
{
if (reflectionImporter == null) {
reflectionImporter = typeInfo.XmlImporter;
if (reflectionImporter == null)
reflectionImporter = new XmlReflectionImporter();
}
return reflectionImporter;
}
}
internal SoapReflectionImporter SoapReflectionImporter
{
get
{
if (soapReflectionImporter == null) {
soapReflectionImporter = typeInfo.SoapImporter;
if (soapReflectionImporter == null)
soapReflectionImporter = new SoapReflectionImporter();
}
return soapReflectionImporter;
}
}
public XmlSchemaExporter SchemaExporter {
get { return schemaExporter; }
}
internal SoapSchemaExporter SoapSchemaExporter {
get { return soapSchemaExporter; }
}
public XmlSchemas Schemas {
get { return serviceReflector.Schemas; }
}
public Service Service {
get { return service; }
}
public ServiceDescription ServiceDescription {
get { return serviceDescription; }
}
public ServiceDescriptionCollection ServiceDescriptions {
get { return serviceReflector.ServiceDescriptions; }
}
public Type ServiceType {
get { return serviceType; }
}
public string ServiceUrl {
get { return serviceUrl; }
}
internal MethodStubInfo MethodStubInfo {
get { return methodStubInfo; }
}
internal TypeStubInfo TypeInfo {
get { return typeInfo; }
}
#endregion // Properties
#region Methods
internal void Reflect (ServiceDescriptionReflector serviceReflector, Type type, string url, XmlSchemaExporter xxporter, SoapSchemaExporter sxporter)
{
portNames = new CodeIdentifiers ();
this.serviceReflector = serviceReflector;
serviceUrl = url;
serviceType = type;
schemaExporter = xxporter;
soapSchemaExporter = sxporter;
typeInfo = TypeStubManager.GetTypeStub (type, ProtocolName);
ServiceDescription desc = ServiceDescriptions [typeInfo.LogicalType.WebServiceNamespace];
if (desc == null)
{
desc = new ServiceDescription ();
desc.TargetNamespace = typeInfo.LogicalType.WebServiceNamespace;
desc.Name = typeInfo.LogicalType.WebServiceName;
ServiceDescriptions.Add (desc);
}
ImportService (desc, typeInfo, url);
}
void ImportService (ServiceDescription desc, TypeStubInfo typeInfo, string url)
{
service = desc.Services [typeInfo.LogicalType.WebServiceName];
if (service == null)
{
service = new Service ();
service.Name = typeInfo.LogicalType.WebServiceName;
service.Documentation = typeInfo.LogicalType.Description;
desc.Services.Add (service);
}
foreach (BindingInfo binfo in typeInfo.Bindings)
ImportBinding (desc, service, typeInfo, url, binfo);
}
void ImportBinding (ServiceDescription desc, Service service, TypeStubInfo typeInfo, string url, BindingInfo binfo)
{
port = new Port ();
port.Name = portNames.AddUnique (binfo.Name, port);
bool bindingFull = true;
if (binfo.Namespace != desc.TargetNamespace)
{
if (binfo.Location == null || binfo.Location == string.Empty)
{
ServiceDescription newDesc = new ServiceDescription();
newDesc.TargetNamespace = binfo.Namespace;
newDesc.Name = binfo.Name;
bindingFull = ImportBindingContent (newDesc, typeInfo, url, binfo);
if (bindingFull) {
int id = ServiceDescriptions.Add (newDesc);
AddImport (desc, binfo.Namespace, GetWsdlUrl (url,id));
}
}
else {
AddImport (desc, binfo.Namespace, binfo.Location);
bindingFull = true;
}
}
else
bindingFull = ImportBindingContent (desc, typeInfo, url, binfo);
if (bindingFull)
{
port.Binding = new XmlQualifiedName (binding.Name, binfo.Namespace);
service.Ports.Add (port);
}
}
bool ImportBindingContent (ServiceDescription desc, TypeStubInfo typeInfo, string url, BindingInfo binfo)
{
serviceDescription = desc;
// Look for an unused name
int n=0;
string name = binfo.Name;
bool found;
do
{
found = false;
foreach (Binding bi in desc.Bindings)
if (bi.Name == name) { found = true; n++; name = binfo.Name+n; break; }
}
while (found);
// Create the binding
binding = new Binding ();
binding.Name = name;
binding.Type = new XmlQualifiedName (binding.Name, binfo.Namespace);
portType = new PortType ();
portType.Name = binding.Name;
BeginClass ();
foreach (MethodStubInfo method in typeInfo.Methods)
{
methodStubInfo = method;
string metBinding = ReflectMethodBinding ();
if (typeInfo.GetBinding (metBinding) != binfo) continue;
operation = new Operation ();
operation.Name = method.OperationName;
operation.Documentation = method.MethodAttribute.Description;
inputMessage = new Message ();
inputMessage.Name = method.Name + ProtocolName + "In";
ServiceDescription.Messages.Add (inputMessage);
outputMessage = new Message ();
outputMessage.Name = method.Name + ProtocolName + "Out";
ServiceDescription.Messages.Add (outputMessage);
OperationInput inOp = new OperationInput ();
if (method.Name != method.OperationName) inOp.Name = method.Name;
Operation.Messages.Add (inOp);
inOp.Message = new XmlQualifiedName (inputMessage.Name, ServiceDescription.TargetNamespace);
OperationOutput outOp = new OperationOutput ();
if (method.Name != method.OperationName) outOp.Name = method.Name;
Operation.Messages.Add (outOp);
outOp.Message = new XmlQualifiedName (outputMessage.Name, ServiceDescription.TargetNamespace);
portType.Operations.Add (operation);
ImportOperationBinding ();
ReflectMethod ();
foreach (SoapExtensionReflector reflector in extensionReflectors)
{
reflector.ReflectionContext = this;
reflector.ReflectMethod ();
}
}
EndClass ();
if (portType.Operations.Count > 0)
{
desc.Bindings.Add (binding);
desc.PortTypes.Add (portType);
return true;
}
else
return false;
}
void ImportOperationBinding ()
{
operationBinding = new OperationBinding ();
operationBinding.Name = methodStubInfo.OperationName;
InputBinding inOp = new InputBinding ();
operationBinding.Input = inOp;
OutputBinding outOp = new OutputBinding ();
operationBinding.Output = outOp;
if (methodStubInfo.OperationName != methodStubInfo.Name)
inOp.Name = outOp.Name = methodStubInfo.Name;
binding.Operations.Add (operationBinding);
}
internal static void AddImport (ServiceDescription desc, string ns, string location)
{
Import im = new Import();
im.Namespace = ns;
im.Location = location;
desc.Imports.Add (im);
}
string GetWsdlUrl (string baseUrl, int id)
{
return baseUrl + "?wsdl=" + id;
}
protected virtual void BeginClass ()
{
}
protected virtual void EndClass ()
{
}
public ServiceDescription GetServiceDescription (string ns)
{
return ServiceDescriptions [ns];
}
protected abstract bool ReflectMethod ();
protected virtual string ReflectMethodBinding ()
{
return null;
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DNS.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System.Text;
using System.Collections;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Threading;
using System.Threading.Tasks;
using System.Globalization;
using System.Net.NetworkInformation;
/// <devdoc>
/// <para>Provides simple
/// domain name resolution functionality.</para>
/// </devdoc>
public static class Dns
{
//
// used by GetHostName() to preallocate a buffer for the call to gethostname.
//
private const int HostNameBufferLength = 256;
//also used as a lock object
private static DnsPermission s_DnsPermission = new DnsPermission(PermissionState.Unrestricted);
// Host names any longer than this automatically fail at the winsock level.
// If the host name is 255 chars, the last char must be a dot.
private const int MaxHostName = 255;
/*++
Routine Description:
Takes a native pointer (expressed as an int) to a hostent structure,
and converts the information in their to an IPHostEntry class. This
involves walking through an array of native pointers, and a temporary
ArrayList object is used in doing this.
Arguments:
nativePointer - Native pointer to hostent structure.
Return Value:
An IPHostEntry structure.
--*/
#if !FEATURE_PAL
private static IPHostEntry NativeToHostEntry(IntPtr nativePointer) {
#else
internal static IPHostEntry NativeToHostEntry(IntPtr nativePointer) {
#endif
//
// marshal pointer to struct
//
hostent Host = (hostent)Marshal.PtrToStructure(nativePointer, typeof(hostent));
IPHostEntry HostEntry = new IPHostEntry();
if (Host.h_name != IntPtr.Zero) {
HostEntry.HostName = Marshal.PtrToStringAnsi(Host.h_name);
GlobalLog.Print("HostEntry.HostName: " + HostEntry.HostName);
}
// decode h_addr_list to ArrayList of IP addresses.
// The h_addr_list field is really a pointer to an array of pointers
// to IP addresses. Loop through the array, and while the pointer
// isn't NULL read the IP address, convert it to an IPAddress class,
// and add it to the list.
ArrayList TempList = new ArrayList();
int IPAddressToAdd;
string AliasToAdd;
IntPtr currentArrayElement;
//
// get the first pointer in the array
//
currentArrayElement = Host.h_addr_list;
nativePointer = Marshal.ReadIntPtr(currentArrayElement);
while (nativePointer != IntPtr.Zero) {
//
// if it's not null it points to an IPAddress,
// read it...
//
IPAddressToAdd = Marshal.ReadInt32(nativePointer);
#if BIGENDIAN
// IP addresses from native code are always a byte array
// converted to int. We need to convert the address into
// a uniform integer value.
IPAddressToAdd = (int)( ((uint)IPAddressToAdd << 24) |
(((uint)IPAddressToAdd & 0x0000FF00) << 8) |
(((uint)IPAddressToAdd >> 8) & 0x0000FF00) |
((uint)IPAddressToAdd >> 24) );
#endif
GlobalLog.Print("currentArrayElement: " + currentArrayElement.ToString() + " nativePointer: " + nativePointer.ToString() + " IPAddressToAdd:" + IPAddressToAdd.ToString());
//
// ...and add it to the list
//
TempList.Add(new IPAddress(IPAddressToAdd));
//
// now get the next pointer in the array and start over
//
currentArrayElement = IntPtrHelper.Add(currentArrayElement, IntPtr.Size);
nativePointer = Marshal.ReadIntPtr(currentArrayElement);
}
HostEntry.AddressList = new IPAddress[TempList.Count];
TempList.CopyTo(HostEntry.AddressList, 0);
//
// Now do the same thing for the aliases.
//
TempList.Clear();
currentArrayElement = Host.h_aliases;
nativePointer = Marshal.ReadIntPtr(currentArrayElement);
while (nativePointer != IntPtr.Zero) {
GlobalLog.Print("currentArrayElement: " + ((long)currentArrayElement).ToString() + "nativePointer: " + ((long)nativePointer).ToString());
//
// if it's not null it points to an Alias,
// read it...
//
AliasToAdd = Marshal.PtrToStringAnsi(nativePointer);
//
// ...and add it to the list
//
TempList.Add(AliasToAdd);
//
// now get the next pointer in the array and start over
//
currentArrayElement = IntPtrHelper.Add(currentArrayElement, IntPtr.Size);
nativePointer = Marshal.ReadIntPtr(currentArrayElement);
}
HostEntry.Aliases = new string[TempList.Count];
TempList.CopyTo(HostEntry.Aliases, 0);
return HostEntry;
} // NativeToHostEntry
/*****************************************************************************
Function : gethostbyname
Abstract: Queries DNS for hostname address
Input Parameters: str (String to query)
Returns: Void
******************************************************************************/
/// <devdoc>
/// <para>Retrieves the <see cref='System.Net.IPHostEntry'/>
/// information
/// corresponding to the DNS name provided in the host
/// parameter.</para>
/// </devdoc>
[Obsolete("GetHostByName is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByName(string hostName) {
if (hostName == null) {
throw new ArgumentNullException("hostName");
}
//
// demand Unrestricted DnsPermission for this call
//
s_DnsPermission.Demand();
// See if it's an IP Address.
IPAddress address;
if (IPAddress.TryParse(hostName, out address))
{
return GetUnresolveAnswer(address);
}
return InternalGetHostByName(hostName, false);
}
//
internal static IPHostEntry InternalGetHostByName(string hostName) {
return InternalGetHostByName(hostName,true);
}
internal static IPHostEntry InternalGetHostByName(string hostName, bool includeIPv6) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "GetHostByName", hostName);
IPHostEntry ipHostEntry = null;
GlobalLog.Print("Dns.GetHostByName: " + hostName);
if (hostName.Length > MaxHostName // If 255 chars, the last one must be a dot.
|| hostName.Length == MaxHostName && hostName[MaxHostName-1] != '.') {
throw new ArgumentOutOfRangeException("hostName", SR.GetString(SR.net_toolong,
"hostName", MaxHostName.ToString(NumberFormatInfo.CurrentInfo)));
}
//
// IPv6 Changes: IPv6 requires the use of getaddrinfo() rather
// than the traditional IPv4 gethostbyaddr() / gethostbyname().
// getaddrinfo() is also protocol independant in that it will also
// resolve IPv4 names / addresses. As a result, it is the preferred
// resolution mechanism on platforms that support it (Windows 5.1+).
// If getaddrinfo() is unsupported, IPv6 resolution does not work.
//
// Consider : If IPv6 is disabled, we could detect IPv6 addresses
// and throw an unsupported platform exception.
//
// Note : Whilst getaddrinfo is available on WinXP+, we only
// use it if IPv6 is enabled (platform is part of that
// decision). This is done to minimize the number of
// possible tests that are needed.
//
if ( Socket.LegacySupportsIPv6 || includeIPv6) {
//
// IPv6 enabled: use getaddrinfo() to obtain DNS information.
//
ipHostEntry = Dns.GetAddrInfo(hostName);
}
else {
//
// IPv6 disabled: use gethostbyname() to obtain DNS information.
//
IntPtr nativePointer =
UnsafeNclNativeMethods.OSSOCK.gethostbyname(
hostName);
if (nativePointer == IntPtr.Zero) {
// This is for compatiblity with NT4/Win2k
// Need to do this first since if we wait the last error code might be overwritten.
SocketException socketException = new SocketException();
//This block supresses "unknown error" on NT4 when input is
//arbitrary IP address. It simulates same result as on Win2K.
// For Everett compat, we allow this to parse and return IPv6 even when it's disabled.
IPAddress address;
if (IPAddress.TryParse(hostName, out address))
{
ipHostEntry = GetUnresolveAnswer(address);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "GetHostByName", ipHostEntry);
return ipHostEntry;
}
throw socketException;
}
ipHostEntry = NativeToHostEntry(nativePointer);
}
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "GetHostByName", ipHostEntry);
return ipHostEntry;
} // GetHostByName
/*****************************************************************************
Function : gethostbyaddr
Abstract: Queries IP address string and tries to match with a host name
Input Parameters: str (String to query)
Returns: IPHostEntry
******************************************************************************/
/// <devdoc>
/// <para>Creates an <see cref='System.Net.IPHostEntry'/>
/// instance from an IP dotted address.</para>
/// </devdoc>
[Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByAddress(string address) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "GetHostByAddress", address);
//
// demand Unrestricted DnsPermission for this call
//
s_DnsPermission.Demand();
if (address == null) {
throw new ArgumentNullException("address");
}
GlobalLog.Print("Dns.GetHostByAddress: " + address);
IPHostEntry ipHostEntry = InternalGetHostByAddress(IPAddress.Parse(address), false);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "GetHostByAddress", ipHostEntry);
return ipHostEntry;
} // GetHostByAddress
/*****************************************************************************
Function : gethostbyaddr
Abstract: Queries IP address and tries to match with a host name
Input Parameters: address (address to query)
Returns: IPHostEntry
******************************************************************************/
/// <devdoc>
/// <para>Creates an <see cref='System.Net.IPHostEntry'/> instance from an <see cref='System.Net.IPAddress'/>
/// instance.</para>
/// </devdoc>
[Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByAddress(IPAddress address) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "GetHostByAddress", "");
//
// demand Unrestricted DnsPermission for this call
//
s_DnsPermission.Demand();
if (address == null) {
throw new ArgumentNullException("address");
}
IPHostEntry ipHostEntry = InternalGetHostByAddress(address, false);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "GetHostByAddress", ipHostEntry);
return ipHostEntry;
} // GetHostByAddress
// Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods).
// Legacy methods do not include IPv6, unless configed to by Socket.LegacySupportsIPv6 and Socket.OSSupportsIPv6.
internal static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6)
{
GlobalLog.Print("Dns.InternalGetHostByAddress: " + address.ToString());
//
// IPv6 Changes: We need to use the new getnameinfo / getaddrinfo functions
// for resolution of IPv6 addresses.
//
SocketError errorCode = SocketError.Success;
Exception exception = null;
if ( Socket.LegacySupportsIPv6 || includeIPv6) {
//
// Try to get the data for the host from it's address
//
// We need to call getnameinfo first, because getaddrinfo w/ the ipaddress string
// will only return that address and not the full list.
// Do a reverse lookup to get the host name.
string name = TryGetNameInfo(address, out errorCode);
if(errorCode == SocketError.Success) {
// Do the forward lookup to get the IPs for that host name
IPHostEntry hostEntry;
errorCode = TryGetAddrInfo(name, out hostEntry);
if (errorCode == SocketError.Success)
return hostEntry;
// Log failure
if (Logging.On) Logging.Exception(Logging.Sockets, "DNS",
"InternalGetHostByAddress", new SocketException(errorCode));
// One of two things happened:
// 1. There was a ptr record in dns, but not a corollary A/AAA record.
// 2. The IP was a local (non-loopback) IP that resolved to a connection specific dns suffix.
// - Workaround, Check "Use this connection's dns suffix in dns registration" on that network
// adapter's advanced dns settings.
// Just return the resolved host name and no IPs.
return hostEntry;
}
exception = new SocketException(errorCode);
}
//
// If IPv6 is not enabled (maybe config switch) but we've been
// given an IPv6 address then we need to bail out now.
//
else {
if ( address.AddressFamily == AddressFamily.InterNetworkV6 ) {
//
// Protocol not supported
//
throw new SocketException(SocketError.ProtocolNotSupported);
}
//
// Use gethostbyaddr() to try to resolve the IP address
//
// End IPv6 Changes
//
int addressAsInt = unchecked((int)address.m_Address);
#if BIGENDIAN
addressAsInt = (int)( ((uint)addressAsInt << 24) | (((uint)addressAsInt & 0x0000FF00) << 8) |
(((uint)addressAsInt >> 8) & 0x0000FF00) | ((uint)addressAsInt >> 24) );
#endif
IntPtr nativePointer =
UnsafeNclNativeMethods.OSSOCK.gethostbyaddr(
ref addressAsInt,
Marshal.SizeOf(typeof(int)),
ProtocolFamily.InterNetwork);
if (nativePointer != IntPtr.Zero) {
return NativeToHostEntry(nativePointer);
}
exception = new SocketException();
}
if (Logging.On) Logging.Exception(Logging.Sockets, "DNS", "InternalGetHostByAddress", exception);
throw exception;
} // InternalGetHostByAddress
/*****************************************************************************
Function : gethostname
Abstract: Queries the hostname from DNS
Input Parameters:
Returns: String
******************************************************************************/
/// <devdoc>
/// <para>Gets the host name of the local machine.</para>
/// </devdoc>
// UEUE: note that this method is not threadsafe!!
public static string GetHostName() {
//
// demand Unrestricted DnsPermission for this call
//
s_DnsPermission.Demand();
GlobalLog.Print("Dns.GetHostName");
//
// note that we could cache the result ourselves since you
// wouldn't expect the hostname of the machine to change during
// execution, but this might still happen and we would want to
// react to that change.
//
Socket.InitializeSockets();
StringBuilder sb = new StringBuilder(HostNameBufferLength);
SocketError errorCode =
UnsafeNclNativeMethods.OSSOCK.gethostname(
sb,
HostNameBufferLength);
//
// if the call failed throw a SocketException()
//
if (errorCode!=SocketError.Success) {
throw new SocketException();
}
return sb.ToString();
}
/*****************************************************************************
Function : resolve
Abstract: Converts IP/hostnames to IP numerical address using DNS
Additional methods provided for convenience
(These methods will resolve strings and hostnames. In case of
multiple IP addresses, the address returned is chosen arbitrarily.)
Input Parameters: host/IP
Returns: IPAddress
******************************************************************************/
/// <devdoc>
/// <para>Creates an <see cref='System.Net.IPAddress'/>
/// instance from a DNS hostname.</para>
/// </devdoc>
// UEUE
[Obsolete("Resolve is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry Resolve(string hostName) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "Resolve", hostName);
//
// demand Unrestricted DnsPermission for this call
//
s_DnsPermission.Demand();
if (hostName == null) {
throw new ArgumentNullException("hostName");
}
// See if it's an IP Address.
IPAddress address;
IPHostEntry ipHostEntry;
// Everett Compat (#497786).
// Everett.Resolve() returns the IPv6 address, even when IPv6 is off. Everett.GetHostByAddress() throws. So
// if IPv6 is off and they passed one in, call InternalGetHostByName which (also for compat) just returns it.
if (IPAddress.TryParse(hostName, out address) && (address.AddressFamily != AddressFamily.InterNetworkV6 || Socket.LegacySupportsIPv6))
{
try
{
ipHostEntry = InternalGetHostByAddress(address, false);
}
catch (SocketException ex)
{
if (Logging.On) Logging.PrintWarning(Logging.Sockets, "DNS", "DNS.Resolve", ex.Message);
ipHostEntry = GetUnresolveAnswer(address);
}
}
else
{
ipHostEntry = InternalGetHostByName(hostName, false);
}
if (Logging.On) Logging.Exit(Logging.Sockets, "DNS", "Resolve", ipHostEntry);
return ipHostEntry;
}
private static IPHostEntry GetUnresolveAnswer(IPAddress address)
{
IPHostEntry ipHostEntry = new IPHostEntry();
ipHostEntry.HostName = address.ToString();
ipHostEntry.Aliases = new string[0];
ipHostEntry.AddressList = new IPAddress[] { address };
return ipHostEntry;
}
// Returns true if the resolution was successful. IPAddresses are not resolved, but return immediately.
// Resolving String.Empty is not supported for security reasons, this would return localhost IPs.
//
// Exceptions are not thrown for performance reasons. The resulting message would never reach the user.
//
// On Win7 SP1+ this also attempts to determine if the host
// name was changed by DNS and should not be trusted as an SPN.
internal static bool TryInternalResolve(string hostName, out IPHostEntry result)
{
if (Logging.On) Logging.Enter(Logging.Sockets, "DNS", "TryInternalResolve", hostName);
if (string.IsNullOrEmpty(hostName) || hostName.Length > MaxHostName)
{
result = null;
return false;
}
IPAddress address;
if (IPAddress.TryParse(hostName, out address))
{
GlobalLog.Print("Dns::InternalResolveFast() returned address:" + address.ToString());
result = GetUnresolveAnswer(address); // Do not do reverse lookups on IPAddresses.
return true;
}
IPHostEntry canonicalResult;
if (SocketError.Success != TryGetAddrInfo(hostName, AddressInfoHints.AI_CANONNAME, out canonicalResult))
{
result = null;
return false;
}
result = canonicalResult;
if (!ComNetOS.IsWin7Sp1orLater)
{
// Win7 RTM or lower, no trusted host verification is supported. Assume Trusted.
return true;
}
// CBT. If the SPN came from an untrusted source, we should tell the server by setting this flag
// SPNs are trusted if:
// - They are manually configured by the user
// - DNSSEC was used (but there is no way for us to find out about this)
// - DNS didn't modify the host name (CNAMEs, Flat -> FQDNs, etc)
// Trusted if the resulting name the same as the input.
if (CompareHosts(hostName, canonicalResult.HostName))
{
return true; // Trusted
}
// AI_FQDN returns the FQDN that was used for resolution, rather than the name that the server returned.
// This helps us detect if CNAME aliases were traversed.
IPHostEntry fqdnResult;
if (SocketError.Success != TryGetAddrInfo(hostName, AddressInfoHints.AI_FQDN, out fqdnResult))
{
// This shouldn't have failed, the result should have been cached already. Assume trusted.
return true;
}
// Trusted if the resulting FQDN matches the resulting CANONNAME.
if (CompareHosts(canonicalResult.HostName, fqdnResult.HostName))
{
return true; // Trusted
}
// Not trusted because the DNS result was different from the input.
canonicalResult.isTrustedHost = false;
return true;
}
private static bool CompareHosts(string host1, string host2)
{
// Normalize and compare
string normalizedHost1, normalizedHost2;
if (TryNormalizeHost(host1, out normalizedHost1))
{
if (TryNormalizeHost(host2, out normalizedHost2))
{
return normalizedHost1.Equals(normalizedHost2, StringComparison.OrdinalIgnoreCase);
}
}
return host1.Equals(host2, StringComparison.OrdinalIgnoreCase);
}
private static bool TryNormalizeHost(string host, out string result)
{
Uri uri;
if (Uri.TryCreate(Uri.UriSchemeHttp + Uri.SchemeDelimiter + host, UriKind.Absolute, out uri))
{
result = uri.GetComponents(UriComponents.NormalizedHost, UriFormat.SafeUnescaped);
return true;
}
result = null;
return false;
}
private static WaitCallback resolveCallback = new WaitCallback(ResolveCallback);
private class ResolveAsyncResult : ContextAwareResult
{
// Forward lookup
internal ResolveAsyncResult(string hostName, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack) :
base(myObject, myState, myCallBack)
{
this.hostName = hostName;
this.includeIPv6 = includeIPv6;
}
// Reverse lookup
internal ResolveAsyncResult(IPAddress address, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack) :
base(myObject, myState, myCallBack)
{
this.includeIPv6 = includeIPv6;
this.address = address;
}
internal readonly string hostName;
internal bool includeIPv6;
internal IPAddress address;
}
private static void ResolveCallback(object context)
{
ResolveAsyncResult result = (ResolveAsyncResult)context;
IPHostEntry hostEntry;
try
{
if(result.address != null){
hostEntry = InternalGetHostByAddress(result.address, result.includeIPv6);
}
else{
hostEntry = InternalGetHostByName(result.hostName, result.includeIPv6);
}
}
catch (Exception exception)
{
if (exception is OutOfMemoryException || exception is ThreadAbortException || exception is StackOverflowException)
throw;
result.InvokeCallback(exception);
return;
}
result.InvokeCallback(hostEntry);
}
// Helpers for async GetHostByName, ResolveToAddresses, and Resolve - they're almost identical
// If hostName is an IPString and justReturnParsedIP==true then no reverse lookup will be attempted, but the orriginal address is returned.
private static IAsyncResult HostResolutionBeginHelper(string hostName, bool justReturnParsedIp, bool flowContext, bool includeIPv6, bool throwOnIPAny, AsyncCallback requestCallback, object state)
{
//
// demand Unrestricted DnsPermission for this call
//
s_DnsPermission.Demand();
if (hostName == null) {
throw new ArgumentNullException("hostName");
}
GlobalLog.Print("Dns.HostResolutionBeginHelper: " + hostName);
// See if it's an IP Address.
IPAddress address;
ResolveAsyncResult asyncResult;
if (IPAddress.TryParse(hostName, out address))
{
if (throwOnIPAny && (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)))
{
throw new ArgumentException(SR.GetString(SR.net_invalid_ip_addr), "hostNameOrAddress");
}
asyncResult = new ResolveAsyncResult(address, null, includeIPv6, state, requestCallback);
if (justReturnParsedIp)
{
IPHostEntry hostEntry = GetUnresolveAnswer(address);
asyncResult.StartPostingAsyncOp(false);
asyncResult.InvokeCallback(hostEntry);
asyncResult.FinishPostingAsyncOp();
return asyncResult;
}
}
else
{
asyncResult = new ResolveAsyncResult(hostName, null, includeIPv6, state, requestCallback);
}
// Set up the context, possibly flow.
if (flowContext)
{
asyncResult.StartPostingAsyncOp(false);
}
// Start the resolve.
ThreadPool.UnsafeQueueUserWorkItem(resolveCallback, asyncResult);
// Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above.
asyncResult.FinishPostingAsyncOp();
return asyncResult;
}
private static IAsyncResult HostResolutionBeginHelper(IPAddress address, bool flowContext, bool includeIPv6, AsyncCallback requestCallback, object state)
{
//
// demand Unrestricted DnsPermission for this call
//
s_DnsPermission.Demand();
if (address == null) {
throw new ArgumentNullException("address");
}
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.GetString(SR.net_invalid_ip_addr), "address");
}
GlobalLog.Print("Dns.HostResolutionBeginHelper: " + address);
// Set up the context, possibly flow.
ResolveAsyncResult asyncResult = new ResolveAsyncResult(address, null, includeIPv6, state, requestCallback);
if (flowContext)
{
asyncResult.StartPostingAsyncOp(false);
}
// Start the resolve.
ThreadPool.UnsafeQueueUserWorkItem(resolveCallback, asyncResult);
// Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above.
asyncResult.FinishPostingAsyncOp();
return asyncResult;
}
private static IPHostEntry HostResolutionEndHelper(IAsyncResult asyncResult)
{
//
// parameter validation
//
if (asyncResult == null) {
throw new ArgumentNullException("asyncResult");
}
ResolveAsyncResult castedResult = asyncResult as ResolveAsyncResult;
if (castedResult == null)
{
throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
}
if (castedResult.EndCalled)
{
throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndResolve"));
}
GlobalLog.Print("Dns.HostResolutionEndHelper");
castedResult.InternalWaitForCompletion();
castedResult.EndCalled = true;
Exception exception = castedResult.Result as Exception;
if (exception != null)
{
throw exception;
}
return (IPHostEntry) castedResult.Result;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[HostProtection(ExternalThreading=true)]
[Obsolete("BeginGetHostByName is obsoleted for this type, please use BeginGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback requestCallback, object stateObject) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "BeginGetHostByName", hostName);
IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, true, true, false, false, requestCallback, stateObject);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "BeginGetHostByName", asyncResult);
return asyncResult;
} // BeginGetHostByName
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[Obsolete("EndGetHostByName is obsoleted for this type, please use EndGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "EndGetHostByName", asyncResult);
IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "EndGetHostByName", ipHostEntry);
return ipHostEntry;
} // EndGetHostByName()
//***********************************************************************
//************* New Whidbey Apis *************************************
//***********************************************************************
public static IPHostEntry GetHostEntry(string hostNameOrAddress) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "GetHostEntry", hostNameOrAddress);
//
// demand Unrestricted DnsPermission for this call
//
s_DnsPermission.Demand();
if (hostNameOrAddress == null) {
throw new ArgumentNullException("hostNameOrAddress");
}
// See if it's an IP Address.
IPAddress address;
IPHostEntry ipHostEntry;
if (IPAddress.TryParse(hostNameOrAddress, out address))
{
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.GetString(SR.net_invalid_ip_addr), "hostNameOrAddress");
}
ipHostEntry = InternalGetHostByAddress(address, true);
}
else
{
ipHostEntry = InternalGetHostByName(hostNameOrAddress, true);
}
if (Logging.On) Logging.Exit(Logging.Sockets, "DNS", "GetHostEntry", ipHostEntry);
return ipHostEntry;
}
public static IPHostEntry GetHostEntry(IPAddress address) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "GetHostEntry", "");
//
// demand Unrestricted DnsPermission for this call
//
s_DnsPermission.Demand();
if (address == null) {
throw new ArgumentNullException("address");
}
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.GetString(SR.net_invalid_ip_addr), "address");
}
IPHostEntry ipHostEntry = InternalGetHostByAddress(address, true);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "GetHostEntry", ipHostEntry);
return ipHostEntry;
} // GetHostByAddress
public static IPAddress[] GetHostAddresses(string hostNameOrAddress) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "GetHostAddresses", hostNameOrAddress);
//
// demand Unrestricted DnsPermission for this call
//
s_DnsPermission.Demand();
if (hostNameOrAddress == null) {
throw new ArgumentNullException("hostNameOrAddress");
}
// See if it's an IP Address.
IPAddress address;
IPAddress[] addresses;
if (IPAddress.TryParse(hostNameOrAddress, out address))
{
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
throw new ArgumentException(SR.GetString(SR.net_invalid_ip_addr), "hostNameOrAddress");
}
addresses = new IPAddress[] { address };
}
else
{
// InternalGetHostByName works with IP addresses (and avoids a reverse-lookup), but we need
// explicit handling in order to do the ArgumentException and guarantee the behavior.
addresses = InternalGetHostByName(hostNameOrAddress, true).AddressList;
}
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "GetHostAddresses", addresses);
return addresses;
}
[HostProtection(ExternalThreading=true)]
public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback requestCallback, object stateObject) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "BeginGetHostEntry", hostNameOrAddress);
IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, false, true, true, true, requestCallback, stateObject);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "BeginGetHostEntry", asyncResult);
return asyncResult;
} // BeginResolve
[HostProtection(ExternalThreading=true)]
public static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback requestCallback, object stateObject) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "BeginGetHostEntry", address);
IAsyncResult asyncResult = HostResolutionBeginHelper(address, true, true, requestCallback, stateObject);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "BeginGetHostEntry", asyncResult);
return asyncResult;
} // BeginResolve
public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "EndGetHostEntry", asyncResult);
IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "EndGetHostEntry", ipHostEntry);
return ipHostEntry;
} // EndResolve()
[HostProtection(ExternalThreading=true)]
public static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback requestCallback, object state) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "BeginGetHostAddresses", hostNameOrAddress);
IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, true, true, true, true, requestCallback, state);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "BeginGetHostAddresses", asyncResult);
return asyncResult;
} // BeginResolve
public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult) {
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "EndGetHostAddresses", asyncResult);
IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "EndGetHostAddresses", ipHostEntry);
return ipHostEntry.AddressList;
} // EndResolveToAddresses
internal static IAsyncResult UnsafeBeginGetHostAddresses(string hostName, AsyncCallback requestCallback, object state)
{
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "UnsafeBeginGetHostAddresses", hostName);
IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, true, false, true, true, requestCallback, state);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "UnsafeBeginGetHostAddresses", asyncResult);
return asyncResult;
} // UnsafeBeginResolveToAddresses
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[HostProtection(ExternalThreading=true)]
[Obsolete("BeginResolve is obsoleted for this type, please use BeginGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IAsyncResult BeginResolve(string hostName, AsyncCallback requestCallback, object stateObject)
{
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "BeginResolve", hostName);
IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, false, true, false, false, requestCallback, stateObject);
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "BeginResolve", asyncResult);
return asyncResult;
} // BeginResolve
[Obsolete("EndResolve is obsoleted for this type, please use EndGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry EndResolve(IAsyncResult asyncResult)
{
if(Logging.On)Logging.Enter(Logging.Sockets, "DNS", "EndResolve", asyncResult);
IPHostEntry ipHostEntry;
try
{
ipHostEntry = HostResolutionEndHelper(asyncResult);
}
catch (SocketException ex)
{
IPAddress address = ((ResolveAsyncResult)asyncResult).address;
if (address == null)
throw; // BeginResolve was called with a HostName, not an IPAddress
if (Logging.On) Logging.PrintWarning(Logging.Sockets, "DNS", "DNS.EndResolve", ex.Message);
ipHostEntry = GetUnresolveAnswer(address);
}
if(Logging.On)Logging.Exit(Logging.Sockets, "DNS", "EndResolve", ipHostEntry);
return ipHostEntry;
} // EndResolve()
//************* Task-based async public methods *************************
[HostProtection(ExternalThreading = true)]
public static Task<IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress)
{
return Task<IPAddress[]>.Factory.FromAsync(BeginGetHostAddresses, EndGetHostAddresses, hostNameOrAddress, null);
}
[HostProtection(ExternalThreading = true)]
public static Task<IPHostEntry> GetHostEntryAsync(IPAddress address)
{
return Task<IPHostEntry>.Factory.FromAsync(BeginGetHostEntry, EndGetHostEntry, address, null);
}
[HostProtection(ExternalThreading = true)]
public static Task<IPHostEntry> GetHostEntryAsync(string hostNameOrAddress)
{
return Task<IPHostEntry>.Factory.FromAsync(BeginGetHostEntry, EndGetHostEntry, hostNameOrAddress, null);
}
private unsafe static IPHostEntry GetAddrInfo(string name) {
IPHostEntry hostEntry;
SocketError errorCode = TryGetAddrInfo(name, out hostEntry);
if (errorCode != SocketError.Success) {
throw new SocketException(errorCode);
}
return hostEntry;
}
//
// IPv6 Changes: Add getaddrinfo and getnameinfo methods.
//
private unsafe static SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo)
{
// gets the resolved name
return TryGetAddrInfo(name, AddressInfoHints.AI_CANONNAME, out hostinfo);
}
private unsafe static SocketError TryGetAddrInfo(string name, AddressInfoHints flags, out IPHostEntry hostinfo)
{
//
// Use SocketException here to show operation not supported
// if, by some nefarious means, this method is called on an
// unsupported platform.
//
#if FEATURE_PAL
throw new SocketException(SocketError.OperationNotSupported);
#else
SafeFreeAddrInfo root = null;
ArrayList addresses = new ArrayList();
string canonicalname = null;
AddressInfo hints = new AddressInfo();
hints.ai_flags = flags;
hints.ai_family = AddressFamily.Unspecified; // gets all address families
//
// Use try / finally so we always get a shot at freeaddrinfo
//
try {
SocketError errorCode = (SocketError)SafeFreeAddrInfo.GetAddrInfo(name, null, ref hints, out root);
if (errorCode != SocketError.Success) { // Should not throw, return mostly blank hostentry
hostinfo = new IPHostEntry();
hostinfo.HostName = name;
hostinfo.Aliases = new string[0];
hostinfo.AddressList = new IPAddress[0];
return errorCode;
}
AddressInfo* pAddressInfo = (AddressInfo*)root.DangerousGetHandle();
//
// Process the results
//
while (pAddressInfo!=null) {
SocketAddress sockaddr;
//
// Retrieve the canonical name for the host - only appears in the first AddressInfo
// entry in the returned array.
//
if (canonicalname==null && pAddressInfo->ai_canonname!=null) {
canonicalname = Marshal.PtrToStringUni((IntPtr)pAddressInfo->ai_canonname);
}
//
// Only process IPv4 or IPv6 Addresses. Note that it's unlikely that we'll
// ever get any other address families, but better to be safe than sorry.
// We also filter based on whether IPv6 is supported on the current
// platform / machine.
//
if ( ( pAddressInfo->ai_family == AddressFamily.InterNetwork ) || // Never filter v4
(pAddressInfo->ai_family == AddressFamily.InterNetworkV6 && Socket.OSSupportsIPv6))
{
sockaddr = new SocketAddress(pAddressInfo->ai_family, pAddressInfo->ai_addrlen);
//
// Push address data into the socket address buffer
//
for (int d = 0; d < pAddressInfo->ai_addrlen; d++) {
sockaddr.m_Buffer[d] = *(pAddressInfo->ai_addr + d);
}
//
// NOTE: We need an IPAddress now, the only way to create it from a
// SocketAddress is via IPEndPoint. This ought to be simpler.
//
if ( pAddressInfo->ai_family == AddressFamily.InterNetwork ) {
addresses.Add( ((IPEndPoint)IPEndPoint.Any.Create(sockaddr)).Address );
}
else {
addresses.Add( ((IPEndPoint)IPEndPoint.IPv6Any.Create(sockaddr)).Address );
}
}
//
// Next addressinfo entry
//
pAddressInfo = pAddressInfo->ai_next;
}
}
finally {
if (root != null) {
root.Close();
}
}
//
// Finally, put together the IPHostEntry
//
hostinfo = new IPHostEntry();
hostinfo.HostName = canonicalname!=null ? canonicalname : name;
hostinfo.Aliases = new string[0];
hostinfo.AddressList = new IPAddress[addresses.Count];
addresses.CopyTo(hostinfo.AddressList);
return SocketError.Success;
#endif // FEATURE_PAL
}
internal static string TryGetNameInfo(IPAddress addr, out SocketError errorCode) {
//
// Use SocketException here to show operation not supported
// if, by some nefarious means, this method is called on an
// unsupported platform.
//
#if FEATURE_PAL
throw new SocketException(SocketError.OperationNotSupported);
#else
SocketAddress address = (new IPEndPoint(addr,0)).Serialize();
StringBuilder hostname = new StringBuilder(1025); // NI_MAXHOST
int flags = (int)NameInfoFlags.NI_NAMEREQD;
Socket.InitializeSockets();
errorCode =
UnsafeNclNativeMethods.OSSOCK.GetNameInfoW(
address.m_Buffer,
address.m_Size,
hostname,
hostname.Capacity,
null, // We don't want a service name
0, // so no need for buffer or length
flags);
if (errorCode!=SocketError.Success) {
return null;
}
return hostname.ToString();
#endif // FEATURE_PAL
}
}
}
| |
// 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.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
using ASM_CACHE = GlobalAssemblyCacheLocation.ASM_CACHE;
/// <summary>
/// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache.
/// </summary>
internal sealed class ClrGlobalAssemblyCache : GlobalAssemblyCache
{
#region Interop
private const int MAX_PATH = 260;
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")]
private interface IAssemblyEnum
{
[PreserveSig]
int GetNextAssembly(out FusionAssemblyIdentity.IApplicationContext ppAppCtx, out FusionAssemblyIdentity.IAssemblyName ppName, uint dwFlags);
[PreserveSig]
int Reset();
[PreserveSig]
int Clone(out IAssemblyEnum ppEnum);
}
[ComImport, Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IAssemblyCache
{
void UninstallAssembly();
void QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref ASSEMBLY_INFO pAsmInfo);
void CreateAssemblyCacheItem();
void CreateAssemblyScavenger();
void InstallAssembly();
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct ASSEMBLY_INFO
{
public uint cbAssemblyInfo;
public readonly uint dwAssemblyFlags;
public readonly ulong uliAssemblySizeInKB;
public char* pszCurrentAssemblyPathBuf;
public uint cchBuf;
}
[DllImport("clr", PreserveSig = true)]
private static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, FusionAssemblyIdentity.IApplicationContext pAppCtx, FusionAssemblyIdentity.IAssemblyName pName, ASM_CACHE dwFlags, IntPtr pvReserved);
[DllImport("clr", PreserveSig = false)]
private static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved);
#endregion
/// <summary>
/// Enumerates assemblies in the GAC returning those that match given partial name and
/// architecture.
/// </summary>
/// <param name="partialName">Optional partial name.</param>
/// <param name="architectureFilter">Optional architecture filter.</param>
public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(AssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>))
{
return GetAssemblyIdentities(FusionAssemblyIdentity.ToAssemblyNameObject(partialName), architectureFilter);
}
/// <summary>
/// Enumerates assemblies in the GAC returning those that match given partial name and
/// architecture.
/// </summary>
/// <param name="partialName">The optional partial name.</param>
/// <param name="architectureFilter">The optional architecture filter.</param>
public override IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName = null, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>))
{
FusionAssemblyIdentity.IAssemblyName nameObj;
if (partialName != null)
{
nameObj = FusionAssemblyIdentity.ToAssemblyNameObject(partialName);
if (nameObj == null)
{
return SpecializedCollections.EmptyEnumerable<AssemblyIdentity>();
}
}
else
{
nameObj = null;
}
return GetAssemblyIdentities(nameObj, architectureFilter);
}
/// <summary>
/// Enumerates assemblies in the GAC returning their simple names.
/// </summary>
/// <param name="architectureFilter">Optional architecture filter.</param>
/// <returns>Unique simple names of GAC assemblies.</returns>
public override IEnumerable<string> GetAssemblySimpleNames(ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>))
{
var q = from nameObject in GetAssemblyObjects(partialNameFilter: null, architectureFilter: architectureFilter)
select FusionAssemblyIdentity.GetName(nameObject);
return q.Distinct();
}
private static IEnumerable<AssemblyIdentity> GetAssemblyIdentities(
FusionAssemblyIdentity.IAssemblyName partialName,
ImmutableArray<ProcessorArchitecture> architectureFilter)
{
return from nameObject in GetAssemblyObjects(partialName, architectureFilter)
select FusionAssemblyIdentity.ToAssemblyIdentity(nameObject);
}
private const int S_OK = 0;
private const int S_FALSE = 1;
// Internal for testing.
internal static IEnumerable<FusionAssemblyIdentity.IAssemblyName> GetAssemblyObjects(
FusionAssemblyIdentity.IAssemblyName partialNameFilter,
ImmutableArray<ProcessorArchitecture> architectureFilter)
{
IAssemblyEnum enumerator;
FusionAssemblyIdentity.IApplicationContext applicationContext = null;
int hr = CreateAssemblyEnum(out enumerator, applicationContext, partialNameFilter, ASM_CACHE.GAC, IntPtr.Zero);
if (hr == S_FALSE)
{
// no assembly found
yield break;
}
else if (hr != S_OK)
{
Exception e = Marshal.GetExceptionForHR(hr);
if (e is FileNotFoundException || e is DirectoryNotFoundException)
{
// invalid assembly name:
yield break;
}
else if (e != null)
{
throw e;
}
else
{
// for some reason it might happen that CreateAssemblyEnum returns non-zero HR that doesn't correspond to any exception:
#if SCRIPTING
throw new ArgumentException(Microsoft.CodeAnalysis.Scripting.ScriptingResources.InvalidAssemblyName);
#else
throw new ArgumentException(Microsoft.CodeAnalysis.WorkspaceDesktopResources.Invalid_assembly_name);
#endif
}
}
while (true)
{
FusionAssemblyIdentity.IAssemblyName nameObject;
hr = enumerator.GetNextAssembly(out applicationContext, out nameObject, 0);
if (hr != 0)
{
if (hr < 0)
{
Marshal.ThrowExceptionForHR(hr);
}
break;
}
if (!architectureFilter.IsDefault)
{
var assemblyArchitecture = FusionAssemblyIdentity.GetProcessorArchitecture(nameObject);
if (!architectureFilter.Contains(assemblyArchitecture))
{
continue;
}
}
yield return nameObject;
}
}
public override AssemblyIdentity ResolvePartialName(
string displayName,
out string location,
ImmutableArray<ProcessorArchitecture> architectureFilter,
CultureInfo preferredCulture)
{
if (displayName == null)
{
throw new ArgumentNullException(nameof(displayName));
}
location = null;
FusionAssemblyIdentity.IAssemblyName nameObject = FusionAssemblyIdentity.ToAssemblyNameObject(displayName);
if (nameObject == null)
{
return null;
}
var candidates = GetAssemblyObjects(nameObject, architectureFilter);
string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null;
var bestMatch = FusionAssemblyIdentity.GetBestMatch(candidates, cultureName);
if (bestMatch == null)
{
return null;
}
location = GetAssemblyLocation(bestMatch);
return FusionAssemblyIdentity.ToAssemblyIdentity(bestMatch);
}
internal static unsafe string GetAssemblyLocation(FusionAssemblyIdentity.IAssemblyName nameObject)
{
// NAME | VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE
string fullName = FusionAssemblyIdentity.GetDisplayName(nameObject, FusionAssemblyIdentity.ASM_DISPLAYF.FULL);
fixed (char* p = new char[MAX_PATH])
{
ASSEMBLY_INFO info = new ASSEMBLY_INFO
{
cbAssemblyInfo = (uint)Marshal.SizeOf<ASSEMBLY_INFO>(),
pszCurrentAssemblyPathBuf = p,
cchBuf = MAX_PATH
};
IAssemblyCache assemblyCacheObject;
CreateAssemblyCache(out assemblyCacheObject, 0);
assemblyCacheObject.QueryAssemblyInfo(0, fullName, ref info);
Debug.Assert(info.pszCurrentAssemblyPathBuf != null);
Debug.Assert(info.pszCurrentAssemblyPathBuf[info.cchBuf - 1] == '\0');
var result = Marshal.PtrToStringUni((IntPtr)info.pszCurrentAssemblyPathBuf, (int)info.cchBuf - 1);
Debug.Assert(result.IndexOf('\0') == -1);
return result;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.